PackageManagerService.java revision 0d1fd8d09163566d2c7eb72037f63b6404ada642
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_ANY_USER;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
69import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
70import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
71import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
72import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
73import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
74import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
75import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
76import static android.content.pm.PackageManager.PERMISSION_DENIED;
77import static android.content.pm.PackageManager.PERMISSION_GRANTED;
78import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
79import static android.content.pm.PackageParser.isApkFile;
80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
81import static android.system.OsConstants.O_CREAT;
82import static android.system.OsConstants.O_RDWR;
83
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
88import static com.android.internal.util.ArrayUtils.appendInt;
89import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.annotation.UserIdInt;
106import android.app.ActivityManager;
107import android.app.AppOpsManager;
108import android.app.IActivityManager;
109import android.app.ResourcesManager;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.ContentResolver;
116import android.content.Context;
117import android.content.IIntentReceiver;
118import android.content.Intent;
119import android.content.IntentFilter;
120import android.content.IntentSender;
121import android.content.IntentSender.SendIntentException;
122import android.content.ServiceConnection;
123import android.content.pm.ActivityInfo;
124import android.content.pm.ApplicationInfo;
125import android.content.pm.AppsQueryHelper;
126import android.content.pm.ComponentInfo;
127import android.content.pm.EphemeralApplicationInfo;
128import android.content.pm.EphemeralRequest;
129import android.content.pm.EphemeralResolveInfo;
130import android.content.pm.EphemeralResponse;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstrumentationInfo;
142import android.content.pm.IntentFilterVerificationInfo;
143import android.content.pm.KeySet;
144import android.content.pm.PackageCleanItem;
145import android.content.pm.PackageInfo;
146import android.content.pm.PackageInfoLite;
147import android.content.pm.PackageInstaller;
148import android.content.pm.PackageManager;
149import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
150import android.content.pm.PackageManagerInternal;
151import android.content.pm.PackageParser;
152import android.content.pm.PackageParser.ActivityIntentInfo;
153import android.content.pm.PackageParser.PackageLite;
154import android.content.pm.PackageParser.PackageParserException;
155import android.content.pm.PackageStats;
156import android.content.pm.PackageUserState;
157import android.content.pm.ParceledListSlice;
158import android.content.pm.PermissionGroupInfo;
159import android.content.pm.PermissionInfo;
160import android.content.pm.ProviderInfo;
161import android.content.pm.ResolveInfo;
162import android.content.pm.ServiceInfo;
163import android.content.pm.Signature;
164import android.content.pm.UserInfo;
165import android.content.pm.VerifierDeviceIdentity;
166import android.content.pm.VerifierInfo;
167import android.content.res.Resources;
168import android.graphics.Bitmap;
169import android.hardware.display.DisplayManager;
170import android.net.Uri;
171import android.os.Binder;
172import android.os.Build;
173import android.os.Bundle;
174import android.os.Debug;
175import android.os.Environment;
176import android.os.Environment.UserEnvironment;
177import android.os.FileUtils;
178import android.os.Handler;
179import android.os.IBinder;
180import android.os.Looper;
181import android.os.Message;
182import android.os.Parcel;
183import android.os.ParcelFileDescriptor;
184import android.os.PatternMatcher;
185import android.os.Process;
186import android.os.RemoteCallbackList;
187import android.os.RemoteException;
188import android.os.ResultReceiver;
189import android.os.SELinux;
190import android.os.ServiceManager;
191import android.os.ShellCallback;
192import android.os.SystemClock;
193import android.os.SystemProperties;
194import android.os.Trace;
195import android.os.UserHandle;
196import android.os.UserManager;
197import android.os.UserManagerInternal;
198import android.os.storage.IStorageManager;
199import android.os.storage.StorageManagerInternal;
200import android.os.storage.StorageEventListener;
201import android.os.storage.StorageManager;
202import android.os.storage.VolumeInfo;
203import android.os.storage.VolumeRecord;
204import android.provider.Settings.Global;
205import android.provider.Settings.Secure;
206import android.security.KeyStore;
207import android.security.SystemKeyStore;
208import android.system.ErrnoException;
209import android.system.Os;
210import android.text.TextUtils;
211import android.text.format.DateUtils;
212import android.util.ArrayMap;
213import android.util.ArraySet;
214import android.util.Base64;
215import android.util.DisplayMetrics;
216import android.util.EventLog;
217import android.util.ExceptionUtils;
218import android.util.Log;
219import android.util.LogPrinter;
220import android.util.MathUtils;
221import android.util.Pair;
222import android.util.PrintStreamPrinter;
223import android.util.Slog;
224import android.util.SparseArray;
225import android.util.SparseBooleanArray;
226import android.util.SparseIntArray;
227import android.util.Xml;
228import android.util.jar.StrictJarFile;
229import android.view.Display;
230
231import com.android.internal.R;
232import com.android.internal.annotations.GuardedBy;
233import com.android.internal.app.IMediaContainerService;
234import com.android.internal.app.ResolverActivity;
235import com.android.internal.content.NativeLibraryHelper;
236import com.android.internal.content.PackageHelper;
237import com.android.internal.logging.MetricsLogger;
238import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
239import com.android.internal.os.IParcelFileDescriptorFactory;
240import com.android.internal.os.InstallerConnection.InstallerException;
241import com.android.internal.os.RoSystemProperties;
242import com.android.internal.os.SomeArgs;
243import com.android.internal.os.Zygote;
244import com.android.internal.telephony.CarrierAppUtils;
245import com.android.internal.util.ArrayUtils;
246import com.android.internal.util.FastPrintWriter;
247import com.android.internal.util.FastXmlSerializer;
248import com.android.internal.util.IndentingPrintWriter;
249import com.android.internal.util.Preconditions;
250import com.android.internal.util.XmlUtils;
251import com.android.server.AttributeCache;
252import com.android.server.EventLogTags;
253import com.android.server.FgThread;
254import com.android.server.IntentResolver;
255import com.android.server.LocalServices;
256import com.android.server.ServiceThread;
257import com.android.server.SystemConfig;
258import com.android.server.Watchdog;
259import com.android.server.net.NetworkPolicyManagerInternal;
260import com.android.server.pm.PermissionsState.PermissionState;
261import com.android.server.pm.Settings.DatabaseVersion;
262import com.android.server.pm.Settings.VersionInfo;
263import com.android.server.storage.DeviceStorageMonitorInternal;
264
265import dalvik.system.CloseGuard;
266import dalvik.system.DexFile;
267import dalvik.system.VMRuntime;
268
269import libcore.io.IoUtils;
270import libcore.util.EmptyArray;
271
272import org.xmlpull.v1.XmlPullParser;
273import org.xmlpull.v1.XmlPullParserException;
274import org.xmlpull.v1.XmlSerializer;
275
276import java.io.BufferedOutputStream;
277import java.io.BufferedReader;
278import java.io.ByteArrayInputStream;
279import java.io.ByteArrayOutputStream;
280import java.io.File;
281import java.io.FileDescriptor;
282import java.io.FileInputStream;
283import java.io.FileNotFoundException;
284import java.io.FileOutputStream;
285import java.io.FileReader;
286import java.io.FilenameFilter;
287import java.io.IOException;
288import java.io.PrintWriter;
289import java.nio.charset.StandardCharsets;
290import java.security.DigestInputStream;
291import java.security.MessageDigest;
292import java.security.NoSuchAlgorithmException;
293import java.security.PublicKey;
294import java.security.SecureRandom;
295import java.security.cert.Certificate;
296import java.security.cert.CertificateEncodingException;
297import java.security.cert.CertificateException;
298import java.text.SimpleDateFormat;
299import java.util.ArrayList;
300import java.util.Arrays;
301import java.util.Collection;
302import java.util.Collections;
303import java.util.Comparator;
304import java.util.Date;
305import java.util.HashSet;
306import java.util.Iterator;
307import java.util.List;
308import java.util.Map;
309import java.util.Objects;
310import java.util.Set;
311import java.util.concurrent.CountDownLatch;
312import java.util.concurrent.TimeUnit;
313import java.util.concurrent.atomic.AtomicBoolean;
314import java.util.concurrent.atomic.AtomicInteger;
315
316/**
317 * Keep track of all those APKs everywhere.
318 * <p>
319 * Internally there are two important locks:
320 * <ul>
321 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
322 * and other related state. It is a fine-grained lock that should only be held
323 * momentarily, as it's one of the most contended locks in the system.
324 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
325 * operations typically involve heavy lifting of application data on disk. Since
326 * {@code installd} is single-threaded, and it's operations can often be slow,
327 * this lock should never be acquired while already holding {@link #mPackages}.
328 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
329 * holding {@link #mInstallLock}.
330 * </ul>
331 * Many internal methods rely on the caller to hold the appropriate locks, and
332 * this contract is expressed through method name suffixes:
333 * <ul>
334 * <li>fooLI(): the caller must hold {@link #mInstallLock}
335 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
336 * being modified must be frozen
337 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
338 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
339 * </ul>
340 * <p>
341 * Because this class is very central to the platform's security; please run all
342 * CTS and unit tests whenever making modifications:
343 *
344 * <pre>
345 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
346 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
347 * </pre>
348 */
349public class PackageManagerService extends IPackageManager.Stub {
350    static final String TAG = "PackageManager";
351    static final boolean DEBUG_SETTINGS = false;
352    static final boolean DEBUG_PREFERRED = false;
353    static final boolean DEBUG_UPGRADE = false;
354    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
355    private static final boolean DEBUG_BACKUP = false;
356    private static final boolean DEBUG_INSTALL = false;
357    private static final boolean DEBUG_REMOVE = false;
358    private static final boolean DEBUG_BROADCASTS = false;
359    private static final boolean DEBUG_SHOW_INFO = false;
360    private static final boolean DEBUG_PACKAGE_INFO = false;
361    private static final boolean DEBUG_INTENT_MATCHING = false;
362    private static final boolean DEBUG_PACKAGE_SCANNING = false;
363    private static final boolean DEBUG_VERIFY = false;
364    private static final boolean DEBUG_FILTERS = false;
365
366    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
367    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
368    // user, but by default initialize to this.
369    static final boolean DEBUG_DEXOPT = false;
370
371    private static final boolean DEBUG_ABI_SELECTION = false;
372    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
373    private static final boolean DEBUG_TRIAGED_MISSING = false;
374    private static final boolean DEBUG_APP_DATA = false;
375
376    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
377    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
378
379    private static final boolean DISABLE_EPHEMERAL_APPS = false;
380    private static final boolean HIDE_EPHEMERAL_APIS = true;
381
382    private static final int RADIO_UID = Process.PHONE_UID;
383    private static final int LOG_UID = Process.LOG_UID;
384    private static final int NFC_UID = Process.NFC_UID;
385    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
386    private static final int SHELL_UID = Process.SHELL_UID;
387
388    // Cap the size of permission trees that 3rd party apps can define
389    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
390
391    // Suffix used during package installation when copying/moving
392    // package apks to install directory.
393    private static final String INSTALL_PACKAGE_SUFFIX = "-";
394
395    static final int SCAN_NO_DEX = 1<<1;
396    static final int SCAN_FORCE_DEX = 1<<2;
397    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
398    static final int SCAN_NEW_INSTALL = 1<<4;
399    static final int SCAN_UPDATE_TIME = 1<<5;
400    static final int SCAN_BOOTING = 1<<6;
401    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
402    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
403    static final int SCAN_REPLACING = 1<<9;
404    static final int SCAN_REQUIRE_KNOWN = 1<<10;
405    static final int SCAN_MOVE = 1<<11;
406    static final int SCAN_INITIAL = 1<<12;
407    static final int SCAN_CHECK_ONLY = 1<<13;
408    static final int SCAN_DONT_KILL_APP = 1<<14;
409    static final int SCAN_IGNORE_FROZEN = 1<<15;
410    static final int REMOVE_CHATTY = 1<<16;
411    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
412
413    private static final int[] EMPTY_INT_ARRAY = new int[0];
414
415    /**
416     * Timeout (in milliseconds) after which the watchdog should declare that
417     * our handler thread is wedged.  The usual default for such things is one
418     * minute but we sometimes do very lengthy I/O operations on this thread,
419     * such as installing multi-gigabyte applications, so ours needs to be longer.
420     */
421    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
422
423    /**
424     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
425     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
426     * settings entry if available, otherwise we use the hardcoded default.  If it's been
427     * more than this long since the last fstrim, we force one during the boot sequence.
428     *
429     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
430     * one gets run at the next available charging+idle time.  This final mandatory
431     * no-fstrim check kicks in only of the other scheduling criteria is never met.
432     */
433    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
434
435    /**
436     * Whether verification is enabled by default.
437     */
438    private static final boolean DEFAULT_VERIFY_ENABLE = true;
439
440    /**
441     * The default maximum time to wait for the verification agent to return in
442     * milliseconds.
443     */
444    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
445
446    /**
447     * The default response for package verification timeout.
448     *
449     * This can be either PackageManager.VERIFICATION_ALLOW or
450     * PackageManager.VERIFICATION_REJECT.
451     */
452    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
453
454    static final String PLATFORM_PACKAGE_NAME = "android";
455
456    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
457
458    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
459            DEFAULT_CONTAINER_PACKAGE,
460            "com.android.defcontainer.DefaultContainerService");
461
462    private static final String KILL_APP_REASON_GIDS_CHANGED =
463            "permission grant or revoke changed gids";
464
465    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
466            "permissions revoked";
467
468    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
469
470    private static final String PACKAGE_SCHEME = "package";
471
472    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
473    /**
474     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
475     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
476     * VENDOR_OVERLAY_DIR.
477     */
478    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
479    /**
480     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
481     * is in VENDOR_OVERLAY_THEME_PROPERTY.
482     */
483    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
484            = "persist.vendor.overlay.theme";
485
486    /** Permission grant: not grant the permission. */
487    private static final int GRANT_DENIED = 1;
488
489    /** Permission grant: grant the permission as an install permission. */
490    private static final int GRANT_INSTALL = 2;
491
492    /** Permission grant: grant the permission as a runtime one. */
493    private static final int GRANT_RUNTIME = 3;
494
495    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
496    private static final int GRANT_UPGRADE = 4;
497
498    /** Canonical intent used to identify what counts as a "web browser" app */
499    private static final Intent sBrowserIntent;
500    static {
501        sBrowserIntent = new Intent();
502        sBrowserIntent.setAction(Intent.ACTION_VIEW);
503        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
504        sBrowserIntent.setData(Uri.parse("http:"));
505    }
506
507    /**
508     * The set of all protected actions [i.e. those actions for which a high priority
509     * intent filter is disallowed].
510     */
511    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
512    static {
513        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
514        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
515        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
516        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
517    }
518
519    // Compilation reasons.
520    public static final int REASON_FIRST_BOOT = 0;
521    public static final int REASON_BOOT = 1;
522    public static final int REASON_INSTALL = 2;
523    public static final int REASON_BACKGROUND_DEXOPT = 3;
524    public static final int REASON_AB_OTA = 4;
525    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
526    public static final int REASON_SHARED_APK = 6;
527    public static final int REASON_FORCED_DEXOPT = 7;
528    public static final int REASON_CORE_APP = 8;
529
530    public static final int REASON_LAST = REASON_CORE_APP;
531
532    /** Special library name that skips shared libraries check during compilation. */
533    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
534
535    /** All dangerous permission names in the same order as the events in MetricsEvent */
536    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
537            Manifest.permission.READ_CALENDAR,
538            Manifest.permission.WRITE_CALENDAR,
539            Manifest.permission.CAMERA,
540            Manifest.permission.READ_CONTACTS,
541            Manifest.permission.WRITE_CONTACTS,
542            Manifest.permission.GET_ACCOUNTS,
543            Manifest.permission.ACCESS_FINE_LOCATION,
544            Manifest.permission.ACCESS_COARSE_LOCATION,
545            Manifest.permission.RECORD_AUDIO,
546            Manifest.permission.READ_PHONE_STATE,
547            Manifest.permission.CALL_PHONE,
548            Manifest.permission.READ_CALL_LOG,
549            Manifest.permission.WRITE_CALL_LOG,
550            Manifest.permission.ADD_VOICEMAIL,
551            Manifest.permission.USE_SIP,
552            Manifest.permission.PROCESS_OUTGOING_CALLS,
553            Manifest.permission.READ_CELL_BROADCASTS,
554            Manifest.permission.BODY_SENSORS,
555            Manifest.permission.SEND_SMS,
556            Manifest.permission.RECEIVE_SMS,
557            Manifest.permission.READ_SMS,
558            Manifest.permission.RECEIVE_WAP_PUSH,
559            Manifest.permission.RECEIVE_MMS,
560            Manifest.permission.READ_EXTERNAL_STORAGE,
561            Manifest.permission.WRITE_EXTERNAL_STORAGE);
562
563    final ServiceThread mHandlerThread;
564
565    final PackageHandler mHandler;
566
567    private final ProcessLoggingHandler mProcessLoggingHandler;
568
569    /**
570     * Messages for {@link #mHandler} that need to wait for system ready before
571     * being dispatched.
572     */
573    private ArrayList<Message> mPostSystemReadyMessages;
574
575    final int mSdkVersion = Build.VERSION.SDK_INT;
576
577    final Context mContext;
578    final boolean mFactoryTest;
579    final boolean mOnlyCore;
580    final DisplayMetrics mMetrics;
581    final int mDefParseFlags;
582    final String[] mSeparateProcesses;
583    final boolean mIsUpgrade;
584    final boolean mIsPreNUpgrade;
585    final boolean mIsPreNMR1Upgrade;
586
587    @GuardedBy("mPackages")
588    private boolean mDexOptDialogShown;
589
590    /** The location for ASEC container files on internal storage. */
591    final String mAsecInternalPath;
592
593    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
594    // LOCK HELD.  Can be called with mInstallLock held.
595    @GuardedBy("mInstallLock")
596    final Installer mInstaller;
597
598    /** Directory where installed third-party apps stored */
599    final File mAppInstallDir;
600    final File mEphemeralInstallDir;
601
602    /**
603     * Directory to which applications installed internally have their
604     * 32 bit native libraries copied.
605     */
606    private File mAppLib32InstallDir;
607
608    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
609    // apps.
610    final File mDrmAppPrivateInstallDir;
611
612    // ----------------------------------------------------------------
613
614    // Lock for state used when installing and doing other long running
615    // operations.  Methods that must be called with this lock held have
616    // the suffix "LI".
617    final Object mInstallLock = new Object();
618
619    // ----------------------------------------------------------------
620
621    // Keys are String (package name), values are Package.  This also serves
622    // as the lock for the global state.  Methods that must be called with
623    // this lock held have the prefix "LP".
624    @GuardedBy("mPackages")
625    final ArrayMap<String, PackageParser.Package> mPackages =
626            new ArrayMap<String, PackageParser.Package>();
627
628    final ArrayMap<String, Set<String>> mKnownCodebase =
629            new ArrayMap<String, Set<String>>();
630
631    // Tracks available target package names -> overlay package paths.
632    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
633        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
634
635    /**
636     * Tracks new system packages [received in an OTA] that we expect to
637     * find updated user-installed versions. Keys are package name, values
638     * are package location.
639     */
640    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
641    /**
642     * Tracks high priority intent filters for protected actions. During boot, certain
643     * filter actions are protected and should never be allowed to have a high priority
644     * intent filter for them. However, there is one, and only one exception -- the
645     * setup wizard. It must be able to define a high priority intent filter for these
646     * actions to ensure there are no escapes from the wizard. We need to delay processing
647     * of these during boot as we need to look at all of the system packages in order
648     * to know which component is the setup wizard.
649     */
650    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
651    /**
652     * Whether or not processing protected filters should be deferred.
653     */
654    private boolean mDeferProtectedFilters = true;
655
656    /**
657     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
658     */
659    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
660    /**
661     * Whether or not system app permissions should be promoted from install to runtime.
662     */
663    boolean mPromoteSystemApps;
664
665    @GuardedBy("mPackages")
666    final Settings mSettings;
667
668    /**
669     * Set of package names that are currently "frozen", which means active
670     * surgery is being done on the code/data for that package. The platform
671     * will refuse to launch frozen packages to avoid race conditions.
672     *
673     * @see PackageFreezer
674     */
675    @GuardedBy("mPackages")
676    final ArraySet<String> mFrozenPackages = new ArraySet<>();
677
678    final ProtectedPackages mProtectedPackages;
679
680    boolean mFirstBoot;
681
682    // System configuration read by SystemConfig.
683    final int[] mGlobalGids;
684    final SparseArray<ArraySet<String>> mSystemPermissions;
685    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
686
687    // If mac_permissions.xml was found for seinfo labeling.
688    boolean mFoundPolicyFile;
689
690    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
691
692    public static final class SharedLibraryEntry {
693        public final String path;
694        public final String apk;
695
696        SharedLibraryEntry(String _path, String _apk) {
697            path = _path;
698            apk = _apk;
699        }
700    }
701
702    // Currently known shared libraries.
703    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
704            new ArrayMap<String, SharedLibraryEntry>();
705
706    // All available activities, for your resolving pleasure.
707    final ActivityIntentResolver mActivities =
708            new ActivityIntentResolver();
709
710    // All available receivers, for your resolving pleasure.
711    final ActivityIntentResolver mReceivers =
712            new ActivityIntentResolver();
713
714    // All available services, for your resolving pleasure.
715    final ServiceIntentResolver mServices = new ServiceIntentResolver();
716
717    // All available providers, for your resolving pleasure.
718    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
719
720    // Mapping from provider base names (first directory in content URI codePath)
721    // to the provider information.
722    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
723            new ArrayMap<String, PackageParser.Provider>();
724
725    // Mapping from instrumentation class names to info about them.
726    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
727            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
728
729    // Mapping from permission names to info about them.
730    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
731            new ArrayMap<String, PackageParser.PermissionGroup>();
732
733    // Packages whose data we have transfered into another package, thus
734    // should no longer exist.
735    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
736
737    // Broadcast actions that are only available to the system.
738    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
739
740    /** List of packages waiting for verification. */
741    final SparseArray<PackageVerificationState> mPendingVerification
742            = new SparseArray<PackageVerificationState>();
743
744    /** Set of packages associated with each app op permission. */
745    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
746
747    final PackageInstallerService mInstallerService;
748
749    private final PackageDexOptimizer mPackageDexOptimizer;
750
751    private AtomicInteger mNextMoveId = new AtomicInteger();
752    private final MoveCallbacks mMoveCallbacks;
753
754    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
755
756    // Cache of users who need badging.
757    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
758
759    /** Token for keys in mPendingVerification. */
760    private int mPendingVerificationToken = 0;
761
762    volatile boolean mSystemReady;
763    volatile boolean mSafeMode;
764    volatile boolean mHasSystemUidErrors;
765
766    ApplicationInfo mAndroidApplication;
767    final ActivityInfo mResolveActivity = new ActivityInfo();
768    final ResolveInfo mResolveInfo = new ResolveInfo();
769    ComponentName mResolveComponentName;
770    PackageParser.Package mPlatformPackage;
771    ComponentName mCustomResolverComponentName;
772
773    boolean mResolverReplaced = false;
774
775    private final @Nullable ComponentName mIntentFilterVerifierComponent;
776    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
777
778    private int mIntentFilterVerificationToken = 0;
779
780    /** The service connection to the ephemeral resolver */
781    final EphemeralResolverConnection mEphemeralResolverConnection;
782
783    /** Component used to install ephemeral applications */
784    ComponentName mEphemeralInstallerComponent;
785    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
786    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
787
788    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
789            = new SparseArray<IntentFilterVerificationState>();
790
791    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
792
793    // List of packages names to keep cached, even if they are uninstalled for all users
794    private List<String> mKeepUninstalledPackages;
795
796    private UserManagerInternal mUserManagerInternal;
797
798    private static class IFVerificationParams {
799        PackageParser.Package pkg;
800        boolean replacing;
801        int userId;
802        int verifierUid;
803
804        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
805                int _userId, int _verifierUid) {
806            pkg = _pkg;
807            replacing = _replacing;
808            userId = _userId;
809            replacing = _replacing;
810            verifierUid = _verifierUid;
811        }
812    }
813
814    private interface IntentFilterVerifier<T extends IntentFilter> {
815        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
816                                               T filter, String packageName);
817        void startVerifications(int userId);
818        void receiveVerificationResponse(int verificationId);
819    }
820
821    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
822        private Context mContext;
823        private ComponentName mIntentFilterVerifierComponent;
824        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
825
826        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
827            mContext = context;
828            mIntentFilterVerifierComponent = verifierComponent;
829        }
830
831        private String getDefaultScheme() {
832            return IntentFilter.SCHEME_HTTPS;
833        }
834
835        @Override
836        public void startVerifications(int userId) {
837            // Launch verifications requests
838            int count = mCurrentIntentFilterVerifications.size();
839            for (int n=0; n<count; n++) {
840                int verificationId = mCurrentIntentFilterVerifications.get(n);
841                final IntentFilterVerificationState ivs =
842                        mIntentFilterVerificationStates.get(verificationId);
843
844                String packageName = ivs.getPackageName();
845
846                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
847                final int filterCount = filters.size();
848                ArraySet<String> domainsSet = new ArraySet<>();
849                for (int m=0; m<filterCount; m++) {
850                    PackageParser.ActivityIntentInfo filter = filters.get(m);
851                    domainsSet.addAll(filter.getHostsList());
852                }
853                synchronized (mPackages) {
854                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
855                            packageName, domainsSet) != null) {
856                        scheduleWriteSettingsLocked();
857                    }
858                }
859                sendVerificationRequest(userId, verificationId, ivs);
860            }
861            mCurrentIntentFilterVerifications.clear();
862        }
863
864        private void sendVerificationRequest(int userId, int verificationId,
865                IntentFilterVerificationState ivs) {
866
867            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
868            verificationIntent.putExtra(
869                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
870                    verificationId);
871            verificationIntent.putExtra(
872                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
873                    getDefaultScheme());
874            verificationIntent.putExtra(
875                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
876                    ivs.getHostsString());
877            verificationIntent.putExtra(
878                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
879                    ivs.getPackageName());
880            verificationIntent.setComponent(mIntentFilterVerifierComponent);
881            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
882
883            UserHandle user = new UserHandle(userId);
884            mContext.sendBroadcastAsUser(verificationIntent, user);
885            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
886                    "Sending IntentFilter verification broadcast");
887        }
888
889        public void receiveVerificationResponse(int verificationId) {
890            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
891
892            final boolean verified = ivs.isVerified();
893
894            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
895            final int count = filters.size();
896            if (DEBUG_DOMAIN_VERIFICATION) {
897                Slog.i(TAG, "Received verification response " + verificationId
898                        + " for " + count + " filters, verified=" + verified);
899            }
900            for (int n=0; n<count; n++) {
901                PackageParser.ActivityIntentInfo filter = filters.get(n);
902                filter.setVerified(verified);
903
904                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
905                        + " verified with result:" + verified + " and hosts:"
906                        + ivs.getHostsString());
907            }
908
909            mIntentFilterVerificationStates.remove(verificationId);
910
911            final String packageName = ivs.getPackageName();
912            IntentFilterVerificationInfo ivi = null;
913
914            synchronized (mPackages) {
915                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
916            }
917            if (ivi == null) {
918                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
919                        + verificationId + " packageName:" + packageName);
920                return;
921            }
922            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
923                    "Updating IntentFilterVerificationInfo for package " + packageName
924                            +" verificationId:" + verificationId);
925
926            synchronized (mPackages) {
927                if (verified) {
928                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
929                } else {
930                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
931                }
932                scheduleWriteSettingsLocked();
933
934                final int userId = ivs.getUserId();
935                if (userId != UserHandle.USER_ALL) {
936                    final int userStatus =
937                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
938
939                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
940                    boolean needUpdate = false;
941
942                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
943                    // already been set by the User thru the Disambiguation dialog
944                    switch (userStatus) {
945                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
946                            if (verified) {
947                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
948                            } else {
949                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
950                            }
951                            needUpdate = true;
952                            break;
953
954                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
955                            if (verified) {
956                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
957                                needUpdate = true;
958                            }
959                            break;
960
961                        default:
962                            // Nothing to do
963                    }
964
965                    if (needUpdate) {
966                        mSettings.updateIntentFilterVerificationStatusLPw(
967                                packageName, updatedStatus, userId);
968                        scheduleWritePackageRestrictionsLocked(userId);
969                    }
970                }
971            }
972        }
973
974        @Override
975        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
976                    ActivityIntentInfo filter, String packageName) {
977            if (!hasValidDomains(filter)) {
978                return false;
979            }
980            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
981            if (ivs == null) {
982                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
983                        packageName);
984            }
985            if (DEBUG_DOMAIN_VERIFICATION) {
986                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
987            }
988            ivs.addFilter(filter);
989            return true;
990        }
991
992        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
993                int userId, int verificationId, String packageName) {
994            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
995                    verifierUid, userId, packageName);
996            ivs.setPendingState();
997            synchronized (mPackages) {
998                mIntentFilterVerificationStates.append(verificationId, ivs);
999                mCurrentIntentFilterVerifications.add(verificationId);
1000            }
1001            return ivs;
1002        }
1003    }
1004
1005    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1006        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1007                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1008                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1009    }
1010
1011    // Set of pending broadcasts for aggregating enable/disable of components.
1012    static class PendingPackageBroadcasts {
1013        // for each user id, a map of <package name -> components within that package>
1014        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1015
1016        public PendingPackageBroadcasts() {
1017            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1018        }
1019
1020        public ArrayList<String> get(int userId, String packageName) {
1021            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1022            return packages.get(packageName);
1023        }
1024
1025        public void put(int userId, String packageName, ArrayList<String> components) {
1026            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1027            packages.put(packageName, components);
1028        }
1029
1030        public void remove(int userId, String packageName) {
1031            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1032            if (packages != null) {
1033                packages.remove(packageName);
1034            }
1035        }
1036
1037        public void remove(int userId) {
1038            mUidMap.remove(userId);
1039        }
1040
1041        public int userIdCount() {
1042            return mUidMap.size();
1043        }
1044
1045        public int userIdAt(int n) {
1046            return mUidMap.keyAt(n);
1047        }
1048
1049        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1050            return mUidMap.get(userId);
1051        }
1052
1053        public int size() {
1054            // total number of pending broadcast entries across all userIds
1055            int num = 0;
1056            for (int i = 0; i< mUidMap.size(); i++) {
1057                num += mUidMap.valueAt(i).size();
1058            }
1059            return num;
1060        }
1061
1062        public void clear() {
1063            mUidMap.clear();
1064        }
1065
1066        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1067            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1068            if (map == null) {
1069                map = new ArrayMap<String, ArrayList<String>>();
1070                mUidMap.put(userId, map);
1071            }
1072            return map;
1073        }
1074    }
1075    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1076
1077    // Service Connection to remote media container service to copy
1078    // package uri's from external media onto secure containers
1079    // or internal storage.
1080    private IMediaContainerService mContainerService = null;
1081
1082    static final int SEND_PENDING_BROADCAST = 1;
1083    static final int MCS_BOUND = 3;
1084    static final int END_COPY = 4;
1085    static final int INIT_COPY = 5;
1086    static final int MCS_UNBIND = 6;
1087    static final int START_CLEANING_PACKAGE = 7;
1088    static final int FIND_INSTALL_LOC = 8;
1089    static final int POST_INSTALL = 9;
1090    static final int MCS_RECONNECT = 10;
1091    static final int MCS_GIVE_UP = 11;
1092    static final int UPDATED_MEDIA_STATUS = 12;
1093    static final int WRITE_SETTINGS = 13;
1094    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1095    static final int PACKAGE_VERIFIED = 15;
1096    static final int CHECK_PENDING_VERIFICATION = 16;
1097    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1098    static final int INTENT_FILTER_VERIFIED = 18;
1099    static final int WRITE_PACKAGE_LIST = 19;
1100    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1101
1102    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1103
1104    // Delay time in millisecs
1105    static final int BROADCAST_DELAY = 10 * 1000;
1106
1107    static UserManagerService sUserManager;
1108
1109    // Stores a list of users whose package restrictions file needs to be updated
1110    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1111
1112    final private DefaultContainerConnection mDefContainerConn =
1113            new DefaultContainerConnection();
1114    class DefaultContainerConnection implements ServiceConnection {
1115        public void onServiceConnected(ComponentName name, IBinder service) {
1116            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1117            final IMediaContainerService imcs = IMediaContainerService.Stub
1118                    .asInterface(Binder.allowBlocking(service));
1119            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1120        }
1121
1122        public void onServiceDisconnected(ComponentName name) {
1123            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1124        }
1125    }
1126
1127    // Recordkeeping of restore-after-install operations that are currently in flight
1128    // between the Package Manager and the Backup Manager
1129    static class PostInstallData {
1130        public InstallArgs args;
1131        public PackageInstalledInfo res;
1132
1133        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1134            args = _a;
1135            res = _r;
1136        }
1137    }
1138
1139    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1140    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1141
1142    // XML tags for backup/restore of various bits of state
1143    private static final String TAG_PREFERRED_BACKUP = "pa";
1144    private static final String TAG_DEFAULT_APPS = "da";
1145    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1146
1147    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1148    private static final String TAG_ALL_GRANTS = "rt-grants";
1149    private static final String TAG_GRANT = "grant";
1150    private static final String ATTR_PACKAGE_NAME = "pkg";
1151
1152    private static final String TAG_PERMISSION = "perm";
1153    private static final String ATTR_PERMISSION_NAME = "name";
1154    private static final String ATTR_IS_GRANTED = "g";
1155    private static final String ATTR_USER_SET = "set";
1156    private static final String ATTR_USER_FIXED = "fixed";
1157    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1158
1159    // System/policy permission grants are not backed up
1160    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1161            FLAG_PERMISSION_POLICY_FIXED
1162            | FLAG_PERMISSION_SYSTEM_FIXED
1163            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1164
1165    // And we back up these user-adjusted states
1166    private static final int USER_RUNTIME_GRANT_MASK =
1167            FLAG_PERMISSION_USER_SET
1168            | FLAG_PERMISSION_USER_FIXED
1169            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1170
1171    final @Nullable String mRequiredVerifierPackage;
1172    final @NonNull String mRequiredInstallerPackage;
1173    final @NonNull String mRequiredUninstallerPackage;
1174    final @Nullable String mSetupWizardPackage;
1175    final @Nullable String mStorageManagerPackage;
1176    final @NonNull String mServicesSystemSharedLibraryPackageName;
1177    final @NonNull String mSharedSystemSharedLibraryPackageName;
1178
1179    final boolean mPermissionReviewRequired;
1180
1181    private final PackageUsage mPackageUsage = new PackageUsage();
1182    private final CompilerStats mCompilerStats = new CompilerStats();
1183
1184    class PackageHandler extends Handler {
1185        private boolean mBound = false;
1186        final ArrayList<HandlerParams> mPendingInstalls =
1187            new ArrayList<HandlerParams>();
1188
1189        private boolean connectToService() {
1190            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1191                    " DefaultContainerService");
1192            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1193            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1194            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1195                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1196                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1197                mBound = true;
1198                return true;
1199            }
1200            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1201            return false;
1202        }
1203
1204        private void disconnectService() {
1205            mContainerService = null;
1206            mBound = false;
1207            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1208            mContext.unbindService(mDefContainerConn);
1209            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1210        }
1211
1212        PackageHandler(Looper looper) {
1213            super(looper);
1214        }
1215
1216        public void handleMessage(Message msg) {
1217            try {
1218                doHandleMessage(msg);
1219            } finally {
1220                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1221            }
1222        }
1223
1224        void doHandleMessage(Message msg) {
1225            switch (msg.what) {
1226                case INIT_COPY: {
1227                    HandlerParams params = (HandlerParams) msg.obj;
1228                    int idx = mPendingInstalls.size();
1229                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1230                    // If a bind was already initiated we dont really
1231                    // need to do anything. The pending install
1232                    // will be processed later on.
1233                    if (!mBound) {
1234                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1235                                System.identityHashCode(mHandler));
1236                        // If this is the only one pending we might
1237                        // have to bind to the service again.
1238                        if (!connectToService()) {
1239                            Slog.e(TAG, "Failed to bind to media container service");
1240                            params.serviceError();
1241                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1242                                    System.identityHashCode(mHandler));
1243                            if (params.traceMethod != null) {
1244                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1245                                        params.traceCookie);
1246                            }
1247                            return;
1248                        } else {
1249                            // Once we bind to the service, the first
1250                            // pending request will be processed.
1251                            mPendingInstalls.add(idx, params);
1252                        }
1253                    } else {
1254                        mPendingInstalls.add(idx, params);
1255                        // Already bound to the service. Just make
1256                        // sure we trigger off processing the first request.
1257                        if (idx == 0) {
1258                            mHandler.sendEmptyMessage(MCS_BOUND);
1259                        }
1260                    }
1261                    break;
1262                }
1263                case MCS_BOUND: {
1264                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1265                    if (msg.obj != null) {
1266                        mContainerService = (IMediaContainerService) msg.obj;
1267                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1268                                System.identityHashCode(mHandler));
1269                    }
1270                    if (mContainerService == null) {
1271                        if (!mBound) {
1272                            // Something seriously wrong since we are not bound and we are not
1273                            // waiting for connection. Bail out.
1274                            Slog.e(TAG, "Cannot bind to media container service");
1275                            for (HandlerParams params : mPendingInstalls) {
1276                                // Indicate service bind error
1277                                params.serviceError();
1278                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1279                                        System.identityHashCode(params));
1280                                if (params.traceMethod != null) {
1281                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1282                                            params.traceMethod, params.traceCookie);
1283                                }
1284                                return;
1285                            }
1286                            mPendingInstalls.clear();
1287                        } else {
1288                            Slog.w(TAG, "Waiting to connect to media container service");
1289                        }
1290                    } else if (mPendingInstalls.size() > 0) {
1291                        HandlerParams params = mPendingInstalls.get(0);
1292                        if (params != null) {
1293                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1294                                    System.identityHashCode(params));
1295                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1296                            if (params.startCopy()) {
1297                                // We are done...  look for more work or to
1298                                // go idle.
1299                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1300                                        "Checking for more work or unbind...");
1301                                // Delete pending install
1302                                if (mPendingInstalls.size() > 0) {
1303                                    mPendingInstalls.remove(0);
1304                                }
1305                                if (mPendingInstalls.size() == 0) {
1306                                    if (mBound) {
1307                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1308                                                "Posting delayed MCS_UNBIND");
1309                                        removeMessages(MCS_UNBIND);
1310                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1311                                        // Unbind after a little delay, to avoid
1312                                        // continual thrashing.
1313                                        sendMessageDelayed(ubmsg, 10000);
1314                                    }
1315                                } else {
1316                                    // There are more pending requests in queue.
1317                                    // Just post MCS_BOUND message to trigger processing
1318                                    // of next pending install.
1319                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1320                                            "Posting MCS_BOUND for next work");
1321                                    mHandler.sendEmptyMessage(MCS_BOUND);
1322                                }
1323                            }
1324                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1325                        }
1326                    } else {
1327                        // Should never happen ideally.
1328                        Slog.w(TAG, "Empty queue");
1329                    }
1330                    break;
1331                }
1332                case MCS_RECONNECT: {
1333                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1334                    if (mPendingInstalls.size() > 0) {
1335                        if (mBound) {
1336                            disconnectService();
1337                        }
1338                        if (!connectToService()) {
1339                            Slog.e(TAG, "Failed to bind to media container service");
1340                            for (HandlerParams params : mPendingInstalls) {
1341                                // Indicate service bind error
1342                                params.serviceError();
1343                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1344                                        System.identityHashCode(params));
1345                            }
1346                            mPendingInstalls.clear();
1347                        }
1348                    }
1349                    break;
1350                }
1351                case MCS_UNBIND: {
1352                    // If there is no actual work left, then time to unbind.
1353                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1354
1355                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1356                        if (mBound) {
1357                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1358
1359                            disconnectService();
1360                        }
1361                    } else if (mPendingInstalls.size() > 0) {
1362                        // There are more pending requests in queue.
1363                        // Just post MCS_BOUND message to trigger processing
1364                        // of next pending install.
1365                        mHandler.sendEmptyMessage(MCS_BOUND);
1366                    }
1367
1368                    break;
1369                }
1370                case MCS_GIVE_UP: {
1371                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1372                    HandlerParams params = mPendingInstalls.remove(0);
1373                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1374                            System.identityHashCode(params));
1375                    break;
1376                }
1377                case SEND_PENDING_BROADCAST: {
1378                    String packages[];
1379                    ArrayList<String> components[];
1380                    int size = 0;
1381                    int uids[];
1382                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1383                    synchronized (mPackages) {
1384                        if (mPendingBroadcasts == null) {
1385                            return;
1386                        }
1387                        size = mPendingBroadcasts.size();
1388                        if (size <= 0) {
1389                            // Nothing to be done. Just return
1390                            return;
1391                        }
1392                        packages = new String[size];
1393                        components = new ArrayList[size];
1394                        uids = new int[size];
1395                        int i = 0;  // filling out the above arrays
1396
1397                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1398                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1399                            Iterator<Map.Entry<String, ArrayList<String>>> it
1400                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1401                                            .entrySet().iterator();
1402                            while (it.hasNext() && i < size) {
1403                                Map.Entry<String, ArrayList<String>> ent = it.next();
1404                                packages[i] = ent.getKey();
1405                                components[i] = ent.getValue();
1406                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1407                                uids[i] = (ps != null)
1408                                        ? UserHandle.getUid(packageUserId, ps.appId)
1409                                        : -1;
1410                                i++;
1411                            }
1412                        }
1413                        size = i;
1414                        mPendingBroadcasts.clear();
1415                    }
1416                    // Send broadcasts
1417                    for (int i = 0; i < size; i++) {
1418                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1419                    }
1420                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                    break;
1422                }
1423                case START_CLEANING_PACKAGE: {
1424                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1425                    final String packageName = (String)msg.obj;
1426                    final int userId = msg.arg1;
1427                    final boolean andCode = msg.arg2 != 0;
1428                    synchronized (mPackages) {
1429                        if (userId == UserHandle.USER_ALL) {
1430                            int[] users = sUserManager.getUserIds();
1431                            for (int user : users) {
1432                                mSettings.addPackageToCleanLPw(
1433                                        new PackageCleanItem(user, packageName, andCode));
1434                            }
1435                        } else {
1436                            mSettings.addPackageToCleanLPw(
1437                                    new PackageCleanItem(userId, packageName, andCode));
1438                        }
1439                    }
1440                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441                    startCleaningPackages();
1442                } break;
1443                case POST_INSTALL: {
1444                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1445
1446                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1447                    final boolean didRestore = (msg.arg2 != 0);
1448                    mRunningInstalls.delete(msg.arg1);
1449
1450                    if (data != null) {
1451                        InstallArgs args = data.args;
1452                        PackageInstalledInfo parentRes = data.res;
1453
1454                        final boolean grantPermissions = (args.installFlags
1455                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1456                        final boolean killApp = (args.installFlags
1457                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1458                        final String[] grantedPermissions = args.installGrantPermissions;
1459
1460                        // Handle the parent package
1461                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1462                                grantedPermissions, didRestore, args.installerPackageName,
1463                                args.observer);
1464
1465                        // Handle the child packages
1466                        final int childCount = (parentRes.addedChildPackages != null)
1467                                ? parentRes.addedChildPackages.size() : 0;
1468                        for (int i = 0; i < childCount; i++) {
1469                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1470                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1471                                    grantedPermissions, false, args.installerPackageName,
1472                                    args.observer);
1473                        }
1474
1475                        // Log tracing if needed
1476                        if (args.traceMethod != null) {
1477                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1478                                    args.traceCookie);
1479                        }
1480                    } else {
1481                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1482                    }
1483
1484                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1485                } break;
1486                case UPDATED_MEDIA_STATUS: {
1487                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1488                    boolean reportStatus = msg.arg1 == 1;
1489                    boolean doGc = msg.arg2 == 1;
1490                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1491                    if (doGc) {
1492                        // Force a gc to clear up stale containers.
1493                        Runtime.getRuntime().gc();
1494                    }
1495                    if (msg.obj != null) {
1496                        @SuppressWarnings("unchecked")
1497                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1498                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1499                        // Unload containers
1500                        unloadAllContainers(args);
1501                    }
1502                    if (reportStatus) {
1503                        try {
1504                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1505                                    "Invoking StorageManagerService call back");
1506                            PackageHelper.getStorageManager().finishMediaUpdate();
1507                        } catch (RemoteException e) {
1508                            Log.e(TAG, "StorageManagerService not running?");
1509                        }
1510                    }
1511                } break;
1512                case WRITE_SETTINGS: {
1513                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1514                    synchronized (mPackages) {
1515                        removeMessages(WRITE_SETTINGS);
1516                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1517                        mSettings.writeLPr();
1518                        mDirtyUsers.clear();
1519                    }
1520                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1521                } break;
1522                case WRITE_PACKAGE_RESTRICTIONS: {
1523                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1524                    synchronized (mPackages) {
1525                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1526                        for (int userId : mDirtyUsers) {
1527                            mSettings.writePackageRestrictionsLPr(userId);
1528                        }
1529                        mDirtyUsers.clear();
1530                    }
1531                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1532                } break;
1533                case WRITE_PACKAGE_LIST: {
1534                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1535                    synchronized (mPackages) {
1536                        removeMessages(WRITE_PACKAGE_LIST);
1537                        mSettings.writePackageListLPr(msg.arg1);
1538                    }
1539                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1540                } break;
1541                case CHECK_PENDING_VERIFICATION: {
1542                    final int verificationId = msg.arg1;
1543                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1544
1545                    if ((state != null) && !state.timeoutExtended()) {
1546                        final InstallArgs args = state.getInstallArgs();
1547                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1548
1549                        Slog.i(TAG, "Verification timed out for " + originUri);
1550                        mPendingVerification.remove(verificationId);
1551
1552                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1553
1554                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1555                            Slog.i(TAG, "Continuing with installation of " + originUri);
1556                            state.setVerifierResponse(Binder.getCallingUid(),
1557                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1558                            broadcastPackageVerified(verificationId, originUri,
1559                                    PackageManager.VERIFICATION_ALLOW,
1560                                    state.getInstallArgs().getUser());
1561                            try {
1562                                ret = args.copyApk(mContainerService, true);
1563                            } catch (RemoteException e) {
1564                                Slog.e(TAG, "Could not contact the ContainerService");
1565                            }
1566                        } else {
1567                            broadcastPackageVerified(verificationId, originUri,
1568                                    PackageManager.VERIFICATION_REJECT,
1569                                    state.getInstallArgs().getUser());
1570                        }
1571
1572                        Trace.asyncTraceEnd(
1573                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1574
1575                        processPendingInstall(args, ret);
1576                        mHandler.sendEmptyMessage(MCS_UNBIND);
1577                    }
1578                    break;
1579                }
1580                case PACKAGE_VERIFIED: {
1581                    final int verificationId = msg.arg1;
1582
1583                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1584                    if (state == null) {
1585                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1586                        break;
1587                    }
1588
1589                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1590
1591                    state.setVerifierResponse(response.callerUid, response.code);
1592
1593                    if (state.isVerificationComplete()) {
1594                        mPendingVerification.remove(verificationId);
1595
1596                        final InstallArgs args = state.getInstallArgs();
1597                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1598
1599                        int ret;
1600                        if (state.isInstallAllowed()) {
1601                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1602                            broadcastPackageVerified(verificationId, originUri,
1603                                    response.code, state.getInstallArgs().getUser());
1604                            try {
1605                                ret = args.copyApk(mContainerService, true);
1606                            } catch (RemoteException e) {
1607                                Slog.e(TAG, "Could not contact the ContainerService");
1608                            }
1609                        } else {
1610                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1611                        }
1612
1613                        Trace.asyncTraceEnd(
1614                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1615
1616                        processPendingInstall(args, ret);
1617                        mHandler.sendEmptyMessage(MCS_UNBIND);
1618                    }
1619
1620                    break;
1621                }
1622                case START_INTENT_FILTER_VERIFICATIONS: {
1623                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1624                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1625                            params.replacing, params.pkg);
1626                    break;
1627                }
1628                case INTENT_FILTER_VERIFIED: {
1629                    final int verificationId = msg.arg1;
1630
1631                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1632                            verificationId);
1633                    if (state == null) {
1634                        Slog.w(TAG, "Invalid IntentFilter verification token "
1635                                + verificationId + " received");
1636                        break;
1637                    }
1638
1639                    final int userId = state.getUserId();
1640
1641                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1642                            "Processing IntentFilter verification with token:"
1643                            + verificationId + " and userId:" + userId);
1644
1645                    final IntentFilterVerificationResponse response =
1646                            (IntentFilterVerificationResponse) msg.obj;
1647
1648                    state.setVerifierResponse(response.callerUid, response.code);
1649
1650                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1651                            "IntentFilter verification with token:" + verificationId
1652                            + " and userId:" + userId
1653                            + " is settings verifier response with response code:"
1654                            + response.code);
1655
1656                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1657                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1658                                + response.getFailedDomainsString());
1659                    }
1660
1661                    if (state.isVerificationComplete()) {
1662                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1663                    } else {
1664                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1665                                "IntentFilter verification with token:" + verificationId
1666                                + " was not said to be complete");
1667                    }
1668
1669                    break;
1670                }
1671                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1672                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1673                            mEphemeralResolverConnection,
1674                            (EphemeralRequest) msg.obj,
1675                            mEphemeralInstallerActivity,
1676                            mHandler);
1677                }
1678            }
1679        }
1680    }
1681
1682    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1683            boolean killApp, String[] grantedPermissions,
1684            boolean launchedForRestore, String installerPackage,
1685            IPackageInstallObserver2 installObserver) {
1686        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1687            // Send the removed broadcasts
1688            if (res.removedInfo != null) {
1689                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1690            }
1691
1692            // Now that we successfully installed the package, grant runtime
1693            // permissions if requested before broadcasting the install.
1694            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1695                    >= Build.VERSION_CODES.M) {
1696                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1697            }
1698
1699            final boolean update = res.removedInfo != null
1700                    && res.removedInfo.removedPackage != null;
1701
1702            // If this is the first time we have child packages for a disabled privileged
1703            // app that had no children, we grant requested runtime permissions to the new
1704            // children if the parent on the system image had them already granted.
1705            if (res.pkg.parentPackage != null) {
1706                synchronized (mPackages) {
1707                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1708                }
1709            }
1710
1711            synchronized (mPackages) {
1712                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1713            }
1714
1715            final String packageName = res.pkg.applicationInfo.packageName;
1716
1717            // Determine the set of users who are adding this package for
1718            // the first time vs. those who are seeing an update.
1719            int[] firstUsers = EMPTY_INT_ARRAY;
1720            int[] updateUsers = EMPTY_INT_ARRAY;
1721            if (res.origUsers == null || res.origUsers.length == 0) {
1722                firstUsers = res.newUsers;
1723            } else {
1724                for (int newUser : res.newUsers) {
1725                    boolean isNew = true;
1726                    for (int origUser : res.origUsers) {
1727                        if (origUser == newUser) {
1728                            isNew = false;
1729                            break;
1730                        }
1731                    }
1732                    if (isNew) {
1733                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1734                    } else {
1735                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1736                    }
1737                }
1738            }
1739
1740            // Send installed broadcasts if the install/update is not ephemeral
1741            if (!isEphemeral(res.pkg)) {
1742                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1743
1744                // Send added for users that see the package for the first time
1745                // sendPackageAddedForNewUsers also deals with system apps
1746                int appId = UserHandle.getAppId(res.uid);
1747                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1748                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1749
1750                // Send added for users that don't see the package for the first time
1751                Bundle extras = new Bundle(1);
1752                extras.putInt(Intent.EXTRA_UID, res.uid);
1753                if (update) {
1754                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1755                }
1756                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1757                        extras, 0 /*flags*/, null /*targetPackage*/,
1758                        null /*finishedReceiver*/, updateUsers);
1759
1760                // Send replaced for users that don't see the package for the first time
1761                if (update) {
1762                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1763                            packageName, extras, 0 /*flags*/,
1764                            null /*targetPackage*/, null /*finishedReceiver*/,
1765                            updateUsers);
1766                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1767                            null /*package*/, null /*extras*/, 0 /*flags*/,
1768                            packageName /*targetPackage*/,
1769                            null /*finishedReceiver*/, updateUsers);
1770                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1771                    // First-install and we did a restore, so we're responsible for the
1772                    // first-launch broadcast.
1773                    if (DEBUG_BACKUP) {
1774                        Slog.i(TAG, "Post-restore of " + packageName
1775                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1776                    }
1777                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1778                }
1779
1780                // Send broadcast package appeared if forward locked/external for all users
1781                // treat asec-hosted packages like removable media on upgrade
1782                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1783                    if (DEBUG_INSTALL) {
1784                        Slog.i(TAG, "upgrading pkg " + res.pkg
1785                                + " is ASEC-hosted -> AVAILABLE");
1786                    }
1787                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1788                    ArrayList<String> pkgList = new ArrayList<>(1);
1789                    pkgList.add(packageName);
1790                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1791                }
1792            }
1793
1794            // Work that needs to happen on first install within each user
1795            if (firstUsers != null && firstUsers.length > 0) {
1796                synchronized (mPackages) {
1797                    for (int userId : firstUsers) {
1798                        // If this app is a browser and it's newly-installed for some
1799                        // users, clear any default-browser state in those users. The
1800                        // app's nature doesn't depend on the user, so we can just check
1801                        // its browser nature in any user and generalize.
1802                        if (packageIsBrowser(packageName, userId)) {
1803                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1804                        }
1805
1806                        // We may also need to apply pending (restored) runtime
1807                        // permission grants within these users.
1808                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1809                    }
1810                }
1811            }
1812
1813            // Log current value of "unknown sources" setting
1814            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1815                    getUnknownSourcesSettings());
1816
1817            // Force a gc to clear up things
1818            Runtime.getRuntime().gc();
1819
1820            // Remove the replaced package's older resources safely now
1821            // We delete after a gc for applications  on sdcard.
1822            if (res.removedInfo != null && res.removedInfo.args != null) {
1823                synchronized (mInstallLock) {
1824                    res.removedInfo.args.doPostDeleteLI(true);
1825                }
1826            }
1827        }
1828
1829        // If someone is watching installs - notify them
1830        if (installObserver != null) {
1831            try {
1832                Bundle extras = extrasForInstallResult(res);
1833                installObserver.onPackageInstalled(res.name, res.returnCode,
1834                        res.returnMsg, extras);
1835            } catch (RemoteException e) {
1836                Slog.i(TAG, "Observer no longer exists.");
1837            }
1838        }
1839    }
1840
1841    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1842            PackageParser.Package pkg) {
1843        if (pkg.parentPackage == null) {
1844            return;
1845        }
1846        if (pkg.requestedPermissions == null) {
1847            return;
1848        }
1849        final PackageSetting disabledSysParentPs = mSettings
1850                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1851        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1852                || !disabledSysParentPs.isPrivileged()
1853                || (disabledSysParentPs.childPackageNames != null
1854                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1855            return;
1856        }
1857        final int[] allUserIds = sUserManager.getUserIds();
1858        final int permCount = pkg.requestedPermissions.size();
1859        for (int i = 0; i < permCount; i++) {
1860            String permission = pkg.requestedPermissions.get(i);
1861            BasePermission bp = mSettings.mPermissions.get(permission);
1862            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1863                continue;
1864            }
1865            for (int userId : allUserIds) {
1866                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1867                        permission, userId)) {
1868                    grantRuntimePermission(pkg.packageName, permission, userId);
1869                }
1870            }
1871        }
1872    }
1873
1874    private StorageEventListener mStorageListener = new StorageEventListener() {
1875        @Override
1876        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1877            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1878                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1879                    final String volumeUuid = vol.getFsUuid();
1880
1881                    // Clean up any users or apps that were removed or recreated
1882                    // while this volume was missing
1883                    reconcileUsers(volumeUuid);
1884                    reconcileApps(volumeUuid);
1885
1886                    // Clean up any install sessions that expired or were
1887                    // cancelled while this volume was missing
1888                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1889
1890                    loadPrivatePackages(vol);
1891
1892                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1893                    unloadPrivatePackages(vol);
1894                }
1895            }
1896
1897            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1898                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1899                    updateExternalMediaStatus(true, false);
1900                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1901                    updateExternalMediaStatus(false, false);
1902                }
1903            }
1904        }
1905
1906        @Override
1907        public void onVolumeForgotten(String fsUuid) {
1908            if (TextUtils.isEmpty(fsUuid)) {
1909                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1910                return;
1911            }
1912
1913            // Remove any apps installed on the forgotten volume
1914            synchronized (mPackages) {
1915                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1916                for (PackageSetting ps : packages) {
1917                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1918                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1919                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1920
1921                    // Try very hard to release any references to this package
1922                    // so we don't risk the system server being killed due to
1923                    // open FDs
1924                    AttributeCache.instance().removePackage(ps.name);
1925                }
1926
1927                mSettings.onVolumeForgotten(fsUuid);
1928                mSettings.writeLPr();
1929            }
1930        }
1931    };
1932
1933    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1934            String[] grantedPermissions) {
1935        for (int userId : userIds) {
1936            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1937        }
1938
1939        // We could have touched GID membership, so flush out packages.list
1940        synchronized (mPackages) {
1941            mSettings.writePackageListLPr();
1942        }
1943    }
1944
1945    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1946            String[] grantedPermissions) {
1947        SettingBase sb = (SettingBase) pkg.mExtras;
1948        if (sb == null) {
1949            return;
1950        }
1951
1952        PermissionsState permissionsState = sb.getPermissionsState();
1953
1954        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1955                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1956
1957        for (String permission : pkg.requestedPermissions) {
1958            final BasePermission bp;
1959            synchronized (mPackages) {
1960                bp = mSettings.mPermissions.get(permission);
1961            }
1962            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1963                    && (grantedPermissions == null
1964                           || ArrayUtils.contains(grantedPermissions, permission))) {
1965                final int flags = permissionsState.getPermissionFlags(permission, userId);
1966                // Installer cannot change immutable permissions.
1967                if ((flags & immutableFlags) == 0) {
1968                    grantRuntimePermission(pkg.packageName, permission, userId);
1969                }
1970            }
1971        }
1972    }
1973
1974    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1975        Bundle extras = null;
1976        switch (res.returnCode) {
1977            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1978                extras = new Bundle();
1979                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1980                        res.origPermission);
1981                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1982                        res.origPackage);
1983                break;
1984            }
1985            case PackageManager.INSTALL_SUCCEEDED: {
1986                extras = new Bundle();
1987                extras.putBoolean(Intent.EXTRA_REPLACING,
1988                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1989                break;
1990            }
1991        }
1992        return extras;
1993    }
1994
1995    void scheduleWriteSettingsLocked() {
1996        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1997            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1998        }
1999    }
2000
2001    void scheduleWritePackageListLocked(int userId) {
2002        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2003            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2004            msg.arg1 = userId;
2005            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2006        }
2007    }
2008
2009    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2010        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2011        scheduleWritePackageRestrictionsLocked(userId);
2012    }
2013
2014    void scheduleWritePackageRestrictionsLocked(int userId) {
2015        final int[] userIds = (userId == UserHandle.USER_ALL)
2016                ? sUserManager.getUserIds() : new int[]{userId};
2017        for (int nextUserId : userIds) {
2018            if (!sUserManager.exists(nextUserId)) return;
2019            mDirtyUsers.add(nextUserId);
2020            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2021                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2022            }
2023        }
2024    }
2025
2026    public static PackageManagerService main(Context context, Installer installer,
2027            boolean factoryTest, boolean onlyCore) {
2028        // Self-check for initial settings.
2029        PackageManagerServiceCompilerMapping.checkProperties();
2030
2031        PackageManagerService m = new PackageManagerService(context, installer,
2032                factoryTest, onlyCore);
2033        m.enableSystemUserPackages();
2034        ServiceManager.addService("package", m);
2035        return m;
2036    }
2037
2038    private void enableSystemUserPackages() {
2039        if (!UserManager.isSplitSystemUser()) {
2040            return;
2041        }
2042        // For system user, enable apps based on the following conditions:
2043        // - app is whitelisted or belong to one of these groups:
2044        //   -- system app which has no launcher icons
2045        //   -- system app which has INTERACT_ACROSS_USERS permission
2046        //   -- system IME app
2047        // - app is not in the blacklist
2048        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2049        Set<String> enableApps = new ArraySet<>();
2050        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2051                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2052                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2053        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2054        enableApps.addAll(wlApps);
2055        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2056                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2057        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2058        enableApps.removeAll(blApps);
2059        Log.i(TAG, "Applications installed for system user: " + enableApps);
2060        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2061                UserHandle.SYSTEM);
2062        final int allAppsSize = allAps.size();
2063        synchronized (mPackages) {
2064            for (int i = 0; i < allAppsSize; i++) {
2065                String pName = allAps.get(i);
2066                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2067                // Should not happen, but we shouldn't be failing if it does
2068                if (pkgSetting == null) {
2069                    continue;
2070                }
2071                boolean install = enableApps.contains(pName);
2072                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2073                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2074                            + " for system user");
2075                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2076                }
2077            }
2078        }
2079    }
2080
2081    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2082        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2083                Context.DISPLAY_SERVICE);
2084        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2085    }
2086
2087    /**
2088     * Requests that files preopted on a secondary system partition be copied to the data partition
2089     * if possible.  Note that the actual copying of the files is accomplished by init for security
2090     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2091     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2092     */
2093    private static void requestCopyPreoptedFiles() {
2094        final int WAIT_TIME_MS = 100;
2095        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2096        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2097            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2098            // We will wait for up to 100 seconds.
2099            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2100            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2101                try {
2102                    Thread.sleep(WAIT_TIME_MS);
2103                } catch (InterruptedException e) {
2104                    // Do nothing
2105                }
2106                if (SystemClock.uptimeMillis() > timeEnd) {
2107                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2108                    Slog.wtf(TAG, "cppreopt did not finish!");
2109                    break;
2110                }
2111            }
2112        }
2113    }
2114
2115    public PackageManagerService(Context context, Installer installer,
2116            boolean factoryTest, boolean onlyCore) {
2117        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2118        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2119                SystemClock.uptimeMillis());
2120
2121        if (mSdkVersion <= 0) {
2122            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2123        }
2124
2125        mContext = context;
2126
2127        mPermissionReviewRequired = context.getResources().getBoolean(
2128                R.bool.config_permissionReviewRequired);
2129
2130        mFactoryTest = factoryTest;
2131        mOnlyCore = onlyCore;
2132        mMetrics = new DisplayMetrics();
2133        mSettings = new Settings(mPackages);
2134        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2135                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2136        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2137                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2138        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2139                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2140        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2141                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2142        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2143                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2144        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2145                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2146
2147        String separateProcesses = SystemProperties.get("debug.separate_processes");
2148        if (separateProcesses != null && separateProcesses.length() > 0) {
2149            if ("*".equals(separateProcesses)) {
2150                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2151                mSeparateProcesses = null;
2152                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2153            } else {
2154                mDefParseFlags = 0;
2155                mSeparateProcesses = separateProcesses.split(",");
2156                Slog.w(TAG, "Running with debug.separate_processes: "
2157                        + separateProcesses);
2158            }
2159        } else {
2160            mDefParseFlags = 0;
2161            mSeparateProcesses = null;
2162        }
2163
2164        mInstaller = installer;
2165        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2166                "*dexopt*");
2167        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2168
2169        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2170                FgThread.get().getLooper());
2171
2172        getDefaultDisplayMetrics(context, mMetrics);
2173
2174        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2175        SystemConfig systemConfig = SystemConfig.getInstance();
2176        mGlobalGids = systemConfig.getGlobalGids();
2177        mSystemPermissions = systemConfig.getSystemPermissions();
2178        mAvailableFeatures = systemConfig.getAvailableFeatures();
2179        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2180
2181        mProtectedPackages = new ProtectedPackages(mContext);
2182
2183        synchronized (mInstallLock) {
2184        // writer
2185        synchronized (mPackages) {
2186            mHandlerThread = new ServiceThread(TAG,
2187                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2188            mHandlerThread.start();
2189            mHandler = new PackageHandler(mHandlerThread.getLooper());
2190            mProcessLoggingHandler = new ProcessLoggingHandler();
2191            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2192
2193            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2194
2195            File dataDir = Environment.getDataDirectory();
2196            mAppInstallDir = new File(dataDir, "app");
2197            mAppLib32InstallDir = new File(dataDir, "app-lib");
2198            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2199            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2200            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2201
2202            sUserManager = new UserManagerService(context, this, mPackages);
2203
2204            // Propagate permission configuration in to package manager.
2205            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2206                    = systemConfig.getPermissions();
2207            for (int i=0; i<permConfig.size(); i++) {
2208                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2209                BasePermission bp = mSettings.mPermissions.get(perm.name);
2210                if (bp == null) {
2211                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2212                    mSettings.mPermissions.put(perm.name, bp);
2213                }
2214                if (perm.gids != null) {
2215                    bp.setGids(perm.gids, perm.perUser);
2216                }
2217            }
2218
2219            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2220            for (int i=0; i<libConfig.size(); i++) {
2221                mSharedLibraries.put(libConfig.keyAt(i),
2222                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2223            }
2224
2225            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2226
2227            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2228            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2229            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2230
2231            if (mFirstBoot) {
2232                requestCopyPreoptedFiles();
2233            }
2234
2235            String customResolverActivity = Resources.getSystem().getString(
2236                    R.string.config_customResolverActivity);
2237            if (TextUtils.isEmpty(customResolverActivity)) {
2238                customResolverActivity = null;
2239            } else {
2240                mCustomResolverComponentName = ComponentName.unflattenFromString(
2241                        customResolverActivity);
2242            }
2243
2244            long startTime = SystemClock.uptimeMillis();
2245
2246            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2247                    startTime);
2248
2249            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2250            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2251
2252            if (bootClassPath == null) {
2253                Slog.w(TAG, "No BOOTCLASSPATH found!");
2254            }
2255
2256            if (systemServerClassPath == null) {
2257                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2258            }
2259
2260            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2261            final String[] dexCodeInstructionSets =
2262                    getDexCodeInstructionSets(
2263                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2264
2265            /**
2266             * Ensure all external libraries have had dexopt run on them.
2267             */
2268            if (mSharedLibraries.size() > 0) {
2269                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2270                // NOTE: For now, we're compiling these system "shared libraries"
2271                // (and framework jars) into all available architectures. It's possible
2272                // to compile them only when we come across an app that uses them (there's
2273                // already logic for that in scanPackageLI) but that adds some complexity.
2274                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2275                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2276                        final String lib = libEntry.path;
2277                        if (lib == null) {
2278                            continue;
2279                        }
2280
2281                        try {
2282                            // Shared libraries do not have profiles so we perform a full
2283                            // AOT compilation (if needed).
2284                            int dexoptNeeded = DexFile.getDexOptNeeded(
2285                                    lib, dexCodeInstructionSet,
2286                                    getCompilerFilterForReason(REASON_SHARED_APK),
2287                                    false /* newProfile */);
2288                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2289                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2290                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2291                                        getCompilerFilterForReason(REASON_SHARED_APK),
2292                                        StorageManager.UUID_PRIVATE_INTERNAL,
2293                                        SKIP_SHARED_LIBRARY_CHECK);
2294                            }
2295                        } catch (FileNotFoundException e) {
2296                            Slog.w(TAG, "Library not found: " + lib);
2297                        } catch (IOException | InstallerException e) {
2298                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2299                                    + e.getMessage());
2300                        }
2301                    }
2302                }
2303                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2304            }
2305
2306            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2307
2308            final VersionInfo ver = mSettings.getInternalVersion();
2309            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2310
2311            // when upgrading from pre-M, promote system app permissions from install to runtime
2312            mPromoteSystemApps =
2313                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2314
2315            // When upgrading from pre-N, we need to handle package extraction like first boot,
2316            // as there is no profiling data available.
2317            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2318
2319            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2320
2321            // save off the names of pre-existing system packages prior to scanning; we don't
2322            // want to automatically grant runtime permissions for new system apps
2323            if (mPromoteSystemApps) {
2324                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2325                while (pkgSettingIter.hasNext()) {
2326                    PackageSetting ps = pkgSettingIter.next();
2327                    if (isSystemApp(ps)) {
2328                        mExistingSystemPackages.add(ps.name);
2329                    }
2330                }
2331            }
2332
2333            // Set flag to monitor and not change apk file paths when
2334            // scanning install directories.
2335            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2336
2337            if (mIsUpgrade || mFirstBoot) {
2338                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2339            }
2340
2341            // Collect vendor overlay packages. (Do this before scanning any apps.)
2342            // For security and version matching reason, only consider
2343            // overlay packages if they reside in the right directory.
2344            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2345            if (overlayThemeDir.isEmpty()) {
2346                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2347            }
2348            if (!overlayThemeDir.isEmpty()) {
2349                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2350                        | PackageParser.PARSE_IS_SYSTEM
2351                        | PackageParser.PARSE_IS_SYSTEM_DIR
2352                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2353            }
2354            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2355                    | PackageParser.PARSE_IS_SYSTEM
2356                    | PackageParser.PARSE_IS_SYSTEM_DIR
2357                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2358
2359            // Find base frameworks (resource packages without code).
2360            scanDirTracedLI(frameworkDir, mDefParseFlags
2361                    | PackageParser.PARSE_IS_SYSTEM
2362                    | PackageParser.PARSE_IS_SYSTEM_DIR
2363                    | PackageParser.PARSE_IS_PRIVILEGED,
2364                    scanFlags | SCAN_NO_DEX, 0);
2365
2366            // Collected privileged system packages.
2367            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2368            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2369                    | PackageParser.PARSE_IS_SYSTEM
2370                    | PackageParser.PARSE_IS_SYSTEM_DIR
2371                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2372
2373            // Collect ordinary system packages.
2374            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2375            scanDirTracedLI(systemAppDir, mDefParseFlags
2376                    | PackageParser.PARSE_IS_SYSTEM
2377                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2378
2379            // Collect all vendor packages.
2380            File vendorAppDir = new File("/vendor/app");
2381            try {
2382                vendorAppDir = vendorAppDir.getCanonicalFile();
2383            } catch (IOException e) {
2384                // failed to look up canonical path, continue with original one
2385            }
2386            scanDirTracedLI(vendorAppDir, mDefParseFlags
2387                    | PackageParser.PARSE_IS_SYSTEM
2388                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2389
2390            // Collect all OEM packages.
2391            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2392            scanDirTracedLI(oemAppDir, mDefParseFlags
2393                    | PackageParser.PARSE_IS_SYSTEM
2394                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2395
2396            // Prune any system packages that no longer exist.
2397            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2398            if (!mOnlyCore) {
2399                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2400                while (psit.hasNext()) {
2401                    PackageSetting ps = psit.next();
2402
2403                    /*
2404                     * If this is not a system app, it can't be a
2405                     * disable system app.
2406                     */
2407                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2408                        continue;
2409                    }
2410
2411                    /*
2412                     * If the package is scanned, it's not erased.
2413                     */
2414                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2415                    if (scannedPkg != null) {
2416                        /*
2417                         * If the system app is both scanned and in the
2418                         * disabled packages list, then it must have been
2419                         * added via OTA. Remove it from the currently
2420                         * scanned package so the previously user-installed
2421                         * application can be scanned.
2422                         */
2423                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2424                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2425                                    + ps.name + "; removing system app.  Last known codePath="
2426                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2427                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2428                                    + scannedPkg.mVersionCode);
2429                            removePackageLI(scannedPkg, true);
2430                            mExpectingBetter.put(ps.name, ps.codePath);
2431                        }
2432
2433                        continue;
2434                    }
2435
2436                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2437                        psit.remove();
2438                        logCriticalInfo(Log.WARN, "System package " + ps.name
2439                                + " no longer exists; it's data will be wiped");
2440                        // Actual deletion of code and data will be handled by later
2441                        // reconciliation step
2442                    } else {
2443                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2444                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2445                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2446                        }
2447                    }
2448                }
2449            }
2450
2451            //look for any incomplete package installations
2452            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2453            for (int i = 0; i < deletePkgsList.size(); i++) {
2454                // Actual deletion of code and data will be handled by later
2455                // reconciliation step
2456                final String packageName = deletePkgsList.get(i).name;
2457                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2458                synchronized (mPackages) {
2459                    mSettings.removePackageLPw(packageName);
2460                }
2461            }
2462
2463            //delete tmp files
2464            deleteTempPackageFiles();
2465
2466            // Remove any shared userIDs that have no associated packages
2467            mSettings.pruneSharedUsersLPw();
2468
2469            if (!mOnlyCore) {
2470                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2471                        SystemClock.uptimeMillis());
2472                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2473
2474                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2475                        | PackageParser.PARSE_FORWARD_LOCK,
2476                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2477
2478                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2479                        | PackageParser.PARSE_IS_EPHEMERAL,
2480                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2481
2482                /**
2483                 * Remove disable package settings for any updated system
2484                 * apps that were removed via an OTA. If they're not a
2485                 * previously-updated app, remove them completely.
2486                 * Otherwise, just revoke their system-level permissions.
2487                 */
2488                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2489                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2490                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2491
2492                    String msg;
2493                    if (deletedPkg == null) {
2494                        msg = "Updated system package " + deletedAppName
2495                                + " no longer exists; it's data will be wiped";
2496                        // Actual deletion of code and data will be handled by later
2497                        // reconciliation step
2498                    } else {
2499                        msg = "Updated system app + " + deletedAppName
2500                                + " no longer present; removing system privileges for "
2501                                + deletedAppName;
2502
2503                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2504
2505                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2506                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2507                    }
2508                    logCriticalInfo(Log.WARN, msg);
2509                }
2510
2511                /**
2512                 * Make sure all system apps that we expected to appear on
2513                 * the userdata partition actually showed up. If they never
2514                 * appeared, crawl back and revive the system version.
2515                 */
2516                for (int i = 0; i < mExpectingBetter.size(); i++) {
2517                    final String packageName = mExpectingBetter.keyAt(i);
2518                    if (!mPackages.containsKey(packageName)) {
2519                        final File scanFile = mExpectingBetter.valueAt(i);
2520
2521                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2522                                + " but never showed up; reverting to system");
2523
2524                        int reparseFlags = mDefParseFlags;
2525                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2526                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2527                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2528                                    | PackageParser.PARSE_IS_PRIVILEGED;
2529                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2530                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2531                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2532                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2533                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2534                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2535                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2536                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2537                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2538                        } else {
2539                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2540                            continue;
2541                        }
2542
2543                        mSettings.enableSystemPackageLPw(packageName);
2544
2545                        try {
2546                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2547                        } catch (PackageManagerException e) {
2548                            Slog.e(TAG, "Failed to parse original system package: "
2549                                    + e.getMessage());
2550                        }
2551                    }
2552                }
2553            }
2554            mExpectingBetter.clear();
2555
2556            // Resolve the storage manager.
2557            mStorageManagerPackage = getStorageManagerPackageName();
2558
2559            // Resolve protected action filters. Only the setup wizard is allowed to
2560            // have a high priority filter for these actions.
2561            mSetupWizardPackage = getSetupWizardPackageName();
2562            if (mProtectedFilters.size() > 0) {
2563                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2564                    Slog.i(TAG, "No setup wizard;"
2565                        + " All protected intents capped to priority 0");
2566                }
2567                for (ActivityIntentInfo filter : mProtectedFilters) {
2568                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2569                        if (DEBUG_FILTERS) {
2570                            Slog.i(TAG, "Found setup wizard;"
2571                                + " allow priority " + filter.getPriority() + ";"
2572                                + " package: " + filter.activity.info.packageName
2573                                + " activity: " + filter.activity.className
2574                                + " priority: " + filter.getPriority());
2575                        }
2576                        // skip setup wizard; allow it to keep the high priority filter
2577                        continue;
2578                    }
2579                    Slog.w(TAG, "Protected action; cap priority to 0;"
2580                            + " package: " + filter.activity.info.packageName
2581                            + " activity: " + filter.activity.className
2582                            + " origPrio: " + filter.getPriority());
2583                    filter.setPriority(0);
2584                }
2585            }
2586            mDeferProtectedFilters = false;
2587            mProtectedFilters.clear();
2588
2589            // Now that we know all of the shared libraries, update all clients to have
2590            // the correct library paths.
2591            updateAllSharedLibrariesLPw();
2592
2593            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2594                // NOTE: We ignore potential failures here during a system scan (like
2595                // the rest of the commands above) because there's precious little we
2596                // can do about it. A settings error is reported, though.
2597                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2598            }
2599
2600            // Now that we know all the packages we are keeping,
2601            // read and update their last usage times.
2602            mPackageUsage.read(mPackages);
2603            mCompilerStats.read();
2604
2605            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2606                    SystemClock.uptimeMillis());
2607            Slog.i(TAG, "Time to scan packages: "
2608                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2609                    + " seconds");
2610
2611            // If the platform SDK has changed since the last time we booted,
2612            // we need to re-grant app permission to catch any new ones that
2613            // appear.  This is really a hack, and means that apps can in some
2614            // cases get permissions that the user didn't initially explicitly
2615            // allow...  it would be nice to have some better way to handle
2616            // this situation.
2617            int updateFlags = UPDATE_PERMISSIONS_ALL;
2618            if (ver.sdkVersion != mSdkVersion) {
2619                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2620                        + mSdkVersion + "; regranting permissions for internal storage");
2621                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2622            }
2623            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2624            ver.sdkVersion = mSdkVersion;
2625
2626            // If this is the first boot or an update from pre-M, and it is a normal
2627            // boot, then we need to initialize the default preferred apps across
2628            // all defined users.
2629            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2630                for (UserInfo user : sUserManager.getUsers(true)) {
2631                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2632                    applyFactoryDefaultBrowserLPw(user.id);
2633                    primeDomainVerificationsLPw(user.id);
2634                }
2635            }
2636
2637            // Prepare storage for system user really early during boot,
2638            // since core system apps like SettingsProvider and SystemUI
2639            // can't wait for user to start
2640            final int storageFlags;
2641            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2642                storageFlags = StorageManager.FLAG_STORAGE_DE;
2643            } else {
2644                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2645            }
2646            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2647                    storageFlags, true /* migrateAppData */);
2648
2649            // If this is first boot after an OTA, and a normal boot, then
2650            // we need to clear code cache directories.
2651            // Note that we do *not* clear the application profiles. These remain valid
2652            // across OTAs and are used to drive profile verification (post OTA) and
2653            // profile compilation (without waiting to collect a fresh set of profiles).
2654            if (mIsUpgrade && !onlyCore) {
2655                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2656                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2657                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2658                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2659                        // No apps are running this early, so no need to freeze
2660                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2661                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2662                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2663                    }
2664                }
2665                ver.fingerprint = Build.FINGERPRINT;
2666            }
2667
2668            checkDefaultBrowser();
2669
2670            // clear only after permissions and other defaults have been updated
2671            mExistingSystemPackages.clear();
2672            mPromoteSystemApps = false;
2673
2674            // All the changes are done during package scanning.
2675            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2676
2677            // can downgrade to reader
2678            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2679            mSettings.writeLPr();
2680            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2681
2682            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2683            // early on (before the package manager declares itself as early) because other
2684            // components in the system server might ask for package contexts for these apps.
2685            //
2686            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2687            // (i.e, that the data partition is unavailable).
2688            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2689                long start = System.nanoTime();
2690                List<PackageParser.Package> coreApps = new ArrayList<>();
2691                for (PackageParser.Package pkg : mPackages.values()) {
2692                    if (pkg.coreApp) {
2693                        coreApps.add(pkg);
2694                    }
2695                }
2696
2697                int[] stats = performDexOptUpgrade(coreApps, false,
2698                        getCompilerFilterForReason(REASON_CORE_APP));
2699
2700                final int elapsedTimeSeconds =
2701                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2702                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2703
2704                if (DEBUG_DEXOPT) {
2705                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2706                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2707                }
2708
2709
2710                // TODO: Should we log these stats to tron too ?
2711                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2712                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2713                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2714                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2715            }
2716
2717            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2718                    SystemClock.uptimeMillis());
2719
2720            if (!mOnlyCore) {
2721                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2722                mRequiredInstallerPackage = getRequiredInstallerLPr();
2723                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2724                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2725                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2726                        mIntentFilterVerifierComponent);
2727                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2728                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2729                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2730                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2731            } else {
2732                mRequiredVerifierPackage = null;
2733                mRequiredInstallerPackage = null;
2734                mRequiredUninstallerPackage = null;
2735                mIntentFilterVerifierComponent = null;
2736                mIntentFilterVerifier = null;
2737                mServicesSystemSharedLibraryPackageName = null;
2738                mSharedSystemSharedLibraryPackageName = null;
2739            }
2740
2741            mInstallerService = new PackageInstallerService(context, this);
2742
2743            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2744            if (ephemeralResolverComponent != null) {
2745                if (DEBUG_EPHEMERAL) {
2746                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2747                }
2748                mEphemeralResolverConnection =
2749                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2750            } else {
2751                mEphemeralResolverConnection = null;
2752            }
2753            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2754            if (mEphemeralInstallerComponent != null) {
2755                if (DEBUG_EPHEMERAL) {
2756                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2757                }
2758                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2759            }
2760
2761            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2762        } // synchronized (mPackages)
2763        } // synchronized (mInstallLock)
2764
2765        // Now after opening every single application zip, make sure they
2766        // are all flushed.  Not really needed, but keeps things nice and
2767        // tidy.
2768        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2769        Runtime.getRuntime().gc();
2770        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2771
2772        // The initial scanning above does many calls into installd while
2773        // holding the mPackages lock, but we're mostly interested in yelling
2774        // once we have a booted system.
2775        mInstaller.setWarnIfHeld(mPackages);
2776
2777        // Expose private service for system components to use.
2778        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2779        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2780    }
2781
2782    @Override
2783    public boolean isFirstBoot() {
2784        return mFirstBoot;
2785    }
2786
2787    @Override
2788    public boolean isOnlyCoreApps() {
2789        return mOnlyCore;
2790    }
2791
2792    @Override
2793    public boolean isUpgrade() {
2794        return mIsUpgrade;
2795    }
2796
2797    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2798        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2799
2800        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2801                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2802                UserHandle.USER_SYSTEM);
2803        if (matches.size() == 1) {
2804            return matches.get(0).getComponentInfo().packageName;
2805        } else if (matches.size() == 0) {
2806            Log.e(TAG, "There should probably be a verifier, but, none were found");
2807            return null;
2808        }
2809        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2810    }
2811
2812    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2813        synchronized (mPackages) {
2814            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2815            if (libraryEntry == null) {
2816                throw new IllegalStateException("Missing required shared library:" + libraryName);
2817            }
2818            return libraryEntry.apk;
2819        }
2820    }
2821
2822    private @NonNull String getRequiredInstallerLPr() {
2823        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2824        intent.addCategory(Intent.CATEGORY_DEFAULT);
2825        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2826
2827        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2828                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2829                UserHandle.USER_SYSTEM);
2830        if (matches.size() == 1) {
2831            ResolveInfo resolveInfo = matches.get(0);
2832            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2833                throw new RuntimeException("The installer must be a privileged app");
2834            }
2835            return matches.get(0).getComponentInfo().packageName;
2836        } else {
2837            throw new RuntimeException("There must be exactly one installer; found " + matches);
2838        }
2839    }
2840
2841    private @NonNull String getRequiredUninstallerLPr() {
2842        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2843        intent.addCategory(Intent.CATEGORY_DEFAULT);
2844        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2845
2846        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2847                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2848                UserHandle.USER_SYSTEM);
2849        if (resolveInfo == null ||
2850                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2851            throw new RuntimeException("There must be exactly one uninstaller; found "
2852                    + resolveInfo);
2853        }
2854        return resolveInfo.getComponentInfo().packageName;
2855    }
2856
2857    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2858        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2859
2860        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2861                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2862                UserHandle.USER_SYSTEM);
2863        ResolveInfo best = null;
2864        final int N = matches.size();
2865        for (int i = 0; i < N; i++) {
2866            final ResolveInfo cur = matches.get(i);
2867            final String packageName = cur.getComponentInfo().packageName;
2868            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2869                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2870                continue;
2871            }
2872
2873            if (best == null || cur.priority > best.priority) {
2874                best = cur;
2875            }
2876        }
2877
2878        if (best != null) {
2879            return best.getComponentInfo().getComponentName();
2880        } else {
2881            throw new RuntimeException("There must be at least one intent filter verifier");
2882        }
2883    }
2884
2885    private @Nullable ComponentName getEphemeralResolverLPr() {
2886        final String[] packageArray =
2887                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2888        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2889            if (DEBUG_EPHEMERAL) {
2890                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2891            }
2892            return null;
2893        }
2894
2895        final int resolveFlags =
2896                MATCH_DIRECT_BOOT_AWARE
2897                | MATCH_DIRECT_BOOT_UNAWARE
2898                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2899        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2900        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2901                resolveFlags, UserHandle.USER_SYSTEM);
2902
2903        final int N = resolvers.size();
2904        if (N == 0) {
2905            if (DEBUG_EPHEMERAL) {
2906                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2907            }
2908            return null;
2909        }
2910
2911        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2912        for (int i = 0; i < N; i++) {
2913            final ResolveInfo info = resolvers.get(i);
2914
2915            if (info.serviceInfo == null) {
2916                continue;
2917            }
2918
2919            final String packageName = info.serviceInfo.packageName;
2920            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2921                if (DEBUG_EPHEMERAL) {
2922                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2923                            + " pkg: " + packageName + ", info:" + info);
2924                }
2925                continue;
2926            }
2927
2928            if (DEBUG_EPHEMERAL) {
2929                Slog.v(TAG, "Ephemeral resolver found;"
2930                        + " pkg: " + packageName + ", info:" + info);
2931            }
2932            return new ComponentName(packageName, info.serviceInfo.name);
2933        }
2934        if (DEBUG_EPHEMERAL) {
2935            Slog.v(TAG, "Ephemeral resolver NOT found");
2936        }
2937        return null;
2938    }
2939
2940    private @Nullable ComponentName getEphemeralInstallerLPr() {
2941        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2942        intent.addCategory(Intent.CATEGORY_DEFAULT);
2943        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2944
2945        final int resolveFlags =
2946                MATCH_DIRECT_BOOT_AWARE
2947                | MATCH_DIRECT_BOOT_UNAWARE
2948                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2949        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2950                resolveFlags, UserHandle.USER_SYSTEM);
2951        Iterator<ResolveInfo> iter = matches.iterator();
2952        while (iter.hasNext()) {
2953            final ResolveInfo rInfo = iter.next();
2954            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
2955            if (ps != null) {
2956                final PermissionsState permissionsState = ps.getPermissionsState();
2957                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
2958                    continue;
2959                }
2960            }
2961            iter.remove();
2962        }
2963        if (matches.size() == 0) {
2964            return null;
2965        } else if (matches.size() == 1) {
2966            return matches.get(0).getComponentInfo().getComponentName();
2967        } else {
2968            throw new RuntimeException(
2969                    "There must be at most one ephemeral installer; found " + matches);
2970        }
2971    }
2972
2973    private void primeDomainVerificationsLPw(int userId) {
2974        if (DEBUG_DOMAIN_VERIFICATION) {
2975            Slog.d(TAG, "Priming domain verifications in user " + userId);
2976        }
2977
2978        SystemConfig systemConfig = SystemConfig.getInstance();
2979        ArraySet<String> packages = systemConfig.getLinkedApps();
2980
2981        for (String packageName : packages) {
2982            PackageParser.Package pkg = mPackages.get(packageName);
2983            if (pkg != null) {
2984                if (!pkg.isSystemApp()) {
2985                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2986                    continue;
2987                }
2988
2989                ArraySet<String> domains = null;
2990                for (PackageParser.Activity a : pkg.activities) {
2991                    for (ActivityIntentInfo filter : a.intents) {
2992                        if (hasValidDomains(filter)) {
2993                            if (domains == null) {
2994                                domains = new ArraySet<String>();
2995                            }
2996                            domains.addAll(filter.getHostsList());
2997                        }
2998                    }
2999                }
3000
3001                if (domains != null && domains.size() > 0) {
3002                    if (DEBUG_DOMAIN_VERIFICATION) {
3003                        Slog.v(TAG, "      + " + packageName);
3004                    }
3005                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3006                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3007                    // and then 'always' in the per-user state actually used for intent resolution.
3008                    final IntentFilterVerificationInfo ivi;
3009                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3010                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3011                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3012                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3013                } else {
3014                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3015                            + "' does not handle web links");
3016                }
3017            } else {
3018                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3019            }
3020        }
3021
3022        scheduleWritePackageRestrictionsLocked(userId);
3023        scheduleWriteSettingsLocked();
3024    }
3025
3026    private void applyFactoryDefaultBrowserLPw(int userId) {
3027        // The default browser app's package name is stored in a string resource,
3028        // with a product-specific overlay used for vendor customization.
3029        String browserPkg = mContext.getResources().getString(
3030                com.android.internal.R.string.default_browser);
3031        if (!TextUtils.isEmpty(browserPkg)) {
3032            // non-empty string => required to be a known package
3033            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3034            if (ps == null) {
3035                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3036                browserPkg = null;
3037            } else {
3038                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3039            }
3040        }
3041
3042        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3043        // default.  If there's more than one, just leave everything alone.
3044        if (browserPkg == null) {
3045            calculateDefaultBrowserLPw(userId);
3046        }
3047    }
3048
3049    private void calculateDefaultBrowserLPw(int userId) {
3050        List<String> allBrowsers = resolveAllBrowserApps(userId);
3051        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3052        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3053    }
3054
3055    private List<String> resolveAllBrowserApps(int userId) {
3056        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3057        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3058                PackageManager.MATCH_ALL, userId);
3059
3060        final int count = list.size();
3061        List<String> result = new ArrayList<String>(count);
3062        for (int i=0; i<count; i++) {
3063            ResolveInfo info = list.get(i);
3064            if (info.activityInfo == null
3065                    || !info.handleAllWebDataURI
3066                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3067                    || result.contains(info.activityInfo.packageName)) {
3068                continue;
3069            }
3070            result.add(info.activityInfo.packageName);
3071        }
3072
3073        return result;
3074    }
3075
3076    private boolean packageIsBrowser(String packageName, int userId) {
3077        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3078                PackageManager.MATCH_ALL, userId);
3079        final int N = list.size();
3080        for (int i = 0; i < N; i++) {
3081            ResolveInfo info = list.get(i);
3082            if (packageName.equals(info.activityInfo.packageName)) {
3083                return true;
3084            }
3085        }
3086        return false;
3087    }
3088
3089    private void checkDefaultBrowser() {
3090        final int myUserId = UserHandle.myUserId();
3091        final String packageName = getDefaultBrowserPackageName(myUserId);
3092        if (packageName != null) {
3093            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3094            if (info == null) {
3095                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3096                synchronized (mPackages) {
3097                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3098                }
3099            }
3100        }
3101    }
3102
3103    @Override
3104    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3105            throws RemoteException {
3106        try {
3107            return super.onTransact(code, data, reply, flags);
3108        } catch (RuntimeException e) {
3109            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3110                Slog.wtf(TAG, "Package Manager Crash", e);
3111            }
3112            throw e;
3113        }
3114    }
3115
3116    static int[] appendInts(int[] cur, int[] add) {
3117        if (add == null) return cur;
3118        if (cur == null) return add;
3119        final int N = add.length;
3120        for (int i=0; i<N; i++) {
3121            cur = appendInt(cur, add[i]);
3122        }
3123        return cur;
3124    }
3125
3126    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3127        if (!sUserManager.exists(userId)) return null;
3128        if (ps == null) {
3129            return null;
3130        }
3131        final PackageParser.Package p = ps.pkg;
3132        if (p == null) {
3133            return null;
3134        }
3135
3136        final PermissionsState permissionsState = ps.getPermissionsState();
3137
3138        // Compute GIDs only if requested
3139        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3140                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3141        // Compute granted permissions only if package has requested permissions
3142        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3143                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3144        final PackageUserState state = ps.readUserState(userId);
3145
3146        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3147                && ps.isSystem()) {
3148            flags |= MATCH_ANY_USER;
3149        }
3150
3151        return PackageParser.generatePackageInfo(p, gids, flags,
3152                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3153    }
3154
3155    @Override
3156    public void checkPackageStartable(String packageName, int userId) {
3157        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3158
3159        synchronized (mPackages) {
3160            final PackageSetting ps = mSettings.mPackages.get(packageName);
3161            if (ps == null) {
3162                throw new SecurityException("Package " + packageName + " was not found!");
3163            }
3164
3165            if (!ps.getInstalled(userId)) {
3166                throw new SecurityException(
3167                        "Package " + packageName + " was not installed for user " + userId + "!");
3168            }
3169
3170            if (mSafeMode && !ps.isSystem()) {
3171                throw new SecurityException("Package " + packageName + " not a system app!");
3172            }
3173
3174            if (mFrozenPackages.contains(packageName)) {
3175                throw new SecurityException("Package " + packageName + " is currently frozen!");
3176            }
3177
3178            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3179                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3180                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3181            }
3182        }
3183    }
3184
3185    @Override
3186    public boolean isPackageAvailable(String packageName, int userId) {
3187        if (!sUserManager.exists(userId)) return false;
3188        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3189                false /* requireFullPermission */, false /* checkShell */, "is package available");
3190        synchronized (mPackages) {
3191            PackageParser.Package p = mPackages.get(packageName);
3192            if (p != null) {
3193                final PackageSetting ps = (PackageSetting) p.mExtras;
3194                if (ps != null) {
3195                    final PackageUserState state = ps.readUserState(userId);
3196                    if (state != null) {
3197                        return PackageParser.isAvailable(state);
3198                    }
3199                }
3200            }
3201        }
3202        return false;
3203    }
3204
3205    @Override
3206    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3207        if (!sUserManager.exists(userId)) return null;
3208        flags = updateFlagsForPackage(flags, userId, packageName);
3209        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3210                false /* requireFullPermission */, false /* checkShell */, "get package info");
3211        // reader
3212        synchronized (mPackages) {
3213            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3214            PackageParser.Package p = null;
3215            if (matchFactoryOnly) {
3216                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3217                if (ps != null) {
3218                    return generatePackageInfo(ps, flags, userId);
3219                }
3220            }
3221            if (p == null) {
3222                p = mPackages.get(packageName);
3223                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3224                    return null;
3225                }
3226            }
3227            if (DEBUG_PACKAGE_INFO)
3228                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3229            if (p != null) {
3230                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3231            }
3232            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3233                final PackageSetting ps = mSettings.mPackages.get(packageName);
3234                return generatePackageInfo(ps, flags, userId);
3235            }
3236        }
3237        return null;
3238    }
3239
3240    @Override
3241    public String[] currentToCanonicalPackageNames(String[] names) {
3242        String[] out = new String[names.length];
3243        // reader
3244        synchronized (mPackages) {
3245            for (int i=names.length-1; i>=0; i--) {
3246                PackageSetting ps = mSettings.mPackages.get(names[i]);
3247                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3248            }
3249        }
3250        return out;
3251    }
3252
3253    @Override
3254    public String[] canonicalToCurrentPackageNames(String[] names) {
3255        String[] out = new String[names.length];
3256        // reader
3257        synchronized (mPackages) {
3258            for (int i=names.length-1; i>=0; i--) {
3259                String cur = mSettings.getRenamedPackageLPr(names[i]);
3260                out[i] = cur != null ? cur : names[i];
3261            }
3262        }
3263        return out;
3264    }
3265
3266    @Override
3267    public int getPackageUid(String packageName, int flags, int userId) {
3268        if (!sUserManager.exists(userId)) return -1;
3269        flags = updateFlagsForPackage(flags, userId, packageName);
3270        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3271                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3272
3273        // reader
3274        synchronized (mPackages) {
3275            final PackageParser.Package p = mPackages.get(packageName);
3276            if (p != null && p.isMatch(flags)) {
3277                return UserHandle.getUid(userId, p.applicationInfo.uid);
3278            }
3279            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3280                final PackageSetting ps = mSettings.mPackages.get(packageName);
3281                if (ps != null && ps.isMatch(flags)) {
3282                    return UserHandle.getUid(userId, ps.appId);
3283                }
3284            }
3285        }
3286
3287        return -1;
3288    }
3289
3290    @Override
3291    public int[] getPackageGids(String packageName, int flags, int userId) {
3292        if (!sUserManager.exists(userId)) return null;
3293        flags = updateFlagsForPackage(flags, userId, packageName);
3294        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3295                false /* requireFullPermission */, false /* checkShell */,
3296                "getPackageGids");
3297
3298        // reader
3299        synchronized (mPackages) {
3300            final PackageParser.Package p = mPackages.get(packageName);
3301            if (p != null && p.isMatch(flags)) {
3302                PackageSetting ps = (PackageSetting) p.mExtras;
3303                // TODO: Shouldn't this be checking for package installed state for userId and
3304                // return null?
3305                return ps.getPermissionsState().computeGids(userId);
3306            }
3307            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3308                final PackageSetting ps = mSettings.mPackages.get(packageName);
3309                if (ps != null && ps.isMatch(flags)) {
3310                    return ps.getPermissionsState().computeGids(userId);
3311                }
3312            }
3313        }
3314
3315        return null;
3316    }
3317
3318    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3319        if (bp.perm != null) {
3320            return PackageParser.generatePermissionInfo(bp.perm, flags);
3321        }
3322        PermissionInfo pi = new PermissionInfo();
3323        pi.name = bp.name;
3324        pi.packageName = bp.sourcePackage;
3325        pi.nonLocalizedLabel = bp.name;
3326        pi.protectionLevel = bp.protectionLevel;
3327        return pi;
3328    }
3329
3330    @Override
3331    public PermissionInfo getPermissionInfo(String name, int flags) {
3332        // reader
3333        synchronized (mPackages) {
3334            final BasePermission p = mSettings.mPermissions.get(name);
3335            if (p != null) {
3336                return generatePermissionInfo(p, flags);
3337            }
3338            return null;
3339        }
3340    }
3341
3342    @Override
3343    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3344            int flags) {
3345        // reader
3346        synchronized (mPackages) {
3347            if (group != null && !mPermissionGroups.containsKey(group)) {
3348                // This is thrown as NameNotFoundException
3349                return null;
3350            }
3351
3352            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3353            for (BasePermission p : mSettings.mPermissions.values()) {
3354                if (group == null) {
3355                    if (p.perm == null || p.perm.info.group == null) {
3356                        out.add(generatePermissionInfo(p, flags));
3357                    }
3358                } else {
3359                    if (p.perm != null && group.equals(p.perm.info.group)) {
3360                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3361                    }
3362                }
3363            }
3364            return new ParceledListSlice<>(out);
3365        }
3366    }
3367
3368    @Override
3369    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3370        // reader
3371        synchronized (mPackages) {
3372            return PackageParser.generatePermissionGroupInfo(
3373                    mPermissionGroups.get(name), flags);
3374        }
3375    }
3376
3377    @Override
3378    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3379        // reader
3380        synchronized (mPackages) {
3381            final int N = mPermissionGroups.size();
3382            ArrayList<PermissionGroupInfo> out
3383                    = new ArrayList<PermissionGroupInfo>(N);
3384            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3385                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3386            }
3387            return new ParceledListSlice<>(out);
3388        }
3389    }
3390
3391    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3392            int userId) {
3393        if (!sUserManager.exists(userId)) return null;
3394        PackageSetting ps = mSettings.mPackages.get(packageName);
3395        if (ps != null) {
3396            if (ps.pkg == null) {
3397                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3398                if (pInfo != null) {
3399                    return pInfo.applicationInfo;
3400                }
3401                return null;
3402            }
3403            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3404                    ps.readUserState(userId), userId);
3405        }
3406        return null;
3407    }
3408
3409    @Override
3410    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3411        if (!sUserManager.exists(userId)) return null;
3412        flags = updateFlagsForApplication(flags, userId, packageName);
3413        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3414                false /* requireFullPermission */, false /* checkShell */, "get application info");
3415        // writer
3416        synchronized (mPackages) {
3417            PackageParser.Package p = mPackages.get(packageName);
3418            if (DEBUG_PACKAGE_INFO) Log.v(
3419                    TAG, "getApplicationInfo " + packageName
3420                    + ": " + p);
3421            if (p != null) {
3422                PackageSetting ps = mSettings.mPackages.get(packageName);
3423                if (ps == null) return null;
3424                // Note: isEnabledLP() does not apply here - always return info
3425                return PackageParser.generateApplicationInfo(
3426                        p, flags, ps.readUserState(userId), userId);
3427            }
3428            if ("android".equals(packageName)||"system".equals(packageName)) {
3429                return mAndroidApplication;
3430            }
3431            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3432                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3433            }
3434        }
3435        return null;
3436    }
3437
3438    @Override
3439    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3440            final IPackageDataObserver observer) {
3441        mContext.enforceCallingOrSelfPermission(
3442                android.Manifest.permission.CLEAR_APP_CACHE, null);
3443        // Queue up an async operation since clearing cache may take a little while.
3444        mHandler.post(new Runnable() {
3445            public void run() {
3446                mHandler.removeCallbacks(this);
3447                boolean success = true;
3448                synchronized (mInstallLock) {
3449                    try {
3450                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3451                    } catch (InstallerException e) {
3452                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3453                        success = false;
3454                    }
3455                }
3456                if (observer != null) {
3457                    try {
3458                        observer.onRemoveCompleted(null, success);
3459                    } catch (RemoteException e) {
3460                        Slog.w(TAG, "RemoveException when invoking call back");
3461                    }
3462                }
3463            }
3464        });
3465    }
3466
3467    @Override
3468    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3469            final IntentSender pi) {
3470        mContext.enforceCallingOrSelfPermission(
3471                android.Manifest.permission.CLEAR_APP_CACHE, null);
3472        // Queue up an async operation since clearing cache may take a little while.
3473        mHandler.post(new Runnable() {
3474            public void run() {
3475                mHandler.removeCallbacks(this);
3476                boolean success = true;
3477                synchronized (mInstallLock) {
3478                    try {
3479                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3480                    } catch (InstallerException e) {
3481                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3482                        success = false;
3483                    }
3484                }
3485                if(pi != null) {
3486                    try {
3487                        // Callback via pending intent
3488                        int code = success ? 1 : 0;
3489                        pi.sendIntent(null, code, null,
3490                                null, null);
3491                    } catch (SendIntentException e1) {
3492                        Slog.i(TAG, "Failed to send pending intent");
3493                    }
3494                }
3495            }
3496        });
3497    }
3498
3499    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3500        synchronized (mInstallLock) {
3501            try {
3502                mInstaller.freeCache(volumeUuid, freeStorageSize);
3503            } catch (InstallerException e) {
3504                throw new IOException("Failed to free enough space", e);
3505            }
3506        }
3507    }
3508
3509    /**
3510     * Update given flags based on encryption status of current user.
3511     */
3512    private int updateFlags(int flags, int userId) {
3513        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3514                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3515            // Caller expressed an explicit opinion about what encryption
3516            // aware/unaware components they want to see, so fall through and
3517            // give them what they want
3518        } else {
3519            // Caller expressed no opinion, so match based on user state
3520            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3521                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3522            } else {
3523                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3524            }
3525        }
3526        return flags;
3527    }
3528
3529    private UserManagerInternal getUserManagerInternal() {
3530        if (mUserManagerInternal == null) {
3531            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3532        }
3533        return mUserManagerInternal;
3534    }
3535
3536    /**
3537     * Update given flags when being used to request {@link PackageInfo}.
3538     */
3539    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3540        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3541        boolean triaged = true;
3542        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3543                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3544            // Caller is asking for component details, so they'd better be
3545            // asking for specific encryption matching behavior, or be triaged
3546            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3547                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3548                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3549                triaged = false;
3550            }
3551        }
3552        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3553                | PackageManager.MATCH_SYSTEM_ONLY
3554                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3555            triaged = false;
3556        }
3557        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3558            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3559                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3560                    + Debug.getCallers(5));
3561        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3562                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3563            // If the caller wants all packages and has a restricted profile associated with it,
3564            // then match all users. This is to make sure that launchers that need to access work
3565            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3566            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3567            flags |= PackageManager.MATCH_ANY_USER;
3568        }
3569        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3570            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3571                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3572        }
3573        return updateFlags(flags, userId);
3574    }
3575
3576    /**
3577     * Update given flags when being used to request {@link ApplicationInfo}.
3578     */
3579    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3580        return updateFlagsForPackage(flags, userId, cookie);
3581    }
3582
3583    /**
3584     * Update given flags when being used to request {@link ComponentInfo}.
3585     */
3586    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3587        if (cookie instanceof Intent) {
3588            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3589                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3590            }
3591        }
3592
3593        boolean triaged = true;
3594        // Caller is asking for component details, so they'd better be
3595        // asking for specific encryption matching behavior, or be triaged
3596        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3597                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3598                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3599            triaged = false;
3600        }
3601        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3602            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3603                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3604        }
3605
3606        return updateFlags(flags, userId);
3607    }
3608
3609    /**
3610     * Update given flags when being used to request {@link ResolveInfo}.
3611     */
3612    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3613        // Safe mode means we shouldn't match any third-party components
3614        if (mSafeMode) {
3615            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3616        }
3617
3618        return updateFlagsForComponent(flags, userId, cookie);
3619    }
3620
3621    @Override
3622    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3623        if (!sUserManager.exists(userId)) return null;
3624        flags = updateFlagsForComponent(flags, userId, component);
3625        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3626                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3627        synchronized (mPackages) {
3628            PackageParser.Activity a = mActivities.mActivities.get(component);
3629
3630            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3631            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3632                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3633                if (ps == null) return null;
3634                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3635                        userId);
3636            }
3637            if (mResolveComponentName.equals(component)) {
3638                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3639                        new PackageUserState(), userId);
3640            }
3641        }
3642        return null;
3643    }
3644
3645    @Override
3646    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3647            String resolvedType) {
3648        synchronized (mPackages) {
3649            if (component.equals(mResolveComponentName)) {
3650                // The resolver supports EVERYTHING!
3651                return true;
3652            }
3653            PackageParser.Activity a = mActivities.mActivities.get(component);
3654            if (a == null) {
3655                return false;
3656            }
3657            for (int i=0; i<a.intents.size(); i++) {
3658                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3659                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3660                    return true;
3661                }
3662            }
3663            return false;
3664        }
3665    }
3666
3667    @Override
3668    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3669        if (!sUserManager.exists(userId)) return null;
3670        flags = updateFlagsForComponent(flags, userId, component);
3671        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3672                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3673        synchronized (mPackages) {
3674            PackageParser.Activity a = mReceivers.mActivities.get(component);
3675            if (DEBUG_PACKAGE_INFO) Log.v(
3676                TAG, "getReceiverInfo " + component + ": " + a);
3677            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3678                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3679                if (ps == null) return null;
3680                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3681                        userId);
3682            }
3683        }
3684        return null;
3685    }
3686
3687    @Override
3688    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3689        if (!sUserManager.exists(userId)) return null;
3690        flags = updateFlagsForComponent(flags, userId, component);
3691        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3692                false /* requireFullPermission */, false /* checkShell */, "get service info");
3693        synchronized (mPackages) {
3694            PackageParser.Service s = mServices.mServices.get(component);
3695            if (DEBUG_PACKAGE_INFO) Log.v(
3696                TAG, "getServiceInfo " + component + ": " + s);
3697            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3698                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3699                if (ps == null) return null;
3700                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3701                        userId);
3702            }
3703        }
3704        return null;
3705    }
3706
3707    @Override
3708    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3709        if (!sUserManager.exists(userId)) return null;
3710        flags = updateFlagsForComponent(flags, userId, component);
3711        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3712                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3713        synchronized (mPackages) {
3714            PackageParser.Provider p = mProviders.mProviders.get(component);
3715            if (DEBUG_PACKAGE_INFO) Log.v(
3716                TAG, "getProviderInfo " + component + ": " + p);
3717            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3718                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3719                if (ps == null) return null;
3720                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3721                        userId);
3722            }
3723        }
3724        return null;
3725    }
3726
3727    @Override
3728    public String[] getSystemSharedLibraryNames() {
3729        Set<String> libSet;
3730        synchronized (mPackages) {
3731            libSet = mSharedLibraries.keySet();
3732            int size = libSet.size();
3733            if (size > 0) {
3734                String[] libs = new String[size];
3735                libSet.toArray(libs);
3736                return libs;
3737            }
3738        }
3739        return null;
3740    }
3741
3742    @Override
3743    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3744        synchronized (mPackages) {
3745            return mServicesSystemSharedLibraryPackageName;
3746        }
3747    }
3748
3749    @Override
3750    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3751        synchronized (mPackages) {
3752            return mSharedSystemSharedLibraryPackageName;
3753        }
3754    }
3755
3756    @Override
3757    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3758        synchronized (mPackages) {
3759            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3760
3761            final FeatureInfo fi = new FeatureInfo();
3762            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3763                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3764            res.add(fi);
3765
3766            return new ParceledListSlice<>(res);
3767        }
3768    }
3769
3770    @Override
3771    public boolean hasSystemFeature(String name, int version) {
3772        synchronized (mPackages) {
3773            final FeatureInfo feat = mAvailableFeatures.get(name);
3774            if (feat == null) {
3775                return false;
3776            } else {
3777                return feat.version >= version;
3778            }
3779        }
3780    }
3781
3782    @Override
3783    public int checkPermission(String permName, String pkgName, int userId) {
3784        if (!sUserManager.exists(userId)) {
3785            return PackageManager.PERMISSION_DENIED;
3786        }
3787
3788        synchronized (mPackages) {
3789            final PackageParser.Package p = mPackages.get(pkgName);
3790            if (p != null && p.mExtras != null) {
3791                final PackageSetting ps = (PackageSetting) p.mExtras;
3792                final PermissionsState permissionsState = ps.getPermissionsState();
3793                if (permissionsState.hasPermission(permName, userId)) {
3794                    return PackageManager.PERMISSION_GRANTED;
3795                }
3796                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3797                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3798                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3799                    return PackageManager.PERMISSION_GRANTED;
3800                }
3801            }
3802        }
3803
3804        return PackageManager.PERMISSION_DENIED;
3805    }
3806
3807    @Override
3808    public int checkUidPermission(String permName, int uid) {
3809        final int userId = UserHandle.getUserId(uid);
3810
3811        if (!sUserManager.exists(userId)) {
3812            return PackageManager.PERMISSION_DENIED;
3813        }
3814
3815        synchronized (mPackages) {
3816            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3817            if (obj != null) {
3818                final SettingBase ps = (SettingBase) obj;
3819                final PermissionsState permissionsState = ps.getPermissionsState();
3820                if (permissionsState.hasPermission(permName, userId)) {
3821                    return PackageManager.PERMISSION_GRANTED;
3822                }
3823                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3824                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3825                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3826                    return PackageManager.PERMISSION_GRANTED;
3827                }
3828            } else {
3829                ArraySet<String> perms = mSystemPermissions.get(uid);
3830                if (perms != null) {
3831                    if (perms.contains(permName)) {
3832                        return PackageManager.PERMISSION_GRANTED;
3833                    }
3834                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3835                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3836                        return PackageManager.PERMISSION_GRANTED;
3837                    }
3838                }
3839            }
3840        }
3841
3842        return PackageManager.PERMISSION_DENIED;
3843    }
3844
3845    @Override
3846    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3847        if (UserHandle.getCallingUserId() != userId) {
3848            mContext.enforceCallingPermission(
3849                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3850                    "isPermissionRevokedByPolicy for user " + userId);
3851        }
3852
3853        if (checkPermission(permission, packageName, userId)
3854                == PackageManager.PERMISSION_GRANTED) {
3855            return false;
3856        }
3857
3858        final long identity = Binder.clearCallingIdentity();
3859        try {
3860            final int flags = getPermissionFlags(permission, packageName, userId);
3861            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3862        } finally {
3863            Binder.restoreCallingIdentity(identity);
3864        }
3865    }
3866
3867    @Override
3868    public String getPermissionControllerPackageName() {
3869        synchronized (mPackages) {
3870            return mRequiredInstallerPackage;
3871        }
3872    }
3873
3874    /**
3875     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3876     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3877     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3878     * @param message the message to log on security exception
3879     */
3880    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3881            boolean checkShell, String message) {
3882        if (userId < 0) {
3883            throw new IllegalArgumentException("Invalid userId " + userId);
3884        }
3885        if (checkShell) {
3886            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3887        }
3888        if (userId == UserHandle.getUserId(callingUid)) return;
3889        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3890            if (requireFullPermission) {
3891                mContext.enforceCallingOrSelfPermission(
3892                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3893            } else {
3894                try {
3895                    mContext.enforceCallingOrSelfPermission(
3896                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3897                } catch (SecurityException se) {
3898                    mContext.enforceCallingOrSelfPermission(
3899                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3900                }
3901            }
3902        }
3903    }
3904
3905    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3906        if (callingUid == Process.SHELL_UID) {
3907            if (userHandle >= 0
3908                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3909                throw new SecurityException("Shell does not have permission to access user "
3910                        + userHandle);
3911            } else if (userHandle < 0) {
3912                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3913                        + Debug.getCallers(3));
3914            }
3915        }
3916    }
3917
3918    private BasePermission findPermissionTreeLP(String permName) {
3919        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3920            if (permName.startsWith(bp.name) &&
3921                    permName.length() > bp.name.length() &&
3922                    permName.charAt(bp.name.length()) == '.') {
3923                return bp;
3924            }
3925        }
3926        return null;
3927    }
3928
3929    private BasePermission checkPermissionTreeLP(String permName) {
3930        if (permName != null) {
3931            BasePermission bp = findPermissionTreeLP(permName);
3932            if (bp != null) {
3933                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3934                    return bp;
3935                }
3936                throw new SecurityException("Calling uid "
3937                        + Binder.getCallingUid()
3938                        + " is not allowed to add to permission tree "
3939                        + bp.name + " owned by uid " + bp.uid);
3940            }
3941        }
3942        throw new SecurityException("No permission tree found for " + permName);
3943    }
3944
3945    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3946        if (s1 == null) {
3947            return s2 == null;
3948        }
3949        if (s2 == null) {
3950            return false;
3951        }
3952        if (s1.getClass() != s2.getClass()) {
3953            return false;
3954        }
3955        return s1.equals(s2);
3956    }
3957
3958    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3959        if (pi1.icon != pi2.icon) return false;
3960        if (pi1.logo != pi2.logo) return false;
3961        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3962        if (!compareStrings(pi1.name, pi2.name)) return false;
3963        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3964        // We'll take care of setting this one.
3965        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3966        // These are not currently stored in settings.
3967        //if (!compareStrings(pi1.group, pi2.group)) return false;
3968        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3969        //if (pi1.labelRes != pi2.labelRes) return false;
3970        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3971        return true;
3972    }
3973
3974    int permissionInfoFootprint(PermissionInfo info) {
3975        int size = info.name.length();
3976        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3977        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3978        return size;
3979    }
3980
3981    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3982        int size = 0;
3983        for (BasePermission perm : mSettings.mPermissions.values()) {
3984            if (perm.uid == tree.uid) {
3985                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3986            }
3987        }
3988        return size;
3989    }
3990
3991    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3992        // We calculate the max size of permissions defined by this uid and throw
3993        // if that plus the size of 'info' would exceed our stated maximum.
3994        if (tree.uid != Process.SYSTEM_UID) {
3995            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3996            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3997                throw new SecurityException("Permission tree size cap exceeded");
3998            }
3999        }
4000    }
4001
4002    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4003        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4004            throw new SecurityException("Label must be specified in permission");
4005        }
4006        BasePermission tree = checkPermissionTreeLP(info.name);
4007        BasePermission bp = mSettings.mPermissions.get(info.name);
4008        boolean added = bp == null;
4009        boolean changed = true;
4010        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4011        if (added) {
4012            enforcePermissionCapLocked(info, tree);
4013            bp = new BasePermission(info.name, tree.sourcePackage,
4014                    BasePermission.TYPE_DYNAMIC);
4015        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4016            throw new SecurityException(
4017                    "Not allowed to modify non-dynamic permission "
4018                    + info.name);
4019        } else {
4020            if (bp.protectionLevel == fixedLevel
4021                    && bp.perm.owner.equals(tree.perm.owner)
4022                    && bp.uid == tree.uid
4023                    && comparePermissionInfos(bp.perm.info, info)) {
4024                changed = false;
4025            }
4026        }
4027        bp.protectionLevel = fixedLevel;
4028        info = new PermissionInfo(info);
4029        info.protectionLevel = fixedLevel;
4030        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4031        bp.perm.info.packageName = tree.perm.info.packageName;
4032        bp.uid = tree.uid;
4033        if (added) {
4034            mSettings.mPermissions.put(info.name, bp);
4035        }
4036        if (changed) {
4037            if (!async) {
4038                mSettings.writeLPr();
4039            } else {
4040                scheduleWriteSettingsLocked();
4041            }
4042        }
4043        return added;
4044    }
4045
4046    @Override
4047    public boolean addPermission(PermissionInfo info) {
4048        synchronized (mPackages) {
4049            return addPermissionLocked(info, false);
4050        }
4051    }
4052
4053    @Override
4054    public boolean addPermissionAsync(PermissionInfo info) {
4055        synchronized (mPackages) {
4056            return addPermissionLocked(info, true);
4057        }
4058    }
4059
4060    @Override
4061    public void removePermission(String name) {
4062        synchronized (mPackages) {
4063            checkPermissionTreeLP(name);
4064            BasePermission bp = mSettings.mPermissions.get(name);
4065            if (bp != null) {
4066                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4067                    throw new SecurityException(
4068                            "Not allowed to modify non-dynamic permission "
4069                            + name);
4070                }
4071                mSettings.mPermissions.remove(name);
4072                mSettings.writeLPr();
4073            }
4074        }
4075    }
4076
4077    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4078            BasePermission bp) {
4079        int index = pkg.requestedPermissions.indexOf(bp.name);
4080        if (index == -1) {
4081            throw new SecurityException("Package " + pkg.packageName
4082                    + " has not requested permission " + bp.name);
4083        }
4084        if (!bp.isRuntime() && !bp.isDevelopment()) {
4085            throw new SecurityException("Permission " + bp.name
4086                    + " is not a changeable permission type");
4087        }
4088    }
4089
4090    @Override
4091    public void grantRuntimePermission(String packageName, String name, final int userId) {
4092        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4093    }
4094
4095    private void grantRuntimePermission(String packageName, String name, final int userId,
4096            boolean overridePolicy) {
4097        if (!sUserManager.exists(userId)) {
4098            Log.e(TAG, "No such user:" + userId);
4099            return;
4100        }
4101
4102        mContext.enforceCallingOrSelfPermission(
4103                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4104                "grantRuntimePermission");
4105
4106        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4107                true /* requireFullPermission */, true /* checkShell */,
4108                "grantRuntimePermission");
4109
4110        final int uid;
4111        final SettingBase sb;
4112
4113        synchronized (mPackages) {
4114            final PackageParser.Package pkg = mPackages.get(packageName);
4115            if (pkg == null) {
4116                throw new IllegalArgumentException("Unknown package: " + packageName);
4117            }
4118
4119            final BasePermission bp = mSettings.mPermissions.get(name);
4120            if (bp == null) {
4121                throw new IllegalArgumentException("Unknown permission: " + name);
4122            }
4123
4124            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4125
4126            // If a permission review is required for legacy apps we represent
4127            // their permissions as always granted runtime ones since we need
4128            // to keep the review required permission flag per user while an
4129            // install permission's state is shared across all users.
4130            if (mPermissionReviewRequired
4131                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4132                    && bp.isRuntime()) {
4133                return;
4134            }
4135
4136            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4137            sb = (SettingBase) pkg.mExtras;
4138            if (sb == null) {
4139                throw new IllegalArgumentException("Unknown package: " + packageName);
4140            }
4141
4142            final PermissionsState permissionsState = sb.getPermissionsState();
4143
4144            final int flags = permissionsState.getPermissionFlags(name, userId);
4145            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4146                throw new SecurityException("Cannot grant system fixed permission "
4147                        + name + " for package " + packageName);
4148            }
4149            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4150                throw new SecurityException("Cannot grant policy fixed permission "
4151                        + name + " for package " + packageName);
4152            }
4153
4154            if (bp.isDevelopment()) {
4155                // Development permissions must be handled specially, since they are not
4156                // normal runtime permissions.  For now they apply to all users.
4157                if (permissionsState.grantInstallPermission(bp) !=
4158                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4159                    scheduleWriteSettingsLocked();
4160                }
4161                return;
4162            }
4163
4164            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4165                throw new SecurityException("Cannot grant non-ephemeral permission"
4166                        + name + " for package " + packageName);
4167            }
4168
4169            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4170                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4171                return;
4172            }
4173
4174            final int result = permissionsState.grantRuntimePermission(bp, userId);
4175            switch (result) {
4176                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4177                    return;
4178                }
4179
4180                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4181                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4182                    mHandler.post(new Runnable() {
4183                        @Override
4184                        public void run() {
4185                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4186                        }
4187                    });
4188                }
4189                break;
4190            }
4191
4192            if (bp.isRuntime()) {
4193                logPermissionGranted(mContext, name, packageName);
4194            }
4195
4196            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4197
4198            // Not critical if that is lost - app has to request again.
4199            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4200        }
4201
4202        // Only need to do this if user is initialized. Otherwise it's a new user
4203        // and there are no processes running as the user yet and there's no need
4204        // to make an expensive call to remount processes for the changed permissions.
4205        if (READ_EXTERNAL_STORAGE.equals(name)
4206                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4207            final long token = Binder.clearCallingIdentity();
4208            try {
4209                if (sUserManager.isInitialized(userId)) {
4210                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4211                            StorageManagerInternal.class);
4212                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4213                }
4214            } finally {
4215                Binder.restoreCallingIdentity(token);
4216            }
4217        }
4218    }
4219
4220    @Override
4221    public void revokeRuntimePermission(String packageName, String name, int userId) {
4222        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4223    }
4224
4225    private void revokeRuntimePermission(String packageName, String name, int userId,
4226            boolean overridePolicy) {
4227        if (!sUserManager.exists(userId)) {
4228            Log.e(TAG, "No such user:" + userId);
4229            return;
4230        }
4231
4232        mContext.enforceCallingOrSelfPermission(
4233                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4234                "revokeRuntimePermission");
4235
4236        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4237                true /* requireFullPermission */, true /* checkShell */,
4238                "revokeRuntimePermission");
4239
4240        final int appId;
4241
4242        synchronized (mPackages) {
4243            final PackageParser.Package pkg = mPackages.get(packageName);
4244            if (pkg == null) {
4245                throw new IllegalArgumentException("Unknown package: " + packageName);
4246            }
4247
4248            final BasePermission bp = mSettings.mPermissions.get(name);
4249            if (bp == null) {
4250                throw new IllegalArgumentException("Unknown permission: " + name);
4251            }
4252
4253            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4254
4255            // If a permission review is required for legacy apps we represent
4256            // their permissions as always granted runtime ones since we need
4257            // to keep the review required permission flag per user while an
4258            // install permission's state is shared across all users.
4259            if (mPermissionReviewRequired
4260                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4261                    && bp.isRuntime()) {
4262                return;
4263            }
4264
4265            SettingBase sb = (SettingBase) pkg.mExtras;
4266            if (sb == null) {
4267                throw new IllegalArgumentException("Unknown package: " + packageName);
4268            }
4269
4270            final PermissionsState permissionsState = sb.getPermissionsState();
4271
4272            final int flags = permissionsState.getPermissionFlags(name, userId);
4273            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4274                throw new SecurityException("Cannot revoke system fixed permission "
4275                        + name + " for package " + packageName);
4276            }
4277            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4278                throw new SecurityException("Cannot revoke policy fixed permission "
4279                        + name + " for package " + packageName);
4280            }
4281
4282            if (bp.isDevelopment()) {
4283                // Development permissions must be handled specially, since they are not
4284                // normal runtime permissions.  For now they apply to all users.
4285                if (permissionsState.revokeInstallPermission(bp) !=
4286                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4287                    scheduleWriteSettingsLocked();
4288                }
4289                return;
4290            }
4291
4292            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4293                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4294                return;
4295            }
4296
4297            if (bp.isRuntime()) {
4298                logPermissionRevoked(mContext, name, packageName);
4299            }
4300
4301            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4302
4303            // Critical, after this call app should never have the permission.
4304            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4305
4306            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4307        }
4308
4309        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4310    }
4311
4312    /**
4313     * Get the first event id for the permission.
4314     *
4315     * <p>There are four events for each permission: <ul>
4316     *     <li>Request permission: first id + 0</li>
4317     *     <li>Grant permission: first id + 1</li>
4318     *     <li>Request for permission denied: first id + 2</li>
4319     *     <li>Revoke permission: first id + 3</li>
4320     * </ul></p>
4321     *
4322     * @param name name of the permission
4323     *
4324     * @return The first event id for the permission
4325     */
4326    private static int getBaseEventId(@NonNull String name) {
4327        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4328
4329        if (eventIdIndex == -1) {
4330            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4331                    || "user".equals(Build.TYPE)) {
4332                Log.i(TAG, "Unknown permission " + name);
4333
4334                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4335            } else {
4336                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4337                //
4338                // Also update
4339                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4340                // - metrics_constants.proto
4341                throw new IllegalStateException("Unknown permission " + name);
4342            }
4343        }
4344
4345        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4346    }
4347
4348    /**
4349     * Log that a permission was revoked.
4350     *
4351     * @param context Context of the caller
4352     * @param name name of the permission
4353     * @param packageName package permission if for
4354     */
4355    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4356            @NonNull String packageName) {
4357        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4358    }
4359
4360    /**
4361     * Log that a permission request was granted.
4362     *
4363     * @param context Context of the caller
4364     * @param name name of the permission
4365     * @param packageName package permission if for
4366     */
4367    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4368            @NonNull String packageName) {
4369        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4370    }
4371
4372    @Override
4373    public void resetRuntimePermissions() {
4374        mContext.enforceCallingOrSelfPermission(
4375                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4376                "revokeRuntimePermission");
4377
4378        int callingUid = Binder.getCallingUid();
4379        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4380            mContext.enforceCallingOrSelfPermission(
4381                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4382                    "resetRuntimePermissions");
4383        }
4384
4385        synchronized (mPackages) {
4386            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4387            for (int userId : UserManagerService.getInstance().getUserIds()) {
4388                final int packageCount = mPackages.size();
4389                for (int i = 0; i < packageCount; i++) {
4390                    PackageParser.Package pkg = mPackages.valueAt(i);
4391                    if (!(pkg.mExtras instanceof PackageSetting)) {
4392                        continue;
4393                    }
4394                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4395                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4396                }
4397            }
4398        }
4399    }
4400
4401    @Override
4402    public int getPermissionFlags(String name, String packageName, int userId) {
4403        if (!sUserManager.exists(userId)) {
4404            return 0;
4405        }
4406
4407        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4408
4409        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4410                true /* requireFullPermission */, false /* checkShell */,
4411                "getPermissionFlags");
4412
4413        synchronized (mPackages) {
4414            final PackageParser.Package pkg = mPackages.get(packageName);
4415            if (pkg == null) {
4416                return 0;
4417            }
4418
4419            final BasePermission bp = mSettings.mPermissions.get(name);
4420            if (bp == null) {
4421                return 0;
4422            }
4423
4424            SettingBase sb = (SettingBase) pkg.mExtras;
4425            if (sb == null) {
4426                return 0;
4427            }
4428
4429            PermissionsState permissionsState = sb.getPermissionsState();
4430            return permissionsState.getPermissionFlags(name, userId);
4431        }
4432    }
4433
4434    @Override
4435    public void updatePermissionFlags(String name, String packageName, int flagMask,
4436            int flagValues, int userId) {
4437        if (!sUserManager.exists(userId)) {
4438            return;
4439        }
4440
4441        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4442
4443        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4444                true /* requireFullPermission */, true /* checkShell */,
4445                "updatePermissionFlags");
4446
4447        // Only the system can change these flags and nothing else.
4448        if (getCallingUid() != Process.SYSTEM_UID) {
4449            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4450            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4451            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4452            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4453            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4454        }
4455
4456        synchronized (mPackages) {
4457            final PackageParser.Package pkg = mPackages.get(packageName);
4458            if (pkg == null) {
4459                throw new IllegalArgumentException("Unknown package: " + packageName);
4460            }
4461
4462            final BasePermission bp = mSettings.mPermissions.get(name);
4463            if (bp == null) {
4464                throw new IllegalArgumentException("Unknown permission: " + name);
4465            }
4466
4467            SettingBase sb = (SettingBase) pkg.mExtras;
4468            if (sb == null) {
4469                throw new IllegalArgumentException("Unknown package: " + packageName);
4470            }
4471
4472            PermissionsState permissionsState = sb.getPermissionsState();
4473
4474            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4475
4476            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4477                // Install and runtime permissions are stored in different places,
4478                // so figure out what permission changed and persist the change.
4479                if (permissionsState.getInstallPermissionState(name) != null) {
4480                    scheduleWriteSettingsLocked();
4481                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4482                        || hadState) {
4483                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4484                }
4485            }
4486        }
4487    }
4488
4489    /**
4490     * Update the permission flags for all packages and runtime permissions of a user in order
4491     * to allow device or profile owner to remove POLICY_FIXED.
4492     */
4493    @Override
4494    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4495        if (!sUserManager.exists(userId)) {
4496            return;
4497        }
4498
4499        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4500
4501        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4502                true /* requireFullPermission */, true /* checkShell */,
4503                "updatePermissionFlagsForAllApps");
4504
4505        // Only the system can change system fixed flags.
4506        if (getCallingUid() != Process.SYSTEM_UID) {
4507            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4508            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4509        }
4510
4511        synchronized (mPackages) {
4512            boolean changed = false;
4513            final int packageCount = mPackages.size();
4514            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4515                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4516                SettingBase sb = (SettingBase) pkg.mExtras;
4517                if (sb == null) {
4518                    continue;
4519                }
4520                PermissionsState permissionsState = sb.getPermissionsState();
4521                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4522                        userId, flagMask, flagValues);
4523            }
4524            if (changed) {
4525                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4526            }
4527        }
4528    }
4529
4530    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4531        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4532                != PackageManager.PERMISSION_GRANTED
4533            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4534                != PackageManager.PERMISSION_GRANTED) {
4535            throw new SecurityException(message + " requires "
4536                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4537                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4538        }
4539    }
4540
4541    @Override
4542    public boolean shouldShowRequestPermissionRationale(String permissionName,
4543            String packageName, int userId) {
4544        if (UserHandle.getCallingUserId() != userId) {
4545            mContext.enforceCallingPermission(
4546                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4547                    "canShowRequestPermissionRationale for user " + userId);
4548        }
4549
4550        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4551        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4552            return false;
4553        }
4554
4555        if (checkPermission(permissionName, packageName, userId)
4556                == PackageManager.PERMISSION_GRANTED) {
4557            return false;
4558        }
4559
4560        final int flags;
4561
4562        final long identity = Binder.clearCallingIdentity();
4563        try {
4564            flags = getPermissionFlags(permissionName,
4565                    packageName, userId);
4566        } finally {
4567            Binder.restoreCallingIdentity(identity);
4568        }
4569
4570        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4571                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4572                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4573
4574        if ((flags & fixedFlags) != 0) {
4575            return false;
4576        }
4577
4578        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4579    }
4580
4581    @Override
4582    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4583        mContext.enforceCallingOrSelfPermission(
4584                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4585                "addOnPermissionsChangeListener");
4586
4587        synchronized (mPackages) {
4588            mOnPermissionChangeListeners.addListenerLocked(listener);
4589        }
4590    }
4591
4592    @Override
4593    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4594        synchronized (mPackages) {
4595            mOnPermissionChangeListeners.removeListenerLocked(listener);
4596        }
4597    }
4598
4599    @Override
4600    public boolean isProtectedBroadcast(String actionName) {
4601        synchronized (mPackages) {
4602            if (mProtectedBroadcasts.contains(actionName)) {
4603                return true;
4604            } else if (actionName != null) {
4605                // TODO: remove these terrible hacks
4606                if (actionName.startsWith("android.net.netmon.lingerExpired")
4607                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4608                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4609                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4610                    return true;
4611                }
4612            }
4613        }
4614        return false;
4615    }
4616
4617    @Override
4618    public int checkSignatures(String pkg1, String pkg2) {
4619        synchronized (mPackages) {
4620            final PackageParser.Package p1 = mPackages.get(pkg1);
4621            final PackageParser.Package p2 = mPackages.get(pkg2);
4622            if (p1 == null || p1.mExtras == null
4623                    || p2 == null || p2.mExtras == null) {
4624                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4625            }
4626            return compareSignatures(p1.mSignatures, p2.mSignatures);
4627        }
4628    }
4629
4630    @Override
4631    public int checkUidSignatures(int uid1, int uid2) {
4632        // Map to base uids.
4633        uid1 = UserHandle.getAppId(uid1);
4634        uid2 = UserHandle.getAppId(uid2);
4635        // reader
4636        synchronized (mPackages) {
4637            Signature[] s1;
4638            Signature[] s2;
4639            Object obj = mSettings.getUserIdLPr(uid1);
4640            if (obj != null) {
4641                if (obj instanceof SharedUserSetting) {
4642                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4643                } else if (obj instanceof PackageSetting) {
4644                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4645                } else {
4646                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4647                }
4648            } else {
4649                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4650            }
4651            obj = mSettings.getUserIdLPr(uid2);
4652            if (obj != null) {
4653                if (obj instanceof SharedUserSetting) {
4654                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4655                } else if (obj instanceof PackageSetting) {
4656                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4657                } else {
4658                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4659                }
4660            } else {
4661                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4662            }
4663            return compareSignatures(s1, s2);
4664        }
4665    }
4666
4667    /**
4668     * This method should typically only be used when granting or revoking
4669     * permissions, since the app may immediately restart after this call.
4670     * <p>
4671     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4672     * guard your work against the app being relaunched.
4673     */
4674    private void killUid(int appId, int userId, String reason) {
4675        final long identity = Binder.clearCallingIdentity();
4676        try {
4677            IActivityManager am = ActivityManager.getService();
4678            if (am != null) {
4679                try {
4680                    am.killUid(appId, userId, reason);
4681                } catch (RemoteException e) {
4682                    /* ignore - same process */
4683                }
4684            }
4685        } finally {
4686            Binder.restoreCallingIdentity(identity);
4687        }
4688    }
4689
4690    /**
4691     * Compares two sets of signatures. Returns:
4692     * <br />
4693     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4694     * <br />
4695     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4696     * <br />
4697     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4698     * <br />
4699     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4700     * <br />
4701     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4702     */
4703    static int compareSignatures(Signature[] s1, Signature[] s2) {
4704        if (s1 == null) {
4705            return s2 == null
4706                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4707                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4708        }
4709
4710        if (s2 == null) {
4711            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4712        }
4713
4714        if (s1.length != s2.length) {
4715            return PackageManager.SIGNATURE_NO_MATCH;
4716        }
4717
4718        // Since both signature sets are of size 1, we can compare without HashSets.
4719        if (s1.length == 1) {
4720            return s1[0].equals(s2[0]) ?
4721                    PackageManager.SIGNATURE_MATCH :
4722                    PackageManager.SIGNATURE_NO_MATCH;
4723        }
4724
4725        ArraySet<Signature> set1 = new ArraySet<Signature>();
4726        for (Signature sig : s1) {
4727            set1.add(sig);
4728        }
4729        ArraySet<Signature> set2 = new ArraySet<Signature>();
4730        for (Signature sig : s2) {
4731            set2.add(sig);
4732        }
4733        // Make sure s2 contains all signatures in s1.
4734        if (set1.equals(set2)) {
4735            return PackageManager.SIGNATURE_MATCH;
4736        }
4737        return PackageManager.SIGNATURE_NO_MATCH;
4738    }
4739
4740    /**
4741     * If the database version for this type of package (internal storage or
4742     * external storage) is less than the version where package signatures
4743     * were updated, return true.
4744     */
4745    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4746        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4747        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4748    }
4749
4750    /**
4751     * Used for backward compatibility to make sure any packages with
4752     * certificate chains get upgraded to the new style. {@code existingSigs}
4753     * will be in the old format (since they were stored on disk from before the
4754     * system upgrade) and {@code scannedSigs} will be in the newer format.
4755     */
4756    private int compareSignaturesCompat(PackageSignatures existingSigs,
4757            PackageParser.Package scannedPkg) {
4758        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4759            return PackageManager.SIGNATURE_NO_MATCH;
4760        }
4761
4762        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4763        for (Signature sig : existingSigs.mSignatures) {
4764            existingSet.add(sig);
4765        }
4766        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4767        for (Signature sig : scannedPkg.mSignatures) {
4768            try {
4769                Signature[] chainSignatures = sig.getChainSignatures();
4770                for (Signature chainSig : chainSignatures) {
4771                    scannedCompatSet.add(chainSig);
4772                }
4773            } catch (CertificateEncodingException e) {
4774                scannedCompatSet.add(sig);
4775            }
4776        }
4777        /*
4778         * Make sure the expanded scanned set contains all signatures in the
4779         * existing one.
4780         */
4781        if (scannedCompatSet.equals(existingSet)) {
4782            // Migrate the old signatures to the new scheme.
4783            existingSigs.assignSignatures(scannedPkg.mSignatures);
4784            // The new KeySets will be re-added later in the scanning process.
4785            synchronized (mPackages) {
4786                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4787            }
4788            return PackageManager.SIGNATURE_MATCH;
4789        }
4790        return PackageManager.SIGNATURE_NO_MATCH;
4791    }
4792
4793    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4794        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4795        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4796    }
4797
4798    private int compareSignaturesRecover(PackageSignatures existingSigs,
4799            PackageParser.Package scannedPkg) {
4800        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4801            return PackageManager.SIGNATURE_NO_MATCH;
4802        }
4803
4804        String msg = null;
4805        try {
4806            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4807                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4808                        + scannedPkg.packageName);
4809                return PackageManager.SIGNATURE_MATCH;
4810            }
4811        } catch (CertificateException e) {
4812            msg = e.getMessage();
4813        }
4814
4815        logCriticalInfo(Log.INFO,
4816                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4817        return PackageManager.SIGNATURE_NO_MATCH;
4818    }
4819
4820    @Override
4821    public List<String> getAllPackages() {
4822        synchronized (mPackages) {
4823            return new ArrayList<String>(mPackages.keySet());
4824        }
4825    }
4826
4827    @Override
4828    public String[] getPackagesForUid(int uid) {
4829        final int userId = UserHandle.getUserId(uid);
4830        uid = UserHandle.getAppId(uid);
4831        // reader
4832        synchronized (mPackages) {
4833            Object obj = mSettings.getUserIdLPr(uid);
4834            if (obj instanceof SharedUserSetting) {
4835                final SharedUserSetting sus = (SharedUserSetting) obj;
4836                final int N = sus.packages.size();
4837                String[] res = new String[N];
4838                final Iterator<PackageSetting> it = sus.packages.iterator();
4839                int i = 0;
4840                while (it.hasNext()) {
4841                    PackageSetting ps = it.next();
4842                    if (ps.getInstalled(userId)) {
4843                        res[i++] = ps.name;
4844                    } else {
4845                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4846                    }
4847                }
4848                return res;
4849            } else if (obj instanceof PackageSetting) {
4850                final PackageSetting ps = (PackageSetting) obj;
4851                return new String[] { ps.name };
4852            }
4853        }
4854        return null;
4855    }
4856
4857    @Override
4858    public String getNameForUid(int uid) {
4859        // reader
4860        synchronized (mPackages) {
4861            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4862            if (obj instanceof SharedUserSetting) {
4863                final SharedUserSetting sus = (SharedUserSetting) obj;
4864                return sus.name + ":" + sus.userId;
4865            } else if (obj instanceof PackageSetting) {
4866                final PackageSetting ps = (PackageSetting) obj;
4867                return ps.name;
4868            }
4869        }
4870        return null;
4871    }
4872
4873    @Override
4874    public int getUidForSharedUser(String sharedUserName) {
4875        if(sharedUserName == null) {
4876            return -1;
4877        }
4878        // reader
4879        synchronized (mPackages) {
4880            SharedUserSetting suid;
4881            try {
4882                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4883                if (suid != null) {
4884                    return suid.userId;
4885                }
4886            } catch (PackageManagerException ignore) {
4887                // can't happen, but, still need to catch it
4888            }
4889            return -1;
4890        }
4891    }
4892
4893    @Override
4894    public int getFlagsForUid(int uid) {
4895        synchronized (mPackages) {
4896            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4897            if (obj instanceof SharedUserSetting) {
4898                final SharedUserSetting sus = (SharedUserSetting) obj;
4899                return sus.pkgFlags;
4900            } else if (obj instanceof PackageSetting) {
4901                final PackageSetting ps = (PackageSetting) obj;
4902                return ps.pkgFlags;
4903            }
4904        }
4905        return 0;
4906    }
4907
4908    @Override
4909    public int getPrivateFlagsForUid(int uid) {
4910        synchronized (mPackages) {
4911            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4912            if (obj instanceof SharedUserSetting) {
4913                final SharedUserSetting sus = (SharedUserSetting) obj;
4914                return sus.pkgPrivateFlags;
4915            } else if (obj instanceof PackageSetting) {
4916                final PackageSetting ps = (PackageSetting) obj;
4917                return ps.pkgPrivateFlags;
4918            }
4919        }
4920        return 0;
4921    }
4922
4923    @Override
4924    public boolean isUidPrivileged(int uid) {
4925        uid = UserHandle.getAppId(uid);
4926        // reader
4927        synchronized (mPackages) {
4928            Object obj = mSettings.getUserIdLPr(uid);
4929            if (obj instanceof SharedUserSetting) {
4930                final SharedUserSetting sus = (SharedUserSetting) obj;
4931                final Iterator<PackageSetting> it = sus.packages.iterator();
4932                while (it.hasNext()) {
4933                    if (it.next().isPrivileged()) {
4934                        return true;
4935                    }
4936                }
4937            } else if (obj instanceof PackageSetting) {
4938                final PackageSetting ps = (PackageSetting) obj;
4939                return ps.isPrivileged();
4940            }
4941        }
4942        return false;
4943    }
4944
4945    @Override
4946    public String[] getAppOpPermissionPackages(String permissionName) {
4947        synchronized (mPackages) {
4948            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4949            if (pkgs == null) {
4950                return null;
4951            }
4952            return pkgs.toArray(new String[pkgs.size()]);
4953        }
4954    }
4955
4956    @Override
4957    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4958            int flags, int userId) {
4959        try {
4960            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4961
4962            if (!sUserManager.exists(userId)) return null;
4963            flags = updateFlagsForResolve(flags, userId, intent);
4964            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4965                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4966
4967            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4968            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4969                    flags, userId);
4970            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4971
4972            final ResolveInfo bestChoice =
4973                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4974            return bestChoice;
4975        } finally {
4976            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4977        }
4978    }
4979
4980    @Override
4981    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4982            IntentFilter filter, int match, ComponentName activity) {
4983        final int userId = UserHandle.getCallingUserId();
4984        if (DEBUG_PREFERRED) {
4985            Log.v(TAG, "setLastChosenActivity intent=" + intent
4986                + " resolvedType=" + resolvedType
4987                + " flags=" + flags
4988                + " filter=" + filter
4989                + " match=" + match
4990                + " activity=" + activity);
4991            filter.dump(new PrintStreamPrinter(System.out), "    ");
4992        }
4993        intent.setComponent(null);
4994        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4995                userId);
4996        // Find any earlier preferred or last chosen entries and nuke them
4997        findPreferredActivity(intent, resolvedType,
4998                flags, query, 0, false, true, false, userId);
4999        // Add the new activity as the last chosen for this filter
5000        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5001                "Setting last chosen");
5002    }
5003
5004    @Override
5005    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5006        final int userId = UserHandle.getCallingUserId();
5007        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5008        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5009                userId);
5010        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5011                false, false, false, userId);
5012    }
5013
5014    private boolean isEphemeralDisabled() {
5015        // ephemeral apps have been disabled across the board
5016        if (DISABLE_EPHEMERAL_APPS) {
5017            return true;
5018        }
5019        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5020        if (!mSystemReady) {
5021            return true;
5022        }
5023        // we can't get a content resolver until the system is ready; these checks must happen last
5024        final ContentResolver resolver = mContext.getContentResolver();
5025        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5026            return true;
5027        }
5028        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5029    }
5030
5031    private boolean isEphemeralAllowed(
5032            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5033            boolean skipPackageCheck) {
5034        // Short circuit and return early if possible.
5035        if (isEphemeralDisabled()) {
5036            return false;
5037        }
5038        final int callingUser = UserHandle.getCallingUserId();
5039        if (callingUser != UserHandle.USER_SYSTEM) {
5040            return false;
5041        }
5042        if (mEphemeralResolverConnection == null) {
5043            return false;
5044        }
5045        if (mEphemeralInstallerComponent == null) {
5046            return false;
5047        }
5048        if (intent.getComponent() != null) {
5049            return false;
5050        }
5051        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5052            return false;
5053        }
5054        if (!skipPackageCheck && intent.getPackage() != null) {
5055            return false;
5056        }
5057        final boolean isWebUri = hasWebURI(intent);
5058        if (!isWebUri || intent.getData().getHost() == null) {
5059            return false;
5060        }
5061        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5062        synchronized (mPackages) {
5063            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5064            for (int n = 0; n < count; n++) {
5065                ResolveInfo info = resolvedActivities.get(n);
5066                String packageName = info.activityInfo.packageName;
5067                PackageSetting ps = mSettings.mPackages.get(packageName);
5068                if (ps != null) {
5069                    // Try to get the status from User settings first
5070                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5071                    int status = (int) (packedStatus >> 32);
5072                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5073                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5074                        if (DEBUG_EPHEMERAL) {
5075                            Slog.v(TAG, "DENY ephemeral apps;"
5076                                + " pkg: " + packageName + ", status: " + status);
5077                        }
5078                        return false;
5079                    }
5080                }
5081            }
5082        }
5083        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5084        return true;
5085    }
5086
5087    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5088            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5089            int userId) {
5090        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5091                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5092                        callingPackage, userId));
5093        mHandler.sendMessage(msg);
5094    }
5095
5096    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5097            int flags, List<ResolveInfo> query, int userId) {
5098        if (query != null) {
5099            final int N = query.size();
5100            if (N == 1) {
5101                return query.get(0);
5102            } else if (N > 1) {
5103                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5104                // If there is more than one activity with the same priority,
5105                // then let the user decide between them.
5106                ResolveInfo r0 = query.get(0);
5107                ResolveInfo r1 = query.get(1);
5108                if (DEBUG_INTENT_MATCHING || debug) {
5109                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5110                            + r1.activityInfo.name + "=" + r1.priority);
5111                }
5112                // If the first activity has a higher priority, or a different
5113                // default, then it is always desirable to pick it.
5114                if (r0.priority != r1.priority
5115                        || r0.preferredOrder != r1.preferredOrder
5116                        || r0.isDefault != r1.isDefault) {
5117                    return query.get(0);
5118                }
5119                // If we have saved a preference for a preferred activity for
5120                // this Intent, use that.
5121                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5122                        flags, query, r0.priority, true, false, debug, userId);
5123                if (ri != null) {
5124                    return ri;
5125                }
5126                ri = new ResolveInfo(mResolveInfo);
5127                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5128                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5129                // If all of the options come from the same package, show the application's
5130                // label and icon instead of the generic resolver's.
5131                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5132                // and then throw away the ResolveInfo itself, meaning that the caller loses
5133                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5134                // a fallback for this case; we only set the target package's resources on
5135                // the ResolveInfo, not the ActivityInfo.
5136                final String intentPackage = intent.getPackage();
5137                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5138                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5139                    ri.resolvePackageName = intentPackage;
5140                    if (userNeedsBadging(userId)) {
5141                        ri.noResourceId = true;
5142                    } else {
5143                        ri.icon = appi.icon;
5144                    }
5145                    ri.iconResourceId = appi.icon;
5146                    ri.labelRes = appi.labelRes;
5147                }
5148                ri.activityInfo.applicationInfo = new ApplicationInfo(
5149                        ri.activityInfo.applicationInfo);
5150                if (userId != 0) {
5151                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5152                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5153                }
5154                // Make sure that the resolver is displayable in car mode
5155                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5156                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5157                return ri;
5158            }
5159        }
5160        return null;
5161    }
5162
5163    /**
5164     * Return true if the given list is not empty and all of its contents have
5165     * an activityInfo with the given package name.
5166     */
5167    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5168        if (ArrayUtils.isEmpty(list)) {
5169            return false;
5170        }
5171        for (int i = 0, N = list.size(); i < N; i++) {
5172            final ResolveInfo ri = list.get(i);
5173            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5174            if (ai == null || !packageName.equals(ai.packageName)) {
5175                return false;
5176            }
5177        }
5178        return true;
5179    }
5180
5181    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5182            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5183        final int N = query.size();
5184        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5185                .get(userId);
5186        // Get the list of persistent preferred activities that handle the intent
5187        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5188        List<PersistentPreferredActivity> pprefs = ppir != null
5189                ? ppir.queryIntent(intent, resolvedType,
5190                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5191                : null;
5192        if (pprefs != null && pprefs.size() > 0) {
5193            final int M = pprefs.size();
5194            for (int i=0; i<M; i++) {
5195                final PersistentPreferredActivity ppa = pprefs.get(i);
5196                if (DEBUG_PREFERRED || debug) {
5197                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5198                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5199                            + "\n  component=" + ppa.mComponent);
5200                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5201                }
5202                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5203                        flags | MATCH_DISABLED_COMPONENTS, userId);
5204                if (DEBUG_PREFERRED || debug) {
5205                    Slog.v(TAG, "Found persistent preferred activity:");
5206                    if (ai != null) {
5207                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5208                    } else {
5209                        Slog.v(TAG, "  null");
5210                    }
5211                }
5212                if (ai == null) {
5213                    // This previously registered persistent preferred activity
5214                    // component is no longer known. Ignore it and do NOT remove it.
5215                    continue;
5216                }
5217                for (int j=0; j<N; j++) {
5218                    final ResolveInfo ri = query.get(j);
5219                    if (!ri.activityInfo.applicationInfo.packageName
5220                            .equals(ai.applicationInfo.packageName)) {
5221                        continue;
5222                    }
5223                    if (!ri.activityInfo.name.equals(ai.name)) {
5224                        continue;
5225                    }
5226                    //  Found a persistent preference that can handle the intent.
5227                    if (DEBUG_PREFERRED || debug) {
5228                        Slog.v(TAG, "Returning persistent preferred activity: " +
5229                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5230                    }
5231                    return ri;
5232                }
5233            }
5234        }
5235        return null;
5236    }
5237
5238    // TODO: handle preferred activities missing while user has amnesia
5239    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5240            List<ResolveInfo> query, int priority, boolean always,
5241            boolean removeMatches, boolean debug, int userId) {
5242        if (!sUserManager.exists(userId)) return null;
5243        flags = updateFlagsForResolve(flags, userId, intent);
5244        // writer
5245        synchronized (mPackages) {
5246            if (intent.getSelector() != null) {
5247                intent = intent.getSelector();
5248            }
5249            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5250
5251            // Try to find a matching persistent preferred activity.
5252            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5253                    debug, userId);
5254
5255            // If a persistent preferred activity matched, use it.
5256            if (pri != null) {
5257                return pri;
5258            }
5259
5260            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5261            // Get the list of preferred activities that handle the intent
5262            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5263            List<PreferredActivity> prefs = pir != null
5264                    ? pir.queryIntent(intent, resolvedType,
5265                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5266                    : null;
5267            if (prefs != null && prefs.size() > 0) {
5268                boolean changed = false;
5269                try {
5270                    // First figure out how good the original match set is.
5271                    // We will only allow preferred activities that came
5272                    // from the same match quality.
5273                    int match = 0;
5274
5275                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5276
5277                    final int N = query.size();
5278                    for (int j=0; j<N; j++) {
5279                        final ResolveInfo ri = query.get(j);
5280                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5281                                + ": 0x" + Integer.toHexString(match));
5282                        if (ri.match > match) {
5283                            match = ri.match;
5284                        }
5285                    }
5286
5287                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5288                            + Integer.toHexString(match));
5289
5290                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5291                    final int M = prefs.size();
5292                    for (int i=0; i<M; i++) {
5293                        final PreferredActivity pa = prefs.get(i);
5294                        if (DEBUG_PREFERRED || debug) {
5295                            Slog.v(TAG, "Checking PreferredActivity ds="
5296                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5297                                    + "\n  component=" + pa.mPref.mComponent);
5298                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5299                        }
5300                        if (pa.mPref.mMatch != match) {
5301                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5302                                    + Integer.toHexString(pa.mPref.mMatch));
5303                            continue;
5304                        }
5305                        // If it's not an "always" type preferred activity and that's what we're
5306                        // looking for, skip it.
5307                        if (always && !pa.mPref.mAlways) {
5308                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5309                            continue;
5310                        }
5311                        final ActivityInfo ai = getActivityInfo(
5312                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5313                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5314                                userId);
5315                        if (DEBUG_PREFERRED || debug) {
5316                            Slog.v(TAG, "Found preferred activity:");
5317                            if (ai != null) {
5318                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5319                            } else {
5320                                Slog.v(TAG, "  null");
5321                            }
5322                        }
5323                        if (ai == null) {
5324                            // This previously registered preferred activity
5325                            // component is no longer known.  Most likely an update
5326                            // to the app was installed and in the new version this
5327                            // component no longer exists.  Clean it up by removing
5328                            // it from the preferred activities list, and skip it.
5329                            Slog.w(TAG, "Removing dangling preferred activity: "
5330                                    + pa.mPref.mComponent);
5331                            pir.removeFilter(pa);
5332                            changed = true;
5333                            continue;
5334                        }
5335                        for (int j=0; j<N; j++) {
5336                            final ResolveInfo ri = query.get(j);
5337                            if (!ri.activityInfo.applicationInfo.packageName
5338                                    .equals(ai.applicationInfo.packageName)) {
5339                                continue;
5340                            }
5341                            if (!ri.activityInfo.name.equals(ai.name)) {
5342                                continue;
5343                            }
5344
5345                            if (removeMatches) {
5346                                pir.removeFilter(pa);
5347                                changed = true;
5348                                if (DEBUG_PREFERRED) {
5349                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5350                                }
5351                                break;
5352                            }
5353
5354                            // Okay we found a previously set preferred or last chosen app.
5355                            // If the result set is different from when this
5356                            // was created, we need to clear it and re-ask the
5357                            // user their preference, if we're looking for an "always" type entry.
5358                            if (always && !pa.mPref.sameSet(query)) {
5359                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5360                                        + intent + " type " + resolvedType);
5361                                if (DEBUG_PREFERRED) {
5362                                    Slog.v(TAG, "Removing preferred activity since set changed "
5363                                            + pa.mPref.mComponent);
5364                                }
5365                                pir.removeFilter(pa);
5366                                // Re-add the filter as a "last chosen" entry (!always)
5367                                PreferredActivity lastChosen = new PreferredActivity(
5368                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5369                                pir.addFilter(lastChosen);
5370                                changed = true;
5371                                return null;
5372                            }
5373
5374                            // Yay! Either the set matched or we're looking for the last chosen
5375                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5376                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5377                            return ri;
5378                        }
5379                    }
5380                } finally {
5381                    if (changed) {
5382                        if (DEBUG_PREFERRED) {
5383                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5384                        }
5385                        scheduleWritePackageRestrictionsLocked(userId);
5386                    }
5387                }
5388            }
5389        }
5390        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5391        return null;
5392    }
5393
5394    /*
5395     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5396     */
5397    @Override
5398    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5399            int targetUserId) {
5400        mContext.enforceCallingOrSelfPermission(
5401                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5402        List<CrossProfileIntentFilter> matches =
5403                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5404        if (matches != null) {
5405            int size = matches.size();
5406            for (int i = 0; i < size; i++) {
5407                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5408            }
5409        }
5410        if (hasWebURI(intent)) {
5411            // cross-profile app linking works only towards the parent.
5412            final UserInfo parent = getProfileParent(sourceUserId);
5413            synchronized(mPackages) {
5414                int flags = updateFlagsForResolve(0, parent.id, intent);
5415                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5416                        intent, resolvedType, flags, sourceUserId, parent.id);
5417                return xpDomainInfo != null;
5418            }
5419        }
5420        return false;
5421    }
5422
5423    private UserInfo getProfileParent(int userId) {
5424        final long identity = Binder.clearCallingIdentity();
5425        try {
5426            return sUserManager.getProfileParent(userId);
5427        } finally {
5428            Binder.restoreCallingIdentity(identity);
5429        }
5430    }
5431
5432    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5433            String resolvedType, int userId) {
5434        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5435        if (resolver != null) {
5436            return resolver.queryIntent(intent, resolvedType, false, userId);
5437        }
5438        return null;
5439    }
5440
5441    @Override
5442    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5443            String resolvedType, int flags, int userId) {
5444        try {
5445            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5446
5447            return new ParceledListSlice<>(
5448                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5449        } finally {
5450            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5451        }
5452    }
5453
5454    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5455            String resolvedType, int flags, int userId) {
5456        if (!sUserManager.exists(userId)) return Collections.emptyList();
5457        flags = updateFlagsForResolve(flags, userId, intent);
5458        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5459                false /* requireFullPermission */, false /* checkShell */,
5460                "query intent activities");
5461        ComponentName comp = intent.getComponent();
5462        if (comp == null) {
5463            if (intent.getSelector() != null) {
5464                intent = intent.getSelector();
5465                comp = intent.getComponent();
5466            }
5467        }
5468
5469        if (comp != null) {
5470            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5471            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5472            if (ai != null) {
5473                final ResolveInfo ri = new ResolveInfo();
5474                ri.activityInfo = ai;
5475                list.add(ri);
5476            }
5477            return list;
5478        }
5479
5480        // reader
5481        boolean sortResult = false;
5482        boolean addEphemeral = false;
5483        boolean matchEphemeralPackage = false;
5484        List<ResolveInfo> result;
5485        final String pkgName = intent.getPackage();
5486        synchronized (mPackages) {
5487            if (pkgName == null) {
5488                List<CrossProfileIntentFilter> matchingFilters =
5489                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5490                // Check for results that need to skip the current profile.
5491                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5492                        resolvedType, flags, userId);
5493                if (xpResolveInfo != null) {
5494                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5495                    xpResult.add(xpResolveInfo);
5496                    return filterIfNotSystemUser(xpResult, userId);
5497                }
5498
5499                // Check for results in the current profile.
5500                result = filterIfNotSystemUser(mActivities.queryIntent(
5501                        intent, resolvedType, flags, userId), userId);
5502                addEphemeral =
5503                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5504
5505                // Check for cross profile results.
5506                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5507                xpResolveInfo = queryCrossProfileIntents(
5508                        matchingFilters, intent, resolvedType, flags, userId,
5509                        hasNonNegativePriorityResult);
5510                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5511                    boolean isVisibleToUser = filterIfNotSystemUser(
5512                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5513                    if (isVisibleToUser) {
5514                        result.add(xpResolveInfo);
5515                        sortResult = true;
5516                    }
5517                }
5518                if (hasWebURI(intent)) {
5519                    CrossProfileDomainInfo xpDomainInfo = null;
5520                    final UserInfo parent = getProfileParent(userId);
5521                    if (parent != null) {
5522                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5523                                flags, userId, parent.id);
5524                    }
5525                    if (xpDomainInfo != null) {
5526                        if (xpResolveInfo != null) {
5527                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5528                            // in the result.
5529                            result.remove(xpResolveInfo);
5530                        }
5531                        if (result.size() == 0 && !addEphemeral) {
5532                            // No result in current profile, but found candidate in parent user.
5533                            // And we are not going to add emphemeral app, so we can return the
5534                            // result straight away.
5535                            result.add(xpDomainInfo.resolveInfo);
5536                            return result;
5537                        }
5538                    } else if (result.size() <= 1 && !addEphemeral) {
5539                        // No result in parent user and <= 1 result in current profile, and we
5540                        // are not going to add emphemeral app, so we can return the result without
5541                        // further processing.
5542                        return result;
5543                    }
5544                    // We have more than one candidate (combining results from current and parent
5545                    // profile), so we need filtering and sorting.
5546                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5547                            intent, flags, result, xpDomainInfo, userId);
5548                    sortResult = true;
5549                }
5550            } else {
5551                final PackageParser.Package pkg = mPackages.get(pkgName);
5552                if (pkg != null) {
5553                    result = filterIfNotSystemUser(
5554                            mActivities.queryIntentForPackage(
5555                                    intent, resolvedType, flags, pkg.activities, userId),
5556                            userId);
5557                } else {
5558                    // the caller wants to resolve for a particular package; however, there
5559                    // were no installed results, so, try to find an ephemeral result
5560                    addEphemeral = isEphemeralAllowed(
5561                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5562                    matchEphemeralPackage = true;
5563                    result = new ArrayList<ResolveInfo>();
5564                }
5565            }
5566        }
5567        if (addEphemeral) {
5568            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5569            final EphemeralRequest requestObject = new EphemeralRequest(
5570                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5571                    null /*launchIntent*/, null /*callingPackage*/, userId);
5572            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5573                    mContext, mEphemeralResolverConnection, requestObject);
5574            if (intentInfo != null) {
5575                if (DEBUG_EPHEMERAL) {
5576                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5577                }
5578                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5579                ephemeralInstaller.ephemeralResponse = intentInfo;
5580                // make sure this resolver is the default
5581                ephemeralInstaller.isDefault = true;
5582                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5583                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5584                // add a non-generic filter
5585                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5586                ephemeralInstaller.filter.addDataPath(
5587                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5588                result.add(ephemeralInstaller);
5589            }
5590            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5591        }
5592        if (sortResult) {
5593            Collections.sort(result, mResolvePrioritySorter);
5594        }
5595        return result;
5596    }
5597
5598    private static class CrossProfileDomainInfo {
5599        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5600        ResolveInfo resolveInfo;
5601        /* Best domain verification status of the activities found in the other profile */
5602        int bestDomainVerificationStatus;
5603    }
5604
5605    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5606            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5607        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5608                sourceUserId)) {
5609            return null;
5610        }
5611        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5612                resolvedType, flags, parentUserId);
5613
5614        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5615            return null;
5616        }
5617        CrossProfileDomainInfo result = null;
5618        int size = resultTargetUser.size();
5619        for (int i = 0; i < size; i++) {
5620            ResolveInfo riTargetUser = resultTargetUser.get(i);
5621            // Intent filter verification is only for filters that specify a host. So don't return
5622            // those that handle all web uris.
5623            if (riTargetUser.handleAllWebDataURI) {
5624                continue;
5625            }
5626            String packageName = riTargetUser.activityInfo.packageName;
5627            PackageSetting ps = mSettings.mPackages.get(packageName);
5628            if (ps == null) {
5629                continue;
5630            }
5631            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5632            int status = (int)(verificationState >> 32);
5633            if (result == null) {
5634                result = new CrossProfileDomainInfo();
5635                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5636                        sourceUserId, parentUserId);
5637                result.bestDomainVerificationStatus = status;
5638            } else {
5639                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5640                        result.bestDomainVerificationStatus);
5641            }
5642        }
5643        // Don't consider matches with status NEVER across profiles.
5644        if (result != null && result.bestDomainVerificationStatus
5645                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5646            return null;
5647        }
5648        return result;
5649    }
5650
5651    /**
5652     * Verification statuses are ordered from the worse to the best, except for
5653     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5654     */
5655    private int bestDomainVerificationStatus(int status1, int status2) {
5656        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5657            return status2;
5658        }
5659        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5660            return status1;
5661        }
5662        return (int) MathUtils.max(status1, status2);
5663    }
5664
5665    private boolean isUserEnabled(int userId) {
5666        long callingId = Binder.clearCallingIdentity();
5667        try {
5668            UserInfo userInfo = sUserManager.getUserInfo(userId);
5669            return userInfo != null && userInfo.isEnabled();
5670        } finally {
5671            Binder.restoreCallingIdentity(callingId);
5672        }
5673    }
5674
5675    /**
5676     * Filter out activities with systemUserOnly flag set, when current user is not System.
5677     *
5678     * @return filtered list
5679     */
5680    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5681        if (userId == UserHandle.USER_SYSTEM) {
5682            return resolveInfos;
5683        }
5684        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5685            ResolveInfo info = resolveInfos.get(i);
5686            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5687                resolveInfos.remove(i);
5688            }
5689        }
5690        return resolveInfos;
5691    }
5692
5693    /**
5694     * @param resolveInfos list of resolve infos in descending priority order
5695     * @return if the list contains a resolve info with non-negative priority
5696     */
5697    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5698        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5699    }
5700
5701    private static boolean hasWebURI(Intent intent) {
5702        if (intent.getData() == null) {
5703            return false;
5704        }
5705        final String scheme = intent.getScheme();
5706        if (TextUtils.isEmpty(scheme)) {
5707            return false;
5708        }
5709        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5710    }
5711
5712    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5713            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5714            int userId) {
5715        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5716
5717        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5718            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5719                    candidates.size());
5720        }
5721
5722        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5723        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5724        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5725        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5726        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5727        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5728
5729        synchronized (mPackages) {
5730            final int count = candidates.size();
5731            // First, try to use linked apps. Partition the candidates into four lists:
5732            // one for the final results, one for the "do not use ever", one for "undefined status"
5733            // and finally one for "browser app type".
5734            for (int n=0; n<count; n++) {
5735                ResolveInfo info = candidates.get(n);
5736                String packageName = info.activityInfo.packageName;
5737                PackageSetting ps = mSettings.mPackages.get(packageName);
5738                if (ps != null) {
5739                    // Add to the special match all list (Browser use case)
5740                    if (info.handleAllWebDataURI) {
5741                        matchAllList.add(info);
5742                        continue;
5743                    }
5744                    // Try to get the status from User settings first
5745                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5746                    int status = (int)(packedStatus >> 32);
5747                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5748                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5749                        if (DEBUG_DOMAIN_VERIFICATION) {
5750                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5751                                    + " : linkgen=" + linkGeneration);
5752                        }
5753                        // Use link-enabled generation as preferredOrder, i.e.
5754                        // prefer newly-enabled over earlier-enabled.
5755                        info.preferredOrder = linkGeneration;
5756                        alwaysList.add(info);
5757                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5758                        if (DEBUG_DOMAIN_VERIFICATION) {
5759                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5760                        }
5761                        neverList.add(info);
5762                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5763                        if (DEBUG_DOMAIN_VERIFICATION) {
5764                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5765                        }
5766                        alwaysAskList.add(info);
5767                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5768                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5769                        if (DEBUG_DOMAIN_VERIFICATION) {
5770                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5771                        }
5772                        undefinedList.add(info);
5773                    }
5774                }
5775            }
5776
5777            // We'll want to include browser possibilities in a few cases
5778            boolean includeBrowser = false;
5779
5780            // First try to add the "always" resolution(s) for the current user, if any
5781            if (alwaysList.size() > 0) {
5782                result.addAll(alwaysList);
5783            } else {
5784                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5785                result.addAll(undefinedList);
5786                // Maybe add one for the other profile.
5787                if (xpDomainInfo != null && (
5788                        xpDomainInfo.bestDomainVerificationStatus
5789                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5790                    result.add(xpDomainInfo.resolveInfo);
5791                }
5792                includeBrowser = true;
5793            }
5794
5795            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5796            // If there were 'always' entries their preferred order has been set, so we also
5797            // back that off to make the alternatives equivalent
5798            if (alwaysAskList.size() > 0) {
5799                for (ResolveInfo i : result) {
5800                    i.preferredOrder = 0;
5801                }
5802                result.addAll(alwaysAskList);
5803                includeBrowser = true;
5804            }
5805
5806            if (includeBrowser) {
5807                // Also add browsers (all of them or only the default one)
5808                if (DEBUG_DOMAIN_VERIFICATION) {
5809                    Slog.v(TAG, "   ...including browsers in candidate set");
5810                }
5811                if ((matchFlags & MATCH_ALL) != 0) {
5812                    result.addAll(matchAllList);
5813                } else {
5814                    // Browser/generic handling case.  If there's a default browser, go straight
5815                    // to that (but only if there is no other higher-priority match).
5816                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5817                    int maxMatchPrio = 0;
5818                    ResolveInfo defaultBrowserMatch = null;
5819                    final int numCandidates = matchAllList.size();
5820                    for (int n = 0; n < numCandidates; n++) {
5821                        ResolveInfo info = matchAllList.get(n);
5822                        // track the highest overall match priority...
5823                        if (info.priority > maxMatchPrio) {
5824                            maxMatchPrio = info.priority;
5825                        }
5826                        // ...and the highest-priority default browser match
5827                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5828                            if (defaultBrowserMatch == null
5829                                    || (defaultBrowserMatch.priority < info.priority)) {
5830                                if (debug) {
5831                                    Slog.v(TAG, "Considering default browser match " + info);
5832                                }
5833                                defaultBrowserMatch = info;
5834                            }
5835                        }
5836                    }
5837                    if (defaultBrowserMatch != null
5838                            && defaultBrowserMatch.priority >= maxMatchPrio
5839                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5840                    {
5841                        if (debug) {
5842                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5843                        }
5844                        result.add(defaultBrowserMatch);
5845                    } else {
5846                        result.addAll(matchAllList);
5847                    }
5848                }
5849
5850                // If there is nothing selected, add all candidates and remove the ones that the user
5851                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5852                if (result.size() == 0) {
5853                    result.addAll(candidates);
5854                    result.removeAll(neverList);
5855                }
5856            }
5857        }
5858        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5859            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5860                    result.size());
5861            for (ResolveInfo info : result) {
5862                Slog.v(TAG, "  + " + info.activityInfo);
5863            }
5864        }
5865        return result;
5866    }
5867
5868    // Returns a packed value as a long:
5869    //
5870    // high 'int'-sized word: link status: undefined/ask/never/always.
5871    // low 'int'-sized word: relative priority among 'always' results.
5872    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5873        long result = ps.getDomainVerificationStatusForUser(userId);
5874        // if none available, get the master status
5875        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5876            if (ps.getIntentFilterVerificationInfo() != null) {
5877                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5878            }
5879        }
5880        return result;
5881    }
5882
5883    private ResolveInfo querySkipCurrentProfileIntents(
5884            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5885            int flags, int sourceUserId) {
5886        if (matchingFilters != null) {
5887            int size = matchingFilters.size();
5888            for (int i = 0; i < size; i ++) {
5889                CrossProfileIntentFilter filter = matchingFilters.get(i);
5890                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5891                    // Checking if there are activities in the target user that can handle the
5892                    // intent.
5893                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5894                            resolvedType, flags, sourceUserId);
5895                    if (resolveInfo != null) {
5896                        return resolveInfo;
5897                    }
5898                }
5899            }
5900        }
5901        return null;
5902    }
5903
5904    // Return matching ResolveInfo in target user if any.
5905    private ResolveInfo queryCrossProfileIntents(
5906            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5907            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5908        if (matchingFilters != null) {
5909            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5910            // match the same intent. For performance reasons, it is better not to
5911            // run queryIntent twice for the same userId
5912            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5913            int size = matchingFilters.size();
5914            for (int i = 0; i < size; i++) {
5915                CrossProfileIntentFilter filter = matchingFilters.get(i);
5916                int targetUserId = filter.getTargetUserId();
5917                boolean skipCurrentProfile =
5918                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5919                boolean skipCurrentProfileIfNoMatchFound =
5920                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5921                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5922                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5923                    // Checking if there are activities in the target user that can handle the
5924                    // intent.
5925                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5926                            resolvedType, flags, sourceUserId);
5927                    if (resolveInfo != null) return resolveInfo;
5928                    alreadyTriedUserIds.put(targetUserId, true);
5929                }
5930            }
5931        }
5932        return null;
5933    }
5934
5935    /**
5936     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5937     * will forward the intent to the filter's target user.
5938     * Otherwise, returns null.
5939     */
5940    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5941            String resolvedType, int flags, int sourceUserId) {
5942        int targetUserId = filter.getTargetUserId();
5943        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5944                resolvedType, flags, targetUserId);
5945        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5946            // If all the matches in the target profile are suspended, return null.
5947            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5948                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5949                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5950                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5951                            targetUserId);
5952                }
5953            }
5954        }
5955        return null;
5956    }
5957
5958    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5959            int sourceUserId, int targetUserId) {
5960        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5961        long ident = Binder.clearCallingIdentity();
5962        boolean targetIsProfile;
5963        try {
5964            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5965        } finally {
5966            Binder.restoreCallingIdentity(ident);
5967        }
5968        String className;
5969        if (targetIsProfile) {
5970            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5971        } else {
5972            className = FORWARD_INTENT_TO_PARENT;
5973        }
5974        ComponentName forwardingActivityComponentName = new ComponentName(
5975                mAndroidApplication.packageName, className);
5976        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5977                sourceUserId);
5978        if (!targetIsProfile) {
5979            forwardingActivityInfo.showUserIcon = targetUserId;
5980            forwardingResolveInfo.noResourceId = true;
5981        }
5982        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5983        forwardingResolveInfo.priority = 0;
5984        forwardingResolveInfo.preferredOrder = 0;
5985        forwardingResolveInfo.match = 0;
5986        forwardingResolveInfo.isDefault = true;
5987        forwardingResolveInfo.filter = filter;
5988        forwardingResolveInfo.targetUserId = targetUserId;
5989        return forwardingResolveInfo;
5990    }
5991
5992    @Override
5993    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5994            Intent[] specifics, String[] specificTypes, Intent intent,
5995            String resolvedType, int flags, int userId) {
5996        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5997                specificTypes, intent, resolvedType, flags, userId));
5998    }
5999
6000    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6001            Intent[] specifics, String[] specificTypes, Intent intent,
6002            String resolvedType, int flags, int userId) {
6003        if (!sUserManager.exists(userId)) return Collections.emptyList();
6004        flags = updateFlagsForResolve(flags, userId, intent);
6005        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6006                false /* requireFullPermission */, false /* checkShell */,
6007                "query intent activity options");
6008        final String resultsAction = intent.getAction();
6009
6010        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6011                | PackageManager.GET_RESOLVED_FILTER, userId);
6012
6013        if (DEBUG_INTENT_MATCHING) {
6014            Log.v(TAG, "Query " + intent + ": " + results);
6015        }
6016
6017        int specificsPos = 0;
6018        int N;
6019
6020        // todo: note that the algorithm used here is O(N^2).  This
6021        // isn't a problem in our current environment, but if we start running
6022        // into situations where we have more than 5 or 10 matches then this
6023        // should probably be changed to something smarter...
6024
6025        // First we go through and resolve each of the specific items
6026        // that were supplied, taking care of removing any corresponding
6027        // duplicate items in the generic resolve list.
6028        if (specifics != null) {
6029            for (int i=0; i<specifics.length; i++) {
6030                final Intent sintent = specifics[i];
6031                if (sintent == null) {
6032                    continue;
6033                }
6034
6035                if (DEBUG_INTENT_MATCHING) {
6036                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6037                }
6038
6039                String action = sintent.getAction();
6040                if (resultsAction != null && resultsAction.equals(action)) {
6041                    // If this action was explicitly requested, then don't
6042                    // remove things that have it.
6043                    action = null;
6044                }
6045
6046                ResolveInfo ri = null;
6047                ActivityInfo ai = null;
6048
6049                ComponentName comp = sintent.getComponent();
6050                if (comp == null) {
6051                    ri = resolveIntent(
6052                        sintent,
6053                        specificTypes != null ? specificTypes[i] : null,
6054                            flags, userId);
6055                    if (ri == null) {
6056                        continue;
6057                    }
6058                    if (ri == mResolveInfo) {
6059                        // ACK!  Must do something better with this.
6060                    }
6061                    ai = ri.activityInfo;
6062                    comp = new ComponentName(ai.applicationInfo.packageName,
6063                            ai.name);
6064                } else {
6065                    ai = getActivityInfo(comp, flags, userId);
6066                    if (ai == null) {
6067                        continue;
6068                    }
6069                }
6070
6071                // Look for any generic query activities that are duplicates
6072                // of this specific one, and remove them from the results.
6073                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6074                N = results.size();
6075                int j;
6076                for (j=specificsPos; j<N; j++) {
6077                    ResolveInfo sri = results.get(j);
6078                    if ((sri.activityInfo.name.equals(comp.getClassName())
6079                            && sri.activityInfo.applicationInfo.packageName.equals(
6080                                    comp.getPackageName()))
6081                        || (action != null && sri.filter.matchAction(action))) {
6082                        results.remove(j);
6083                        if (DEBUG_INTENT_MATCHING) Log.v(
6084                            TAG, "Removing duplicate item from " + j
6085                            + " due to specific " + specificsPos);
6086                        if (ri == null) {
6087                            ri = sri;
6088                        }
6089                        j--;
6090                        N--;
6091                    }
6092                }
6093
6094                // Add this specific item to its proper place.
6095                if (ri == null) {
6096                    ri = new ResolveInfo();
6097                    ri.activityInfo = ai;
6098                }
6099                results.add(specificsPos, ri);
6100                ri.specificIndex = i;
6101                specificsPos++;
6102            }
6103        }
6104
6105        // Now we go through the remaining generic results and remove any
6106        // duplicate actions that are found here.
6107        N = results.size();
6108        for (int i=specificsPos; i<N-1; i++) {
6109            final ResolveInfo rii = results.get(i);
6110            if (rii.filter == null) {
6111                continue;
6112            }
6113
6114            // Iterate over all of the actions of this result's intent
6115            // filter...  typically this should be just one.
6116            final Iterator<String> it = rii.filter.actionsIterator();
6117            if (it == null) {
6118                continue;
6119            }
6120            while (it.hasNext()) {
6121                final String action = it.next();
6122                if (resultsAction != null && resultsAction.equals(action)) {
6123                    // If this action was explicitly requested, then don't
6124                    // remove things that have it.
6125                    continue;
6126                }
6127                for (int j=i+1; j<N; j++) {
6128                    final ResolveInfo rij = results.get(j);
6129                    if (rij.filter != null && rij.filter.hasAction(action)) {
6130                        results.remove(j);
6131                        if (DEBUG_INTENT_MATCHING) Log.v(
6132                            TAG, "Removing duplicate item from " + j
6133                            + " due to action " + action + " at " + i);
6134                        j--;
6135                        N--;
6136                    }
6137                }
6138            }
6139
6140            // If the caller didn't request filter information, drop it now
6141            // so we don't have to marshall/unmarshall it.
6142            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6143                rii.filter = null;
6144            }
6145        }
6146
6147        // Filter out the caller activity if so requested.
6148        if (caller != null) {
6149            N = results.size();
6150            for (int i=0; i<N; i++) {
6151                ActivityInfo ainfo = results.get(i).activityInfo;
6152                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6153                        && caller.getClassName().equals(ainfo.name)) {
6154                    results.remove(i);
6155                    break;
6156                }
6157            }
6158        }
6159
6160        // If the caller didn't request filter information,
6161        // drop them now so we don't have to
6162        // marshall/unmarshall it.
6163        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6164            N = results.size();
6165            for (int i=0; i<N; i++) {
6166                results.get(i).filter = null;
6167            }
6168        }
6169
6170        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6171        return results;
6172    }
6173
6174    @Override
6175    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6176            String resolvedType, int flags, int userId) {
6177        return new ParceledListSlice<>(
6178                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6179    }
6180
6181    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6182            String resolvedType, int flags, int userId) {
6183        if (!sUserManager.exists(userId)) return Collections.emptyList();
6184        flags = updateFlagsForResolve(flags, userId, intent);
6185        ComponentName comp = intent.getComponent();
6186        if (comp == null) {
6187            if (intent.getSelector() != null) {
6188                intent = intent.getSelector();
6189                comp = intent.getComponent();
6190            }
6191        }
6192        if (comp != null) {
6193            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6194            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6195            if (ai != null) {
6196                ResolveInfo ri = new ResolveInfo();
6197                ri.activityInfo = ai;
6198                list.add(ri);
6199            }
6200            return list;
6201        }
6202
6203        // reader
6204        synchronized (mPackages) {
6205            String pkgName = intent.getPackage();
6206            if (pkgName == null) {
6207                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6208            }
6209            final PackageParser.Package pkg = mPackages.get(pkgName);
6210            if (pkg != null) {
6211                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6212                        userId);
6213            }
6214            return Collections.emptyList();
6215        }
6216    }
6217
6218    @Override
6219    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6220        if (!sUserManager.exists(userId)) return null;
6221        flags = updateFlagsForResolve(flags, userId, intent);
6222        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6223        if (query != null) {
6224            if (query.size() >= 1) {
6225                // If there is more than one service with the same priority,
6226                // just arbitrarily pick the first one.
6227                return query.get(0);
6228            }
6229        }
6230        return null;
6231    }
6232
6233    @Override
6234    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6235            String resolvedType, int flags, int userId) {
6236        return new ParceledListSlice<>(
6237                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6238    }
6239
6240    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6241            String resolvedType, int flags, int userId) {
6242        if (!sUserManager.exists(userId)) return Collections.emptyList();
6243        flags = updateFlagsForResolve(flags, userId, intent);
6244        ComponentName comp = intent.getComponent();
6245        if (comp == null) {
6246            if (intent.getSelector() != null) {
6247                intent = intent.getSelector();
6248                comp = intent.getComponent();
6249            }
6250        }
6251        if (comp != null) {
6252            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6253            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6254            if (si != null) {
6255                final ResolveInfo ri = new ResolveInfo();
6256                ri.serviceInfo = si;
6257                list.add(ri);
6258            }
6259            return list;
6260        }
6261
6262        // reader
6263        synchronized (mPackages) {
6264            String pkgName = intent.getPackage();
6265            if (pkgName == null) {
6266                return mServices.queryIntent(intent, resolvedType, flags, userId);
6267            }
6268            final PackageParser.Package pkg = mPackages.get(pkgName);
6269            if (pkg != null) {
6270                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6271                        userId);
6272            }
6273            return Collections.emptyList();
6274        }
6275    }
6276
6277    @Override
6278    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6279            String resolvedType, int flags, int userId) {
6280        return new ParceledListSlice<>(
6281                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6282    }
6283
6284    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6285            Intent intent, String resolvedType, int flags, int userId) {
6286        if (!sUserManager.exists(userId)) return Collections.emptyList();
6287        flags = updateFlagsForResolve(flags, userId, intent);
6288        ComponentName comp = intent.getComponent();
6289        if (comp == null) {
6290            if (intent.getSelector() != null) {
6291                intent = intent.getSelector();
6292                comp = intent.getComponent();
6293            }
6294        }
6295        if (comp != null) {
6296            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6297            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6298            if (pi != null) {
6299                final ResolveInfo ri = new ResolveInfo();
6300                ri.providerInfo = pi;
6301                list.add(ri);
6302            }
6303            return list;
6304        }
6305
6306        // reader
6307        synchronized (mPackages) {
6308            String pkgName = intent.getPackage();
6309            if (pkgName == null) {
6310                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6311            }
6312            final PackageParser.Package pkg = mPackages.get(pkgName);
6313            if (pkg != null) {
6314                return mProviders.queryIntentForPackage(
6315                        intent, resolvedType, flags, pkg.providers, userId);
6316            }
6317            return Collections.emptyList();
6318        }
6319    }
6320
6321    @Override
6322    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6323        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6324        flags = updateFlagsForPackage(flags, userId, null);
6325        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6327                true /* requireFullPermission */, false /* checkShell */,
6328                "get installed packages");
6329
6330        // writer
6331        synchronized (mPackages) {
6332            ArrayList<PackageInfo> list;
6333            if (listUninstalled) {
6334                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6335                for (PackageSetting ps : mSettings.mPackages.values()) {
6336                    final PackageInfo pi;
6337                    if (ps.pkg != null) {
6338                        pi = generatePackageInfo(ps, flags, userId);
6339                    } else {
6340                        pi = generatePackageInfo(ps, flags, userId);
6341                    }
6342                    if (pi != null) {
6343                        list.add(pi);
6344                    }
6345                }
6346            } else {
6347                list = new ArrayList<PackageInfo>(mPackages.size());
6348                for (PackageParser.Package p : mPackages.values()) {
6349                    final PackageInfo pi =
6350                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6351                    if (pi != null) {
6352                        list.add(pi);
6353                    }
6354                }
6355            }
6356
6357            return new ParceledListSlice<PackageInfo>(list);
6358        }
6359    }
6360
6361    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6362            String[] permissions, boolean[] tmp, int flags, int userId) {
6363        int numMatch = 0;
6364        final PermissionsState permissionsState = ps.getPermissionsState();
6365        for (int i=0; i<permissions.length; i++) {
6366            final String permission = permissions[i];
6367            if (permissionsState.hasPermission(permission, userId)) {
6368                tmp[i] = true;
6369                numMatch++;
6370            } else {
6371                tmp[i] = false;
6372            }
6373        }
6374        if (numMatch == 0) {
6375            return;
6376        }
6377        final PackageInfo pi;
6378        if (ps.pkg != null) {
6379            pi = generatePackageInfo(ps, flags, userId);
6380        } else {
6381            pi = generatePackageInfo(ps, flags, userId);
6382        }
6383        // The above might return null in cases of uninstalled apps or install-state
6384        // skew across users/profiles.
6385        if (pi != null) {
6386            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6387                if (numMatch == permissions.length) {
6388                    pi.requestedPermissions = permissions;
6389                } else {
6390                    pi.requestedPermissions = new String[numMatch];
6391                    numMatch = 0;
6392                    for (int i=0; i<permissions.length; i++) {
6393                        if (tmp[i]) {
6394                            pi.requestedPermissions[numMatch] = permissions[i];
6395                            numMatch++;
6396                        }
6397                    }
6398                }
6399            }
6400            list.add(pi);
6401        }
6402    }
6403
6404    @Override
6405    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6406            String[] permissions, int flags, int userId) {
6407        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6408        flags = updateFlagsForPackage(flags, userId, permissions);
6409        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6410                true /* requireFullPermission */, false /* checkShell */,
6411                "get packages holding permissions");
6412        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6413
6414        // writer
6415        synchronized (mPackages) {
6416            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6417            boolean[] tmpBools = new boolean[permissions.length];
6418            if (listUninstalled) {
6419                for (PackageSetting ps : mSettings.mPackages.values()) {
6420                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6421                            userId);
6422                }
6423            } else {
6424                for (PackageParser.Package pkg : mPackages.values()) {
6425                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6426                    if (ps != null) {
6427                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6428                                userId);
6429                    }
6430                }
6431            }
6432
6433            return new ParceledListSlice<PackageInfo>(list);
6434        }
6435    }
6436
6437    @Override
6438    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6439        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6440        flags = updateFlagsForApplication(flags, userId, null);
6441        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6442
6443        // writer
6444        synchronized (mPackages) {
6445            ArrayList<ApplicationInfo> list;
6446            if (listUninstalled) {
6447                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6448                for (PackageSetting ps : mSettings.mPackages.values()) {
6449                    ApplicationInfo ai;
6450                    int effectiveFlags = flags;
6451                    if (ps.isSystem()) {
6452                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6453                    }
6454                    if (ps.pkg != null) {
6455                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6456                                ps.readUserState(userId), userId);
6457                    } else {
6458                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6459                                userId);
6460                    }
6461                    if (ai != null) {
6462                        list.add(ai);
6463                    }
6464                }
6465            } else {
6466                list = new ArrayList<ApplicationInfo>(mPackages.size());
6467                for (PackageParser.Package p : mPackages.values()) {
6468                    if (p.mExtras != null) {
6469                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6470                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6471                        if (ai != null) {
6472                            list.add(ai);
6473                        }
6474                    }
6475                }
6476            }
6477
6478            return new ParceledListSlice<ApplicationInfo>(list);
6479        }
6480    }
6481
6482    @Override
6483    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6484        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6485            return null;
6486        }
6487
6488        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6489                "getEphemeralApplications");
6490        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6491                true /* requireFullPermission */, false /* checkShell */,
6492                "getEphemeralApplications");
6493        synchronized (mPackages) {
6494            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6495                    .getEphemeralApplicationsLPw(userId);
6496            if (ephemeralApps != null) {
6497                return new ParceledListSlice<>(ephemeralApps);
6498            }
6499        }
6500        return null;
6501    }
6502
6503    @Override
6504    public boolean isEphemeralApplication(String packageName, int userId) {
6505        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6506                true /* requireFullPermission */, false /* checkShell */,
6507                "isEphemeral");
6508        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6509            return false;
6510        }
6511
6512        if (!isCallerSameApp(packageName)) {
6513            return false;
6514        }
6515        synchronized (mPackages) {
6516            PackageParser.Package pkg = mPackages.get(packageName);
6517            if (pkg != null) {
6518                return pkg.applicationInfo.isEphemeralApp();
6519            }
6520        }
6521        return false;
6522    }
6523
6524    @Override
6525    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6526        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6527            return null;
6528        }
6529
6530        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6531                true /* requireFullPermission */, false /* checkShell */,
6532                "getCookie");
6533        if (!isCallerSameApp(packageName)) {
6534            return null;
6535        }
6536        synchronized (mPackages) {
6537            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6538                    packageName, userId);
6539        }
6540    }
6541
6542    @Override
6543    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6544        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6545            return true;
6546        }
6547
6548        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6549                true /* requireFullPermission */, true /* checkShell */,
6550                "setCookie");
6551        if (!isCallerSameApp(packageName)) {
6552            return false;
6553        }
6554        synchronized (mPackages) {
6555            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6556                    packageName, cookie, userId);
6557        }
6558    }
6559
6560    @Override
6561    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6562        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6563            return null;
6564        }
6565
6566        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6567                "getEphemeralApplicationIcon");
6568        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6569                true /* requireFullPermission */, false /* checkShell */,
6570                "getEphemeralApplicationIcon");
6571        synchronized (mPackages) {
6572            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6573                    packageName, userId);
6574        }
6575    }
6576
6577    private boolean isCallerSameApp(String packageName) {
6578        PackageParser.Package pkg = mPackages.get(packageName);
6579        return pkg != null
6580                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6581    }
6582
6583    @Override
6584    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6585        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6586    }
6587
6588    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6589        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6590
6591        // reader
6592        synchronized (mPackages) {
6593            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6594            final int userId = UserHandle.getCallingUserId();
6595            while (i.hasNext()) {
6596                final PackageParser.Package p = i.next();
6597                if (p.applicationInfo == null) continue;
6598
6599                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6600                        && !p.applicationInfo.isDirectBootAware();
6601                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6602                        && p.applicationInfo.isDirectBootAware();
6603
6604                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6605                        && (!mSafeMode || isSystemApp(p))
6606                        && (matchesUnaware || matchesAware)) {
6607                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6608                    if (ps != null) {
6609                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6610                                ps.readUserState(userId), userId);
6611                        if (ai != null) {
6612                            finalList.add(ai);
6613                        }
6614                    }
6615                }
6616            }
6617        }
6618
6619        return finalList;
6620    }
6621
6622    @Override
6623    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6624        if (!sUserManager.exists(userId)) return null;
6625        flags = updateFlagsForComponent(flags, userId, name);
6626        // reader
6627        synchronized (mPackages) {
6628            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6629            PackageSetting ps = provider != null
6630                    ? mSettings.mPackages.get(provider.owner.packageName)
6631                    : null;
6632            return ps != null
6633                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6634                    ? PackageParser.generateProviderInfo(provider, flags,
6635                            ps.readUserState(userId), userId)
6636                    : null;
6637        }
6638    }
6639
6640    /**
6641     * @deprecated
6642     */
6643    @Deprecated
6644    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6645        // reader
6646        synchronized (mPackages) {
6647            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6648                    .entrySet().iterator();
6649            final int userId = UserHandle.getCallingUserId();
6650            while (i.hasNext()) {
6651                Map.Entry<String, PackageParser.Provider> entry = i.next();
6652                PackageParser.Provider p = entry.getValue();
6653                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6654
6655                if (ps != null && p.syncable
6656                        && (!mSafeMode || (p.info.applicationInfo.flags
6657                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6658                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6659                            ps.readUserState(userId), userId);
6660                    if (info != null) {
6661                        outNames.add(entry.getKey());
6662                        outInfo.add(info);
6663                    }
6664                }
6665            }
6666        }
6667    }
6668
6669    @Override
6670    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6671            int uid, int flags) {
6672        final int userId = processName != null ? UserHandle.getUserId(uid)
6673                : UserHandle.getCallingUserId();
6674        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6675        flags = updateFlagsForComponent(flags, userId, processName);
6676
6677        ArrayList<ProviderInfo> finalList = null;
6678        // reader
6679        synchronized (mPackages) {
6680            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6681            while (i.hasNext()) {
6682                final PackageParser.Provider p = i.next();
6683                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6684                if (ps != null && p.info.authority != null
6685                        && (processName == null
6686                                || (p.info.processName.equals(processName)
6687                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6688                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6689                    if (finalList == null) {
6690                        finalList = new ArrayList<ProviderInfo>(3);
6691                    }
6692                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6693                            ps.readUserState(userId), userId);
6694                    if (info != null) {
6695                        finalList.add(info);
6696                    }
6697                }
6698            }
6699        }
6700
6701        if (finalList != null) {
6702            Collections.sort(finalList, mProviderInitOrderSorter);
6703            return new ParceledListSlice<ProviderInfo>(finalList);
6704        }
6705
6706        return ParceledListSlice.emptyList();
6707    }
6708
6709    @Override
6710    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6711        // reader
6712        synchronized (mPackages) {
6713            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6714            return PackageParser.generateInstrumentationInfo(i, flags);
6715        }
6716    }
6717
6718    @Override
6719    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6720            String targetPackage, int flags) {
6721        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6722    }
6723
6724    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6725            int flags) {
6726        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6727
6728        // reader
6729        synchronized (mPackages) {
6730            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6731            while (i.hasNext()) {
6732                final PackageParser.Instrumentation p = i.next();
6733                if (targetPackage == null
6734                        || targetPackage.equals(p.info.targetPackage)) {
6735                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6736                            flags);
6737                    if (ii != null) {
6738                        finalList.add(ii);
6739                    }
6740                }
6741            }
6742        }
6743
6744        return finalList;
6745    }
6746
6747    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6748        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6749        if (overlays == null) {
6750            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6751            return;
6752        }
6753        for (PackageParser.Package opkg : overlays.values()) {
6754            // Not much to do if idmap fails: we already logged the error
6755            // and we certainly don't want to abort installation of pkg simply
6756            // because an overlay didn't fit properly. For these reasons,
6757            // ignore the return value of createIdmapForPackagePairLI.
6758            createIdmapForPackagePairLI(pkg, opkg);
6759        }
6760    }
6761
6762    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6763            PackageParser.Package opkg) {
6764        if (!opkg.mTrustedOverlay) {
6765            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6766                    opkg.baseCodePath + ": overlay not trusted");
6767            return false;
6768        }
6769        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6770        if (overlaySet == null) {
6771            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6772                    opkg.baseCodePath + " but target package has no known overlays");
6773            return false;
6774        }
6775        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6776        // TODO: generate idmap for split APKs
6777        try {
6778            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6779        } catch (InstallerException e) {
6780            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6781                    + opkg.baseCodePath);
6782            return false;
6783        }
6784        PackageParser.Package[] overlayArray =
6785            overlaySet.values().toArray(new PackageParser.Package[0]);
6786        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6787            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6788                return p1.mOverlayPriority - p2.mOverlayPriority;
6789            }
6790        };
6791        Arrays.sort(overlayArray, cmp);
6792
6793        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6794        int i = 0;
6795        for (PackageParser.Package p : overlayArray) {
6796            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6797        }
6798        return true;
6799    }
6800
6801    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6803        try {
6804            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6805        } finally {
6806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6807        }
6808    }
6809
6810    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6811        final File[] files = dir.listFiles();
6812        if (ArrayUtils.isEmpty(files)) {
6813            Log.d(TAG, "No files in app dir " + dir);
6814            return;
6815        }
6816
6817        if (DEBUG_PACKAGE_SCANNING) {
6818            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6819                    + " flags=0x" + Integer.toHexString(parseFlags));
6820        }
6821        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
6822                mSeparateProcesses, mOnlyCore, mMetrics);
6823
6824        // Submit files for parsing in parallel
6825        int fileCount = 0;
6826        for (File file : files) {
6827            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6828                    && !PackageInstallerService.isStageName(file.getName());
6829            if (!isPackage) {
6830                // Ignore entries which are not packages
6831                continue;
6832            }
6833            parallelPackageParser.submit(file, parseFlags);
6834            fileCount++;
6835        }
6836
6837        // Process results one by one
6838        for (; fileCount > 0; fileCount--) {
6839            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
6840            Throwable throwable = parseResult.throwable;
6841            int errorCode = PackageManager.INSTALL_SUCCEEDED;
6842
6843            if (throwable == null) {
6844                try {
6845                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
6846                            currentTime, null);
6847                } catch (PackageManagerException e) {
6848                    errorCode = e.error;
6849                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
6850                }
6851            } else if (throwable instanceof PackageParser.PackageParserException) {
6852                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
6853                        throwable;
6854                errorCode = e.error;
6855                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
6856            } else {
6857                throw new IllegalStateException("Unexpected exception occurred while parsing "
6858                        + parseResult.scanFile, throwable);
6859            }
6860
6861            // Delete invalid userdata apps
6862            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6863                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
6864                logCriticalInfo(Log.WARN,
6865                        "Deleting invalid package at " + parseResult.scanFile);
6866                removeCodePathLI(parseResult.scanFile);
6867            }
6868        }
6869        parallelPackageParser.close();
6870    }
6871
6872    private static File getSettingsProblemFile() {
6873        File dataDir = Environment.getDataDirectory();
6874        File systemDir = new File(dataDir, "system");
6875        File fname = new File(systemDir, "uiderrors.txt");
6876        return fname;
6877    }
6878
6879    static void reportSettingsProblem(int priority, String msg) {
6880        logCriticalInfo(priority, msg);
6881    }
6882
6883    static void logCriticalInfo(int priority, String msg) {
6884        Slog.println(priority, TAG, msg);
6885        EventLogTags.writePmCriticalInfo(msg);
6886        try {
6887            File fname = getSettingsProblemFile();
6888            FileOutputStream out = new FileOutputStream(fname, true);
6889            PrintWriter pw = new FastPrintWriter(out);
6890            SimpleDateFormat formatter = new SimpleDateFormat();
6891            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6892            pw.println(dateString + ": " + msg);
6893            pw.close();
6894            FileUtils.setPermissions(
6895                    fname.toString(),
6896                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6897                    -1, -1);
6898        } catch (java.io.IOException e) {
6899        }
6900    }
6901
6902    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6903        if (srcFile.isDirectory()) {
6904            final File baseFile = new File(pkg.baseCodePath);
6905            long maxModifiedTime = baseFile.lastModified();
6906            if (pkg.splitCodePaths != null) {
6907                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6908                    final File splitFile = new File(pkg.splitCodePaths[i]);
6909                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6910                }
6911            }
6912            return maxModifiedTime;
6913        }
6914        return srcFile.lastModified();
6915    }
6916
6917    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6918            final int policyFlags) throws PackageManagerException {
6919        // When upgrading from pre-N MR1, verify the package time stamp using the package
6920        // directory and not the APK file.
6921        final long lastModifiedTime = mIsPreNMR1Upgrade
6922                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6923        if (ps != null
6924                && ps.codePath.equals(srcFile)
6925                && ps.timeStamp == lastModifiedTime
6926                && !isCompatSignatureUpdateNeeded(pkg)
6927                && !isRecoverSignatureUpdateNeeded(pkg)) {
6928            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6929            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6930            ArraySet<PublicKey> signingKs;
6931            synchronized (mPackages) {
6932                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6933            }
6934            if (ps.signatures.mSignatures != null
6935                    && ps.signatures.mSignatures.length != 0
6936                    && signingKs != null) {
6937                // Optimization: reuse the existing cached certificates
6938                // if the package appears to be unchanged.
6939                pkg.mSignatures = ps.signatures.mSignatures;
6940                pkg.mSigningKeys = signingKs;
6941                return;
6942            }
6943
6944            Slog.w(TAG, "PackageSetting for " + ps.name
6945                    + " is missing signatures.  Collecting certs again to recover them.");
6946        } else {
6947            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6948        }
6949
6950        try {
6951            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6952            PackageParser.collectCertificates(pkg, policyFlags);
6953        } catch (PackageParserException e) {
6954            throw PackageManagerException.from(e);
6955        } finally {
6956            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6957        }
6958    }
6959
6960    /**
6961     *  Traces a package scan.
6962     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6963     */
6964    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6965            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6966        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6967        try {
6968            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6969        } finally {
6970            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6971        }
6972    }
6973
6974    /**
6975     *  Scans a package and returns the newly parsed package.
6976     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6977     */
6978    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6979            long currentTime, UserHandle user) throws PackageManagerException {
6980        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6981        PackageParser pp = new PackageParser();
6982        pp.setSeparateProcesses(mSeparateProcesses);
6983        pp.setOnlyCoreApps(mOnlyCore);
6984        pp.setDisplayMetrics(mMetrics);
6985
6986        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6987            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6988        }
6989
6990        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6991        final PackageParser.Package pkg;
6992        try {
6993            pkg = pp.parsePackage(scanFile, parseFlags);
6994        } catch (PackageParserException e) {
6995            throw PackageManagerException.from(e);
6996        } finally {
6997            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6998        }
6999
7000        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7001    }
7002
7003    /**
7004     *  Scans a package and returns the newly parsed package.
7005     *  @throws PackageManagerException on a parse error.
7006     */
7007    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7008            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7009            throws PackageManagerException {
7010        // If the package has children and this is the first dive in the function
7011        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7012        // packages (parent and children) would be successfully scanned before the
7013        // actual scan since scanning mutates internal state and we want to atomically
7014        // install the package and its children.
7015        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7016            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7017                scanFlags |= SCAN_CHECK_ONLY;
7018            }
7019        } else {
7020            scanFlags &= ~SCAN_CHECK_ONLY;
7021        }
7022
7023        // Scan the parent
7024        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7025                scanFlags, currentTime, user);
7026
7027        // Scan the children
7028        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7029        for (int i = 0; i < childCount; i++) {
7030            PackageParser.Package childPackage = pkg.childPackages.get(i);
7031            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7032                    currentTime, user);
7033        }
7034
7035
7036        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7037            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7038        }
7039
7040        return scannedPkg;
7041    }
7042
7043    /**
7044     *  Scans a package and returns the newly parsed package.
7045     *  @throws PackageManagerException on a parse error.
7046     */
7047    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7048            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7049            throws PackageManagerException {
7050        PackageSetting ps = null;
7051        PackageSetting updatedPkg;
7052        // reader
7053        synchronized (mPackages) {
7054            // Look to see if we already know about this package.
7055            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7056            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7057                // This package has been renamed to its original name.  Let's
7058                // use that.
7059                ps = mSettings.getPackageLPr(oldName);
7060            }
7061            // If there was no original package, see one for the real package name.
7062            if (ps == null) {
7063                ps = mSettings.getPackageLPr(pkg.packageName);
7064            }
7065            // Check to see if this package could be hiding/updating a system
7066            // package.  Must look for it either under the original or real
7067            // package name depending on our state.
7068            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7069            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7070
7071            // If this is a package we don't know about on the system partition, we
7072            // may need to remove disabled child packages on the system partition
7073            // or may need to not add child packages if the parent apk is updated
7074            // on the data partition and no longer defines this child package.
7075            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7076                // If this is a parent package for an updated system app and this system
7077                // app got an OTA update which no longer defines some of the child packages
7078                // we have to prune them from the disabled system packages.
7079                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7080                if (disabledPs != null) {
7081                    final int scannedChildCount = (pkg.childPackages != null)
7082                            ? pkg.childPackages.size() : 0;
7083                    final int disabledChildCount = disabledPs.childPackageNames != null
7084                            ? disabledPs.childPackageNames.size() : 0;
7085                    for (int i = 0; i < disabledChildCount; i++) {
7086                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7087                        boolean disabledPackageAvailable = false;
7088                        for (int j = 0; j < scannedChildCount; j++) {
7089                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7090                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7091                                disabledPackageAvailable = true;
7092                                break;
7093                            }
7094                         }
7095                         if (!disabledPackageAvailable) {
7096                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7097                         }
7098                    }
7099                }
7100            }
7101        }
7102
7103        boolean updatedPkgBetter = false;
7104        // First check if this is a system package that may involve an update
7105        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7106            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7107            // it needs to drop FLAG_PRIVILEGED.
7108            if (locationIsPrivileged(scanFile)) {
7109                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7110            } else {
7111                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7112            }
7113
7114            if (ps != null && !ps.codePath.equals(scanFile)) {
7115                // The path has changed from what was last scanned...  check the
7116                // version of the new path against what we have stored to determine
7117                // what to do.
7118                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7119                if (pkg.mVersionCode <= ps.versionCode) {
7120                    // The system package has been updated and the code path does not match
7121                    // Ignore entry. Skip it.
7122                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7123                            + " ignored: updated version " + ps.versionCode
7124                            + " better than this " + pkg.mVersionCode);
7125                    if (!updatedPkg.codePath.equals(scanFile)) {
7126                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7127                                + ps.name + " changing from " + updatedPkg.codePathString
7128                                + " to " + scanFile);
7129                        updatedPkg.codePath = scanFile;
7130                        updatedPkg.codePathString = scanFile.toString();
7131                        updatedPkg.resourcePath = scanFile;
7132                        updatedPkg.resourcePathString = scanFile.toString();
7133                    }
7134                    updatedPkg.pkg = pkg;
7135                    updatedPkg.versionCode = pkg.mVersionCode;
7136
7137                    // Update the disabled system child packages to point to the package too.
7138                    final int childCount = updatedPkg.childPackageNames != null
7139                            ? updatedPkg.childPackageNames.size() : 0;
7140                    for (int i = 0; i < childCount; i++) {
7141                        String childPackageName = updatedPkg.childPackageNames.get(i);
7142                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7143                                childPackageName);
7144                        if (updatedChildPkg != null) {
7145                            updatedChildPkg.pkg = pkg;
7146                            updatedChildPkg.versionCode = pkg.mVersionCode;
7147                        }
7148                    }
7149
7150                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7151                            + scanFile + " ignored: updated version " + ps.versionCode
7152                            + " better than this " + pkg.mVersionCode);
7153                } else {
7154                    // The current app on the system partition is better than
7155                    // what we have updated to on the data partition; switch
7156                    // back to the system partition version.
7157                    // At this point, its safely assumed that package installation for
7158                    // apps in system partition will go through. If not there won't be a working
7159                    // version of the app
7160                    // writer
7161                    synchronized (mPackages) {
7162                        // Just remove the loaded entries from package lists.
7163                        mPackages.remove(ps.name);
7164                    }
7165
7166                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7167                            + " reverting from " + ps.codePathString
7168                            + ": new version " + pkg.mVersionCode
7169                            + " better than installed " + ps.versionCode);
7170
7171                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7172                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7173                    synchronized (mInstallLock) {
7174                        args.cleanUpResourcesLI();
7175                    }
7176                    synchronized (mPackages) {
7177                        mSettings.enableSystemPackageLPw(ps.name);
7178                    }
7179                    updatedPkgBetter = true;
7180                }
7181            }
7182        }
7183
7184        if (updatedPkg != null) {
7185            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7186            // initially
7187            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7188
7189            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7190            // flag set initially
7191            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7192                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7193            }
7194        }
7195
7196        // Verify certificates against what was last scanned
7197        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7198
7199        /*
7200         * A new system app appeared, but we already had a non-system one of the
7201         * same name installed earlier.
7202         */
7203        boolean shouldHideSystemApp = false;
7204        if (updatedPkg == null && ps != null
7205                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7206            /*
7207             * Check to make sure the signatures match first. If they don't,
7208             * wipe the installed application and its data.
7209             */
7210            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7211                    != PackageManager.SIGNATURE_MATCH) {
7212                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7213                        + " signatures don't match existing userdata copy; removing");
7214                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7215                        "scanPackageInternalLI")) {
7216                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7217                }
7218                ps = null;
7219            } else {
7220                /*
7221                 * If the newly-added system app is an older version than the
7222                 * already installed version, hide it. It will be scanned later
7223                 * and re-added like an update.
7224                 */
7225                if (pkg.mVersionCode <= ps.versionCode) {
7226                    shouldHideSystemApp = true;
7227                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7228                            + " but new version " + pkg.mVersionCode + " better than installed "
7229                            + ps.versionCode + "; hiding system");
7230                } else {
7231                    /*
7232                     * The newly found system app is a newer version that the
7233                     * one previously installed. Simply remove the
7234                     * already-installed application and replace it with our own
7235                     * while keeping the application data.
7236                     */
7237                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7238                            + " reverting from " + ps.codePathString + ": new version "
7239                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7240                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7241                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7242                    synchronized (mInstallLock) {
7243                        args.cleanUpResourcesLI();
7244                    }
7245                }
7246            }
7247        }
7248
7249        // The apk is forward locked (not public) if its code and resources
7250        // are kept in different files. (except for app in either system or
7251        // vendor path).
7252        // TODO grab this value from PackageSettings
7253        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7254            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7255                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7256            }
7257        }
7258
7259        // TODO: extend to support forward-locked splits
7260        String resourcePath = null;
7261        String baseResourcePath = null;
7262        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7263            if (ps != null && ps.resourcePathString != null) {
7264                resourcePath = ps.resourcePathString;
7265                baseResourcePath = ps.resourcePathString;
7266            } else {
7267                // Should not happen at all. Just log an error.
7268                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7269            }
7270        } else {
7271            resourcePath = pkg.codePath;
7272            baseResourcePath = pkg.baseCodePath;
7273        }
7274
7275        // Set application objects path explicitly.
7276        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7277        pkg.setApplicationInfoCodePath(pkg.codePath);
7278        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7279        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7280        pkg.setApplicationInfoResourcePath(resourcePath);
7281        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7282        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7283
7284        // Note that we invoke the following method only if we are about to unpack an application
7285        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7286                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7287
7288        /*
7289         * If the system app should be overridden by a previously installed
7290         * data, hide the system app now and let the /data/app scan pick it up
7291         * again.
7292         */
7293        if (shouldHideSystemApp) {
7294            synchronized (mPackages) {
7295                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7296            }
7297        }
7298
7299        return scannedPkg;
7300    }
7301
7302    private static String fixProcessName(String defProcessName,
7303            String processName) {
7304        if (processName == null) {
7305            return defProcessName;
7306        }
7307        return processName;
7308    }
7309
7310    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7311            throws PackageManagerException {
7312        if (pkgSetting.signatures.mSignatures != null) {
7313            // Already existing package. Make sure signatures match
7314            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7315                    == PackageManager.SIGNATURE_MATCH;
7316            if (!match) {
7317                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7318                        == PackageManager.SIGNATURE_MATCH;
7319            }
7320            if (!match) {
7321                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7322                        == PackageManager.SIGNATURE_MATCH;
7323            }
7324            if (!match) {
7325                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7326                        + pkg.packageName + " signatures do not match the "
7327                        + "previously installed version; ignoring!");
7328            }
7329        }
7330
7331        // Check for shared user signatures
7332        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7333            // Already existing package. Make sure signatures match
7334            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7335                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7336            if (!match) {
7337                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7338                        == PackageManager.SIGNATURE_MATCH;
7339            }
7340            if (!match) {
7341                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7342                        == PackageManager.SIGNATURE_MATCH;
7343            }
7344            if (!match) {
7345                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7346                        "Package " + pkg.packageName
7347                        + " has no signatures that match those in shared user "
7348                        + pkgSetting.sharedUser.name + "; ignoring!");
7349            }
7350        }
7351    }
7352
7353    /**
7354     * Enforces that only the system UID or root's UID can call a method exposed
7355     * via Binder.
7356     *
7357     * @param message used as message if SecurityException is thrown
7358     * @throws SecurityException if the caller is not system or root
7359     */
7360    private static final void enforceSystemOrRoot(String message) {
7361        final int uid = Binder.getCallingUid();
7362        if (uid != Process.SYSTEM_UID && uid != 0) {
7363            throw new SecurityException(message);
7364        }
7365    }
7366
7367    @Override
7368    public void performFstrimIfNeeded() {
7369        enforceSystemOrRoot("Only the system can request fstrim");
7370
7371        // Before everything else, see whether we need to fstrim.
7372        try {
7373            IStorageManager sm = PackageHelper.getStorageManager();
7374            if (sm != null) {
7375                boolean doTrim = false;
7376                final long interval = android.provider.Settings.Global.getLong(
7377                        mContext.getContentResolver(),
7378                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7379                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7380                if (interval > 0) {
7381                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7382                    if (timeSinceLast > interval) {
7383                        doTrim = true;
7384                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7385                                + "; running immediately");
7386                    }
7387                }
7388                if (doTrim) {
7389                    final boolean dexOptDialogShown;
7390                    synchronized (mPackages) {
7391                        dexOptDialogShown = mDexOptDialogShown;
7392                    }
7393                    if (!isFirstBoot() && dexOptDialogShown) {
7394                        try {
7395                            ActivityManager.getService().showBootMessage(
7396                                    mContext.getResources().getString(
7397                                            R.string.android_upgrading_fstrim), true);
7398                        } catch (RemoteException e) {
7399                        }
7400                    }
7401                    sm.runMaintenance();
7402                }
7403            } else {
7404                Slog.e(TAG, "storageManager service unavailable!");
7405            }
7406        } catch (RemoteException e) {
7407            // Can't happen; StorageManagerService is local
7408        }
7409    }
7410
7411    @Override
7412    public void updatePackagesIfNeeded() {
7413        enforceSystemOrRoot("Only the system can request package update");
7414
7415        // We need to re-extract after an OTA.
7416        boolean causeUpgrade = isUpgrade();
7417
7418        // First boot or factory reset.
7419        // Note: we also handle devices that are upgrading to N right now as if it is their
7420        //       first boot, as they do not have profile data.
7421        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7422
7423        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7424        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7425
7426        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7427            return;
7428        }
7429
7430        List<PackageParser.Package> pkgs;
7431        synchronized (mPackages) {
7432            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7433        }
7434
7435        final long startTime = System.nanoTime();
7436        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7437                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7438
7439        final int elapsedTimeSeconds =
7440                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7441
7442        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7443        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7444        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7445        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7446        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7447    }
7448
7449    /**
7450     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7451     * containing statistics about the invocation. The array consists of three elements,
7452     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7453     * and {@code numberOfPackagesFailed}.
7454     */
7455    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7456            String compilerFilter) {
7457
7458        int numberOfPackagesVisited = 0;
7459        int numberOfPackagesOptimized = 0;
7460        int numberOfPackagesSkipped = 0;
7461        int numberOfPackagesFailed = 0;
7462        final int numberOfPackagesToDexopt = pkgs.size();
7463
7464        for (PackageParser.Package pkg : pkgs) {
7465            numberOfPackagesVisited++;
7466
7467            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7468                if (DEBUG_DEXOPT) {
7469                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7470                }
7471                numberOfPackagesSkipped++;
7472                continue;
7473            }
7474
7475            if (DEBUG_DEXOPT) {
7476                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7477                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7478            }
7479
7480            if (showDialog) {
7481                try {
7482                    ActivityManager.getService().showBootMessage(
7483                            mContext.getResources().getString(R.string.android_upgrading_apk,
7484                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7485                } catch (RemoteException e) {
7486                }
7487                synchronized (mPackages) {
7488                    mDexOptDialogShown = true;
7489                }
7490            }
7491
7492            // If the OTA updates a system app which was previously preopted to a non-preopted state
7493            // the app might end up being verified at runtime. That's because by default the apps
7494            // are verify-profile but for preopted apps there's no profile.
7495            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7496            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7497            // filter (by default interpret-only).
7498            // Note that at this stage unused apps are already filtered.
7499            if (isSystemApp(pkg) &&
7500                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7501                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7502                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7503            }
7504
7505            // If the OTA updates a system app which was previously preopted to a non-preopted state
7506            // the app might end up being verified at runtime. That's because by default the apps
7507            // are verify-profile but for preopted apps there's no profile.
7508            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7509            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7510            // filter (by default interpret-only).
7511            // Note that at this stage unused apps are already filtered.
7512            if (isSystemApp(pkg) &&
7513                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7514                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7515                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7516            }
7517
7518            // checkProfiles is false to avoid merging profiles during boot which
7519            // might interfere with background compilation (b/28612421).
7520            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7521            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7522            // trade-off worth doing to save boot time work.
7523            int dexOptStatus = performDexOptTraced(pkg.packageName,
7524                    false /* checkProfiles */,
7525                    compilerFilter,
7526                    false /* force */);
7527            switch (dexOptStatus) {
7528                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7529                    numberOfPackagesOptimized++;
7530                    break;
7531                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7532                    numberOfPackagesSkipped++;
7533                    break;
7534                case PackageDexOptimizer.DEX_OPT_FAILED:
7535                    numberOfPackagesFailed++;
7536                    break;
7537                default:
7538                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7539                    break;
7540            }
7541        }
7542
7543        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7544                numberOfPackagesFailed };
7545    }
7546
7547    @Override
7548    public void notifyPackageUse(String packageName, int reason) {
7549        synchronized (mPackages) {
7550            PackageParser.Package p = mPackages.get(packageName);
7551            if (p == null) {
7552                return;
7553            }
7554            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7555        }
7556    }
7557
7558    // TODO: this is not used nor needed. Delete it.
7559    @Override
7560    public boolean performDexOptIfNeeded(String packageName) {
7561        int dexOptStatus = performDexOptTraced(packageName,
7562                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7563        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7564    }
7565
7566    @Override
7567    public boolean performDexOpt(String packageName,
7568            boolean checkProfiles, int compileReason, boolean force) {
7569        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7570                getCompilerFilterForReason(compileReason), force);
7571        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7572    }
7573
7574    @Override
7575    public boolean performDexOptMode(String packageName,
7576            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7577        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7578                targetCompilerFilter, force);
7579        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7580    }
7581
7582    private int performDexOptTraced(String packageName,
7583                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7584        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7585        try {
7586            return performDexOptInternal(packageName, checkProfiles,
7587                    targetCompilerFilter, force);
7588        } finally {
7589            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7590        }
7591    }
7592
7593    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7594    // if the package can now be considered up to date for the given filter.
7595    private int performDexOptInternal(String packageName,
7596                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7597        PackageParser.Package p;
7598        synchronized (mPackages) {
7599            p = mPackages.get(packageName);
7600            if (p == null) {
7601                // Package could not be found. Report failure.
7602                return PackageDexOptimizer.DEX_OPT_FAILED;
7603            }
7604            mPackageUsage.maybeWriteAsync(mPackages);
7605            mCompilerStats.maybeWriteAsync();
7606        }
7607        long callingId = Binder.clearCallingIdentity();
7608        try {
7609            synchronized (mInstallLock) {
7610                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7611                        targetCompilerFilter, force);
7612            }
7613        } finally {
7614            Binder.restoreCallingIdentity(callingId);
7615        }
7616    }
7617
7618    public ArraySet<String> getOptimizablePackages() {
7619        ArraySet<String> pkgs = new ArraySet<String>();
7620        synchronized (mPackages) {
7621            for (PackageParser.Package p : mPackages.values()) {
7622                if (PackageDexOptimizer.canOptimizePackage(p)) {
7623                    pkgs.add(p.packageName);
7624                }
7625            }
7626        }
7627        return pkgs;
7628    }
7629
7630    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7631            boolean checkProfiles, String targetCompilerFilter,
7632            boolean force) {
7633        // Select the dex optimizer based on the force parameter.
7634        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7635        //       allocate an object here.
7636        PackageDexOptimizer pdo = force
7637                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7638                : mPackageDexOptimizer;
7639
7640        // Optimize all dependencies first. Note: we ignore the return value and march on
7641        // on errors.
7642        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7643        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7644        if (!deps.isEmpty()) {
7645            for (PackageParser.Package depPackage : deps) {
7646                // TODO: Analyze and investigate if we (should) profile libraries.
7647                // Currently this will do a full compilation of the library by default.
7648                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7649                        false /* checkProfiles */,
7650                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7651                        getOrCreateCompilerPackageStats(depPackage));
7652            }
7653        }
7654        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7655                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7656    }
7657
7658    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7659        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7660            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7661            Set<String> collectedNames = new HashSet<>();
7662            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7663
7664            retValue.remove(p);
7665
7666            return retValue;
7667        } else {
7668            return Collections.emptyList();
7669        }
7670    }
7671
7672    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7673            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7674        if (!collectedNames.contains(p.packageName)) {
7675            collectedNames.add(p.packageName);
7676            collected.add(p);
7677
7678            if (p.usesLibraries != null) {
7679                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7680            }
7681            if (p.usesOptionalLibraries != null) {
7682                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7683                        collectedNames);
7684            }
7685        }
7686    }
7687
7688    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7689            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7690        for (String libName : libs) {
7691            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7692            if (libPkg != null) {
7693                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7694            }
7695        }
7696    }
7697
7698    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7699        synchronized (mPackages) {
7700            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7701            if (lib != null && lib.apk != null) {
7702                return mPackages.get(lib.apk);
7703            }
7704        }
7705        return null;
7706    }
7707
7708    public void shutdown() {
7709        mPackageUsage.writeNow(mPackages);
7710        mCompilerStats.writeNow();
7711    }
7712
7713    @Override
7714    public void dumpProfiles(String packageName) {
7715        PackageParser.Package pkg;
7716        synchronized (mPackages) {
7717            pkg = mPackages.get(packageName);
7718            if (pkg == null) {
7719                throw new IllegalArgumentException("Unknown package: " + packageName);
7720            }
7721        }
7722        /* Only the shell, root, or the app user should be able to dump profiles. */
7723        int callingUid = Binder.getCallingUid();
7724        if (callingUid != Process.SHELL_UID &&
7725            callingUid != Process.ROOT_UID &&
7726            callingUid != pkg.applicationInfo.uid) {
7727            throw new SecurityException("dumpProfiles");
7728        }
7729
7730        synchronized (mInstallLock) {
7731            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7732            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7733            try {
7734                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7735                String gid = Integer.toString(sharedGid);
7736                String codePaths = TextUtils.join(";", allCodePaths);
7737                mInstaller.dumpProfiles(gid, packageName, codePaths);
7738            } catch (InstallerException e) {
7739                Slog.w(TAG, "Failed to dump profiles", e);
7740            }
7741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7742        }
7743    }
7744
7745    @Override
7746    public void forceDexOpt(String packageName) {
7747        enforceSystemOrRoot("forceDexOpt");
7748
7749        PackageParser.Package pkg;
7750        synchronized (mPackages) {
7751            pkg = mPackages.get(packageName);
7752            if (pkg == null) {
7753                throw new IllegalArgumentException("Unknown package: " + packageName);
7754            }
7755        }
7756
7757        synchronized (mInstallLock) {
7758            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7759
7760            // Whoever is calling forceDexOpt wants a fully compiled package.
7761            // Don't use profiles since that may cause compilation to be skipped.
7762            final int res = performDexOptInternalWithDependenciesLI(pkg,
7763                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7764                    true /* force */);
7765
7766            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7767            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7768                throw new IllegalStateException("Failed to dexopt: " + res);
7769            }
7770        }
7771    }
7772
7773    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7774        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7775            Slog.w(TAG, "Unable to update from " + oldPkg.name
7776                    + " to " + newPkg.packageName
7777                    + ": old package not in system partition");
7778            return false;
7779        } else if (mPackages.get(oldPkg.name) != null) {
7780            Slog.w(TAG, "Unable to update from " + oldPkg.name
7781                    + " to " + newPkg.packageName
7782                    + ": old package still exists");
7783            return false;
7784        }
7785        return true;
7786    }
7787
7788    void removeCodePathLI(File codePath) {
7789        if (codePath.isDirectory()) {
7790            try {
7791                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7792            } catch (InstallerException e) {
7793                Slog.w(TAG, "Failed to remove code path", e);
7794            }
7795        } else {
7796            codePath.delete();
7797        }
7798    }
7799
7800    private int[] resolveUserIds(int userId) {
7801        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7802    }
7803
7804    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7805        if (pkg == null) {
7806            Slog.wtf(TAG, "Package was null!", new Throwable());
7807            return;
7808        }
7809        clearAppDataLeafLIF(pkg, userId, flags);
7810        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7811        for (int i = 0; i < childCount; i++) {
7812            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7813        }
7814    }
7815
7816    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7817        final PackageSetting ps;
7818        synchronized (mPackages) {
7819            ps = mSettings.mPackages.get(pkg.packageName);
7820        }
7821        for (int realUserId : resolveUserIds(userId)) {
7822            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7823            try {
7824                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7825                        ceDataInode);
7826            } catch (InstallerException e) {
7827                Slog.w(TAG, String.valueOf(e));
7828            }
7829        }
7830    }
7831
7832    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7833        if (pkg == null) {
7834            Slog.wtf(TAG, "Package was null!", new Throwable());
7835            return;
7836        }
7837        destroyAppDataLeafLIF(pkg, userId, flags);
7838        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7839        for (int i = 0; i < childCount; i++) {
7840            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7841        }
7842    }
7843
7844    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7845        final PackageSetting ps;
7846        synchronized (mPackages) {
7847            ps = mSettings.mPackages.get(pkg.packageName);
7848        }
7849        for (int realUserId : resolveUserIds(userId)) {
7850            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7851            try {
7852                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7853                        ceDataInode);
7854            } catch (InstallerException e) {
7855                Slog.w(TAG, String.valueOf(e));
7856            }
7857        }
7858    }
7859
7860    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7861        if (pkg == null) {
7862            Slog.wtf(TAG, "Package was null!", new Throwable());
7863            return;
7864        }
7865        destroyAppProfilesLeafLIF(pkg);
7866        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7867        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7868        for (int i = 0; i < childCount; i++) {
7869            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7870            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7871                    true /* removeBaseMarker */);
7872        }
7873    }
7874
7875    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7876            boolean removeBaseMarker) {
7877        if (pkg.isForwardLocked()) {
7878            return;
7879        }
7880
7881        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7882            try {
7883                path = PackageManagerServiceUtils.realpath(new File(path));
7884            } catch (IOException e) {
7885                // TODO: Should we return early here ?
7886                Slog.w(TAG, "Failed to get canonical path", e);
7887                continue;
7888            }
7889
7890            final String useMarker = path.replace('/', '@');
7891            for (int realUserId : resolveUserIds(userId)) {
7892                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7893                if (removeBaseMarker) {
7894                    File foreignUseMark = new File(profileDir, useMarker);
7895                    if (foreignUseMark.exists()) {
7896                        if (!foreignUseMark.delete()) {
7897                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7898                                    + pkg.packageName);
7899                        }
7900                    }
7901                }
7902
7903                File[] markers = profileDir.listFiles();
7904                if (markers != null) {
7905                    final String searchString = "@" + pkg.packageName + "@";
7906                    // We also delete all markers that contain the package name we're
7907                    // uninstalling. These are associated with secondary dex-files belonging
7908                    // to the package. Reconstructing the path of these dex files is messy
7909                    // in general.
7910                    for (File marker : markers) {
7911                        if (marker.getName().indexOf(searchString) > 0) {
7912                            if (!marker.delete()) {
7913                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7914                                    + pkg.packageName);
7915                            }
7916                        }
7917                    }
7918                }
7919            }
7920        }
7921    }
7922
7923    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7924        try {
7925            mInstaller.destroyAppProfiles(pkg.packageName);
7926        } catch (InstallerException e) {
7927            Slog.w(TAG, String.valueOf(e));
7928        }
7929    }
7930
7931    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7932        if (pkg == null) {
7933            Slog.wtf(TAG, "Package was null!", new Throwable());
7934            return;
7935        }
7936        clearAppProfilesLeafLIF(pkg);
7937        // We don't remove the base foreign use marker when clearing profiles because
7938        // we will rename it when the app is updated. Unlike the actual profile contents,
7939        // the foreign use marker is good across installs.
7940        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7941        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7942        for (int i = 0; i < childCount; i++) {
7943            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7944        }
7945    }
7946
7947    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7948        try {
7949            mInstaller.clearAppProfiles(pkg.packageName);
7950        } catch (InstallerException e) {
7951            Slog.w(TAG, String.valueOf(e));
7952        }
7953    }
7954
7955    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7956            long lastUpdateTime) {
7957        // Set parent install/update time
7958        PackageSetting ps = (PackageSetting) pkg.mExtras;
7959        if (ps != null) {
7960            ps.firstInstallTime = firstInstallTime;
7961            ps.lastUpdateTime = lastUpdateTime;
7962        }
7963        // Set children install/update time
7964        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7965        for (int i = 0; i < childCount; i++) {
7966            PackageParser.Package childPkg = pkg.childPackages.get(i);
7967            ps = (PackageSetting) childPkg.mExtras;
7968            if (ps != null) {
7969                ps.firstInstallTime = firstInstallTime;
7970                ps.lastUpdateTime = lastUpdateTime;
7971            }
7972        }
7973    }
7974
7975    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7976            PackageParser.Package changingLib) {
7977        if (file.path != null) {
7978            usesLibraryFiles.add(file.path);
7979            return;
7980        }
7981        PackageParser.Package p = mPackages.get(file.apk);
7982        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7983            // If we are doing this while in the middle of updating a library apk,
7984            // then we need to make sure to use that new apk for determining the
7985            // dependencies here.  (We haven't yet finished committing the new apk
7986            // to the package manager state.)
7987            if (p == null || p.packageName.equals(changingLib.packageName)) {
7988                p = changingLib;
7989            }
7990        }
7991        if (p != null) {
7992            usesLibraryFiles.addAll(p.getAllCodePaths());
7993        }
7994    }
7995
7996    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
7997            PackageParser.Package changingLib) throws PackageManagerException {
7998        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7999            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8000            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8001            for (int i=0; i<N; i++) {
8002                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8003                if (file == null) {
8004                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8005                            "Package " + pkg.packageName + " requires unavailable shared library "
8006                            + pkg.usesLibraries.get(i) + "; failing!");
8007                }
8008                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8009            }
8010            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8011            for (int i=0; i<N; i++) {
8012                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8013                if (file == null) {
8014                    Slog.w(TAG, "Package " + pkg.packageName
8015                            + " desires unavailable shared library "
8016                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8017                } else {
8018                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8019                }
8020            }
8021            N = usesLibraryFiles.size();
8022            if (N > 0) {
8023                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8024            } else {
8025                pkg.usesLibraryFiles = null;
8026            }
8027        }
8028    }
8029
8030    private static boolean hasString(List<String> list, List<String> which) {
8031        if (list == null) {
8032            return false;
8033        }
8034        for (int i=list.size()-1; i>=0; i--) {
8035            for (int j=which.size()-1; j>=0; j--) {
8036                if (which.get(j).equals(list.get(i))) {
8037                    return true;
8038                }
8039            }
8040        }
8041        return false;
8042    }
8043
8044    private void updateAllSharedLibrariesLPw() {
8045        for (PackageParser.Package pkg : mPackages.values()) {
8046            try {
8047                updateSharedLibrariesLPr(pkg, null);
8048            } catch (PackageManagerException e) {
8049                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8050            }
8051        }
8052    }
8053
8054    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8055            PackageParser.Package changingPkg) {
8056        ArrayList<PackageParser.Package> res = null;
8057        for (PackageParser.Package pkg : mPackages.values()) {
8058            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8059                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8060                if (res == null) {
8061                    res = new ArrayList<PackageParser.Package>();
8062                }
8063                res.add(pkg);
8064                try {
8065                    updateSharedLibrariesLPr(pkg, changingPkg);
8066                } catch (PackageManagerException e) {
8067                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8068                }
8069            }
8070        }
8071        return res;
8072    }
8073
8074    /**
8075     * Derive the value of the {@code cpuAbiOverride} based on the provided
8076     * value and an optional stored value from the package settings.
8077     */
8078    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8079        String cpuAbiOverride = null;
8080
8081        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8082            cpuAbiOverride = null;
8083        } else if (abiOverride != null) {
8084            cpuAbiOverride = abiOverride;
8085        } else if (settings != null) {
8086            cpuAbiOverride = settings.cpuAbiOverrideString;
8087        }
8088
8089        return cpuAbiOverride;
8090    }
8091
8092    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8093            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8094                    throws PackageManagerException {
8095        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8096        // If the package has children and this is the first dive in the function
8097        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8098        // whether all packages (parent and children) would be successfully scanned
8099        // before the actual scan since scanning mutates internal state and we want
8100        // to atomically install the package and its children.
8101        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8102            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8103                scanFlags |= SCAN_CHECK_ONLY;
8104            }
8105        } else {
8106            scanFlags &= ~SCAN_CHECK_ONLY;
8107        }
8108
8109        final PackageParser.Package scannedPkg;
8110        try {
8111            // Scan the parent
8112            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8113            // Scan the children
8114            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8115            for (int i = 0; i < childCount; i++) {
8116                PackageParser.Package childPkg = pkg.childPackages.get(i);
8117                scanPackageLI(childPkg, policyFlags,
8118                        scanFlags, currentTime, user);
8119            }
8120        } finally {
8121            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8122        }
8123
8124        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8125            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8126        }
8127
8128        return scannedPkg;
8129    }
8130
8131    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8132            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8133        boolean success = false;
8134        try {
8135            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8136                    currentTime, user);
8137            success = true;
8138            return res;
8139        } finally {
8140            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8141                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8142                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8143                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8144                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8145            }
8146        }
8147    }
8148
8149    /**
8150     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8151     */
8152    private static boolean apkHasCode(String fileName) {
8153        StrictJarFile jarFile = null;
8154        try {
8155            jarFile = new StrictJarFile(fileName,
8156                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8157            return jarFile.findEntry("classes.dex") != null;
8158        } catch (IOException ignore) {
8159        } finally {
8160            try {
8161                if (jarFile != null) {
8162                    jarFile.close();
8163                }
8164            } catch (IOException ignore) {}
8165        }
8166        return false;
8167    }
8168
8169    /**
8170     * Enforces code policy for the package. This ensures that if an APK has
8171     * declared hasCode="true" in its manifest that the APK actually contains
8172     * code.
8173     *
8174     * @throws PackageManagerException If bytecode could not be found when it should exist
8175     */
8176    private static void assertCodePolicy(PackageParser.Package pkg)
8177            throws PackageManagerException {
8178        final boolean shouldHaveCode =
8179                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8180        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8181            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8182                    "Package " + pkg.baseCodePath + " code is missing");
8183        }
8184
8185        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8186            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8187                final boolean splitShouldHaveCode =
8188                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8189                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8190                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8191                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8192                }
8193            }
8194        }
8195    }
8196
8197    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8198            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8199                    throws PackageManagerException {
8200        if (DEBUG_PACKAGE_SCANNING) {
8201            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8202                Log.d(TAG, "Scanning package " + pkg.packageName);
8203        }
8204
8205        applyPolicy(pkg, policyFlags);
8206
8207        assertPackageIsValid(pkg, policyFlags, scanFlags);
8208
8209        // Initialize package source and resource directories
8210        final File scanFile = new File(pkg.codePath);
8211        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8212        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8213
8214        SharedUserSetting suid = null;
8215        PackageSetting pkgSetting = null;
8216
8217        // Getting the package setting may have a side-effect, so if we
8218        // are only checking if scan would succeed, stash a copy of the
8219        // old setting to restore at the end.
8220        PackageSetting nonMutatedPs = null;
8221
8222        // We keep references to the derived CPU Abis from settings in oder to reuse
8223        // them in the case where we're not upgrading or booting for the first time.
8224        String primaryCpuAbiFromSettings = null;
8225        String secondaryCpuAbiFromSettings = null;
8226
8227        // writer
8228        synchronized (mPackages) {
8229            if (pkg.mSharedUserId != null) {
8230                // SIDE EFFECTS; may potentially allocate a new shared user
8231                suid = mSettings.getSharedUserLPw(
8232                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8233                if (DEBUG_PACKAGE_SCANNING) {
8234                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8235                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8236                                + "): packages=" + suid.packages);
8237                }
8238            }
8239
8240            // Check if we are renaming from an original package name.
8241            PackageSetting origPackage = null;
8242            String realName = null;
8243            if (pkg.mOriginalPackages != null) {
8244                // This package may need to be renamed to a previously
8245                // installed name.  Let's check on that...
8246                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8247                if (pkg.mOriginalPackages.contains(renamed)) {
8248                    // This package had originally been installed as the
8249                    // original name, and we have already taken care of
8250                    // transitioning to the new one.  Just update the new
8251                    // one to continue using the old name.
8252                    realName = pkg.mRealPackage;
8253                    if (!pkg.packageName.equals(renamed)) {
8254                        // Callers into this function may have already taken
8255                        // care of renaming the package; only do it here if
8256                        // it is not already done.
8257                        pkg.setPackageName(renamed);
8258                    }
8259                } else {
8260                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8261                        if ((origPackage = mSettings.getPackageLPr(
8262                                pkg.mOriginalPackages.get(i))) != null) {
8263                            // We do have the package already installed under its
8264                            // original name...  should we use it?
8265                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8266                                // New package is not compatible with original.
8267                                origPackage = null;
8268                                continue;
8269                            } else if (origPackage.sharedUser != null) {
8270                                // Make sure uid is compatible between packages.
8271                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8272                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8273                                            + " to " + pkg.packageName + ": old uid "
8274                                            + origPackage.sharedUser.name
8275                                            + " differs from " + pkg.mSharedUserId);
8276                                    origPackage = null;
8277                                    continue;
8278                                }
8279                                // TODO: Add case when shared user id is added [b/28144775]
8280                            } else {
8281                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8282                                        + pkg.packageName + " to old name " + origPackage.name);
8283                            }
8284                            break;
8285                        }
8286                    }
8287                }
8288            }
8289
8290            if (mTransferedPackages.contains(pkg.packageName)) {
8291                Slog.w(TAG, "Package " + pkg.packageName
8292                        + " was transferred to another, but its .apk remains");
8293            }
8294
8295            // See comments in nonMutatedPs declaration
8296            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8297                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8298                if (foundPs != null) {
8299                    nonMutatedPs = new PackageSetting(foundPs);
8300                }
8301            }
8302
8303            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8304                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8305                if (foundPs != null) {
8306                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8307                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8308                }
8309            }
8310
8311            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8312            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8313                PackageManagerService.reportSettingsProblem(Log.WARN,
8314                        "Package " + pkg.packageName + " shared user changed from "
8315                                + (pkgSetting.sharedUser != null
8316                                        ? pkgSetting.sharedUser.name : "<nothing>")
8317                                + " to "
8318                                + (suid != null ? suid.name : "<nothing>")
8319                                + "; replacing with new");
8320                pkgSetting = null;
8321            }
8322            final PackageSetting oldPkgSetting =
8323                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8324            final PackageSetting disabledPkgSetting =
8325                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8326            if (pkgSetting == null) {
8327                final String parentPackageName = (pkg.parentPackage != null)
8328                        ? pkg.parentPackage.packageName : null;
8329                // REMOVE SharedUserSetting from method; update in a separate call
8330                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8331                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8332                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8333                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8334                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8335                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8336                        UserManagerService.getInstance());
8337                // SIDE EFFECTS; updates system state; move elsewhere
8338                if (origPackage != null) {
8339                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8340                }
8341                mSettings.addUserToSettingLPw(pkgSetting);
8342            } else {
8343                // REMOVE SharedUserSetting from method; update in a separate call.
8344                //
8345                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8346                // secondaryCpuAbi are not known at this point so we always update them
8347                // to null here, only to reset them at a later point.
8348                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8349                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8350                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8351                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8352                        UserManagerService.getInstance());
8353            }
8354            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8355            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8356
8357            // SIDE EFFECTS; modifies system state; move elsewhere
8358            if (pkgSetting.origPackage != null) {
8359                // If we are first transitioning from an original package,
8360                // fix up the new package's name now.  We need to do this after
8361                // looking up the package under its new name, so getPackageLP
8362                // can take care of fiddling things correctly.
8363                pkg.setPackageName(origPackage.name);
8364
8365                // File a report about this.
8366                String msg = "New package " + pkgSetting.realName
8367                        + " renamed to replace old package " + pkgSetting.name;
8368                reportSettingsProblem(Log.WARN, msg);
8369
8370                // Make a note of it.
8371                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8372                    mTransferedPackages.add(origPackage.name);
8373                }
8374
8375                // No longer need to retain this.
8376                pkgSetting.origPackage = null;
8377            }
8378
8379            // SIDE EFFECTS; modifies system state; move elsewhere
8380            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8381                // Make a note of it.
8382                mTransferedPackages.add(pkg.packageName);
8383            }
8384
8385            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8386                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8387            }
8388
8389            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8390                // Check all shared libraries and map to their actual file path.
8391                // We only do this here for apps not on a system dir, because those
8392                // are the only ones that can fail an install due to this.  We
8393                // will take care of the system apps by updating all of their
8394                // library paths after the scan is done.
8395                updateSharedLibrariesLPr(pkg, null);
8396            }
8397
8398            if (mFoundPolicyFile) {
8399                SELinuxMMAC.assignSeinfoValue(pkg);
8400            }
8401
8402            pkg.applicationInfo.uid = pkgSetting.appId;
8403            pkg.mExtras = pkgSetting;
8404            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8405                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8406                    // We just determined the app is signed correctly, so bring
8407                    // over the latest parsed certs.
8408                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8409                } else {
8410                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8411                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8412                                "Package " + pkg.packageName + " upgrade keys do not match the "
8413                                + "previously installed version");
8414                    } else {
8415                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8416                        String msg = "System package " + pkg.packageName
8417                                + " signature changed; retaining data.";
8418                        reportSettingsProblem(Log.WARN, msg);
8419                    }
8420                }
8421            } else {
8422                try {
8423                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8424                    verifySignaturesLP(pkgSetting, pkg);
8425                    // We just determined the app is signed correctly, so bring
8426                    // over the latest parsed certs.
8427                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8428                } catch (PackageManagerException e) {
8429                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8430                        throw e;
8431                    }
8432                    // The signature has changed, but this package is in the system
8433                    // image...  let's recover!
8434                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8435                    // However...  if this package is part of a shared user, but it
8436                    // doesn't match the signature of the shared user, let's fail.
8437                    // What this means is that you can't change the signatures
8438                    // associated with an overall shared user, which doesn't seem all
8439                    // that unreasonable.
8440                    if (pkgSetting.sharedUser != null) {
8441                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8442                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8443                            throw new PackageManagerException(
8444                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8445                                    "Signature mismatch for shared user: "
8446                                            + pkgSetting.sharedUser);
8447                        }
8448                    }
8449                    // File a report about this.
8450                    String msg = "System package " + pkg.packageName
8451                            + " signature changed; retaining data.";
8452                    reportSettingsProblem(Log.WARN, msg);
8453                }
8454            }
8455
8456            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8457                // This package wants to adopt ownership of permissions from
8458                // another package.
8459                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8460                    final String origName = pkg.mAdoptPermissions.get(i);
8461                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8462                    if (orig != null) {
8463                        if (verifyPackageUpdateLPr(orig, pkg)) {
8464                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8465                                    + pkg.packageName);
8466                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8467                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8468                        }
8469                    }
8470                }
8471            }
8472        }
8473
8474        pkg.applicationInfo.processName = fixProcessName(
8475                pkg.applicationInfo.packageName,
8476                pkg.applicationInfo.processName);
8477
8478        if (pkg != mPlatformPackage) {
8479            // Get all of our default paths setup
8480            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8481        }
8482
8483        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8484
8485        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8486            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8487                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8488                derivePackageAbi(
8489                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8490                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8491
8492                // Some system apps still use directory structure for native libraries
8493                // in which case we might end up not detecting abi solely based on apk
8494                // structure. Try to detect abi based on directory structure.
8495                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8496                        pkg.applicationInfo.primaryCpuAbi == null) {
8497                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8498                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8499                }
8500            } else {
8501                // This is not a first boot or an upgrade, don't bother deriving the
8502                // ABI during the scan. Instead, trust the value that was stored in the
8503                // package setting.
8504                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8505                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8506
8507                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8508
8509                if (DEBUG_ABI_SELECTION) {
8510                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8511                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8512                        pkg.applicationInfo.secondaryCpuAbi);
8513                }
8514            }
8515        } else {
8516            if ((scanFlags & SCAN_MOVE) != 0) {
8517                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8518                // but we already have this packages package info in the PackageSetting. We just
8519                // use that and derive the native library path based on the new codepath.
8520                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8521                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8522            }
8523
8524            // Set native library paths again. For moves, the path will be updated based on the
8525            // ABIs we've determined above. For non-moves, the path will be updated based on the
8526            // ABIs we determined during compilation, but the path will depend on the final
8527            // package path (after the rename away from the stage path).
8528            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8529        }
8530
8531        // This is a special case for the "system" package, where the ABI is
8532        // dictated by the zygote configuration (and init.rc). We should keep track
8533        // of this ABI so that we can deal with "normal" applications that run under
8534        // the same UID correctly.
8535        if (mPlatformPackage == pkg) {
8536            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8537                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8538        }
8539
8540        // If there's a mismatch between the abi-override in the package setting
8541        // and the abiOverride specified for the install. Warn about this because we
8542        // would've already compiled the app without taking the package setting into
8543        // account.
8544        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8545            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8546                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8547                        " for package " + pkg.packageName);
8548            }
8549        }
8550
8551        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8552        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8553        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8554
8555        // Copy the derived override back to the parsed package, so that we can
8556        // update the package settings accordingly.
8557        pkg.cpuAbiOverride = cpuAbiOverride;
8558
8559        if (DEBUG_ABI_SELECTION) {
8560            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8561                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8562                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8563        }
8564
8565        // Push the derived path down into PackageSettings so we know what to
8566        // clean up at uninstall time.
8567        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8568
8569        if (DEBUG_ABI_SELECTION) {
8570            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8571                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8572                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8573        }
8574
8575        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8576        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8577            // We don't do this here during boot because we can do it all
8578            // at once after scanning all existing packages.
8579            //
8580            // We also do this *before* we perform dexopt on this package, so that
8581            // we can avoid redundant dexopts, and also to make sure we've got the
8582            // code and package path correct.
8583            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8584        }
8585
8586        if (mFactoryTest && pkg.requestedPermissions.contains(
8587                android.Manifest.permission.FACTORY_TEST)) {
8588            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8589        }
8590
8591        if (isSystemApp(pkg)) {
8592            pkgSetting.isOrphaned = true;
8593        }
8594
8595        // Take care of first install / last update times.
8596        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8597        if (currentTime != 0) {
8598            if (pkgSetting.firstInstallTime == 0) {
8599                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8600            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8601                pkgSetting.lastUpdateTime = currentTime;
8602            }
8603        } else if (pkgSetting.firstInstallTime == 0) {
8604            // We need *something*.  Take time time stamp of the file.
8605            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8606        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8607            if (scanFileTime != pkgSetting.timeStamp) {
8608                // A package on the system image has changed; consider this
8609                // to be an update.
8610                pkgSetting.lastUpdateTime = scanFileTime;
8611            }
8612        }
8613        pkgSetting.setTimeStamp(scanFileTime);
8614
8615        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8616            if (nonMutatedPs != null) {
8617                synchronized (mPackages) {
8618                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8619                }
8620            }
8621        } else {
8622            // Modify state for the given package setting
8623            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8624                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8625        }
8626        return pkg;
8627    }
8628
8629    /**
8630     * Applies policy to the parsed package based upon the given policy flags.
8631     * Ensures the package is in a good state.
8632     * <p>
8633     * Implementation detail: This method must NOT have any side effect. It would
8634     * ideally be static, but, it requires locks to read system state.
8635     */
8636    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8637        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8638            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8639            if (pkg.applicationInfo.isDirectBootAware()) {
8640                // we're direct boot aware; set for all components
8641                for (PackageParser.Service s : pkg.services) {
8642                    s.info.encryptionAware = s.info.directBootAware = true;
8643                }
8644                for (PackageParser.Provider p : pkg.providers) {
8645                    p.info.encryptionAware = p.info.directBootAware = true;
8646                }
8647                for (PackageParser.Activity a : pkg.activities) {
8648                    a.info.encryptionAware = a.info.directBootAware = true;
8649                }
8650                for (PackageParser.Activity r : pkg.receivers) {
8651                    r.info.encryptionAware = r.info.directBootAware = true;
8652                }
8653            }
8654        } else {
8655            // Only allow system apps to be flagged as core apps.
8656            pkg.coreApp = false;
8657            // clear flags not applicable to regular apps
8658            pkg.applicationInfo.privateFlags &=
8659                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8660            pkg.applicationInfo.privateFlags &=
8661                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8662        }
8663        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8664
8665        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8666            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8667        }
8668
8669        if (!isSystemApp(pkg)) {
8670            // Only system apps can use these features.
8671            pkg.mOriginalPackages = null;
8672            pkg.mRealPackage = null;
8673            pkg.mAdoptPermissions = null;
8674        }
8675    }
8676
8677    /**
8678     * Asserts the parsed package is valid according to teh given policy. If the
8679     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8680     * <p>
8681     * Implementation detail: This method must NOT have any side effects. It would
8682     * ideally be static, but, it requires locks to read system state.
8683     *
8684     * @throws PackageManagerException If the package fails any of the validation checks
8685     */
8686    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8687            throws PackageManagerException {
8688        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8689            assertCodePolicy(pkg);
8690        }
8691
8692        if (pkg.applicationInfo.getCodePath() == null ||
8693                pkg.applicationInfo.getResourcePath() == null) {
8694            // Bail out. The resource and code paths haven't been set.
8695            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8696                    "Code and resource paths haven't been set correctly");
8697        }
8698
8699        // Make sure we're not adding any bogus keyset info
8700        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8701        ksms.assertScannedPackageValid(pkg);
8702
8703        synchronized (mPackages) {
8704            // The special "android" package can only be defined once
8705            if (pkg.packageName.equals("android")) {
8706                if (mAndroidApplication != null) {
8707                    Slog.w(TAG, "*************************************************");
8708                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8709                    Slog.w(TAG, " codePath=" + pkg.codePath);
8710                    Slog.w(TAG, "*************************************************");
8711                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8712                            "Core android package being redefined.  Skipping.");
8713                }
8714            }
8715
8716            // A package name must be unique; don't allow duplicates
8717            if (mPackages.containsKey(pkg.packageName)
8718                    || mSharedLibraries.containsKey(pkg.packageName)) {
8719                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8720                        "Application package " + pkg.packageName
8721                        + " already installed.  Skipping duplicate.");
8722            }
8723
8724            // Only privileged apps and updated privileged apps can add child packages.
8725            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8726                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8727                    throw new PackageManagerException("Only privileged apps can add child "
8728                            + "packages. Ignoring package " + pkg.packageName);
8729                }
8730                final int childCount = pkg.childPackages.size();
8731                for (int i = 0; i < childCount; i++) {
8732                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8733                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8734                            childPkg.packageName)) {
8735                        throw new PackageManagerException("Can't override child of "
8736                                + "another disabled app. Ignoring package " + pkg.packageName);
8737                    }
8738                }
8739            }
8740
8741            // If we're only installing presumed-existing packages, require that the
8742            // scanned APK is both already known and at the path previously established
8743            // for it.  Previously unknown packages we pick up normally, but if we have an
8744            // a priori expectation about this package's install presence, enforce it.
8745            // With a singular exception for new system packages. When an OTA contains
8746            // a new system package, we allow the codepath to change from a system location
8747            // to the user-installed location. If we don't allow this change, any newer,
8748            // user-installed version of the application will be ignored.
8749            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8750                if (mExpectingBetter.containsKey(pkg.packageName)) {
8751                    logCriticalInfo(Log.WARN,
8752                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8753                } else {
8754                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8755                    if (known != null) {
8756                        if (DEBUG_PACKAGE_SCANNING) {
8757                            Log.d(TAG, "Examining " + pkg.codePath
8758                                    + " and requiring known paths " + known.codePathString
8759                                    + " & " + known.resourcePathString);
8760                        }
8761                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8762                                || !pkg.applicationInfo.getResourcePath().equals(
8763                                        known.resourcePathString)) {
8764                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8765                                    "Application package " + pkg.packageName
8766                                    + " found at " + pkg.applicationInfo.getCodePath()
8767                                    + " but expected at " + known.codePathString
8768                                    + "; ignoring.");
8769                        }
8770                    }
8771                }
8772            }
8773
8774            // Verify that this new package doesn't have any content providers
8775            // that conflict with existing packages.  Only do this if the
8776            // package isn't already installed, since we don't want to break
8777            // things that are installed.
8778            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8779                final int N = pkg.providers.size();
8780                int i;
8781                for (i=0; i<N; i++) {
8782                    PackageParser.Provider p = pkg.providers.get(i);
8783                    if (p.info.authority != null) {
8784                        String names[] = p.info.authority.split(";");
8785                        for (int j = 0; j < names.length; j++) {
8786                            if (mProvidersByAuthority.containsKey(names[j])) {
8787                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8788                                final String otherPackageName =
8789                                        ((other != null && other.getComponentName() != null) ?
8790                                                other.getComponentName().getPackageName() : "?");
8791                                throw new PackageManagerException(
8792                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8793                                        "Can't install because provider name " + names[j]
8794                                                + " (in package " + pkg.applicationInfo.packageName
8795                                                + ") is already used by " + otherPackageName);
8796                            }
8797                        }
8798                    }
8799                }
8800            }
8801        }
8802    }
8803
8804    /**
8805     * Adds a scanned package to the system. When this method is finished, the package will
8806     * be available for query, resolution, etc...
8807     */
8808    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8809            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8810        final String pkgName = pkg.packageName;
8811        if (mCustomResolverComponentName != null &&
8812                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8813            setUpCustomResolverActivity(pkg);
8814        }
8815
8816        if (pkg.packageName.equals("android")) {
8817            synchronized (mPackages) {
8818                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8819                    // Set up information for our fall-back user intent resolution activity.
8820                    mPlatformPackage = pkg;
8821                    pkg.mVersionCode = mSdkVersion;
8822                    mAndroidApplication = pkg.applicationInfo;
8823
8824                    if (!mResolverReplaced) {
8825                        mResolveActivity.applicationInfo = mAndroidApplication;
8826                        mResolveActivity.name = ResolverActivity.class.getName();
8827                        mResolveActivity.packageName = mAndroidApplication.packageName;
8828                        mResolveActivity.processName = "system:ui";
8829                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8830                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8831                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8832                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8833                        mResolveActivity.exported = true;
8834                        mResolveActivity.enabled = true;
8835                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8836                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8837                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8838                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8839                                | ActivityInfo.CONFIG_ORIENTATION
8840                                | ActivityInfo.CONFIG_KEYBOARD
8841                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8842                        mResolveInfo.activityInfo = mResolveActivity;
8843                        mResolveInfo.priority = 0;
8844                        mResolveInfo.preferredOrder = 0;
8845                        mResolveInfo.match = 0;
8846                        mResolveComponentName = new ComponentName(
8847                                mAndroidApplication.packageName, mResolveActivity.name);
8848                    }
8849                }
8850            }
8851        }
8852
8853        ArrayList<PackageParser.Package> clientLibPkgs = null;
8854        // writer
8855        synchronized (mPackages) {
8856            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8857                // Only system apps can add new shared libraries.
8858                if (pkg.libraryNames != null) {
8859                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8860                        String name = pkg.libraryNames.get(i);
8861                        boolean allowed = false;
8862                        if (pkg.isUpdatedSystemApp()) {
8863                            // New library entries can only be added through the
8864                            // system image.  This is important to get rid of a lot
8865                            // of nasty edge cases: for example if we allowed a non-
8866                            // system update of the app to add a library, then uninstalling
8867                            // the update would make the library go away, and assumptions
8868                            // we made such as through app install filtering would now
8869                            // have allowed apps on the device which aren't compatible
8870                            // with it.  Better to just have the restriction here, be
8871                            // conservative, and create many fewer cases that can negatively
8872                            // impact the user experience.
8873                            final PackageSetting sysPs = mSettings
8874                                    .getDisabledSystemPkgLPr(pkg.packageName);
8875                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8876                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8877                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8878                                        allowed = true;
8879                                        break;
8880                                    }
8881                                }
8882                            }
8883                        } else {
8884                            allowed = true;
8885                        }
8886                        if (allowed) {
8887                            if (!mSharedLibraries.containsKey(name)) {
8888                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8889                            } else if (!name.equals(pkg.packageName)) {
8890                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8891                                        + name + " already exists; skipping");
8892                            }
8893                        } else {
8894                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8895                                    + name + " that is not declared on system image; skipping");
8896                        }
8897                    }
8898                    if ((scanFlags & SCAN_BOOTING) == 0) {
8899                        // If we are not booting, we need to update any applications
8900                        // that are clients of our shared library.  If we are booting,
8901                        // this will all be done once the scan is complete.
8902                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8903                    }
8904                }
8905            }
8906        }
8907
8908        if ((scanFlags & SCAN_BOOTING) != 0) {
8909            // No apps can run during boot scan, so they don't need to be frozen
8910        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8911            // Caller asked to not kill app, so it's probably not frozen
8912        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8913            // Caller asked us to ignore frozen check for some reason; they
8914            // probably didn't know the package name
8915        } else {
8916            // We're doing major surgery on this package, so it better be frozen
8917            // right now to keep it from launching
8918            checkPackageFrozen(pkgName);
8919        }
8920
8921        // Also need to kill any apps that are dependent on the library.
8922        if (clientLibPkgs != null) {
8923            for (int i=0; i<clientLibPkgs.size(); i++) {
8924                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8925                killApplication(clientPkg.applicationInfo.packageName,
8926                        clientPkg.applicationInfo.uid, "update lib");
8927            }
8928        }
8929
8930        // writer
8931        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8932
8933        boolean createIdmapFailed = false;
8934        synchronized (mPackages) {
8935            // We don't expect installation to fail beyond this point
8936
8937            if (pkgSetting.pkg != null) {
8938                // Note that |user| might be null during the initial boot scan. If a codePath
8939                // for an app has changed during a boot scan, it's due to an app update that's
8940                // part of the system partition and marker changes must be applied to all users.
8941                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
8942                final int[] userIds = resolveUserIds(userId);
8943                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
8944            }
8945
8946            // Add the new setting to mSettings
8947            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8948            // Add the new setting to mPackages
8949            mPackages.put(pkg.applicationInfo.packageName, pkg);
8950            // Make sure we don't accidentally delete its data.
8951            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8952            while (iter.hasNext()) {
8953                PackageCleanItem item = iter.next();
8954                if (pkgName.equals(item.packageName)) {
8955                    iter.remove();
8956                }
8957            }
8958
8959            // Add the package's KeySets to the global KeySetManagerService
8960            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8961            ksms.addScannedPackageLPw(pkg);
8962
8963            int N = pkg.providers.size();
8964            StringBuilder r = null;
8965            int i;
8966            for (i=0; i<N; i++) {
8967                PackageParser.Provider p = pkg.providers.get(i);
8968                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8969                        p.info.processName);
8970                mProviders.addProvider(p);
8971                p.syncable = p.info.isSyncable;
8972                if (p.info.authority != null) {
8973                    String names[] = p.info.authority.split(";");
8974                    p.info.authority = null;
8975                    for (int j = 0; j < names.length; j++) {
8976                        if (j == 1 && p.syncable) {
8977                            // We only want the first authority for a provider to possibly be
8978                            // syncable, so if we already added this provider using a different
8979                            // authority clear the syncable flag. We copy the provider before
8980                            // changing it because the mProviders object contains a reference
8981                            // to a provider that we don't want to change.
8982                            // Only do this for the second authority since the resulting provider
8983                            // object can be the same for all future authorities for this provider.
8984                            p = new PackageParser.Provider(p);
8985                            p.syncable = false;
8986                        }
8987                        if (!mProvidersByAuthority.containsKey(names[j])) {
8988                            mProvidersByAuthority.put(names[j], p);
8989                            if (p.info.authority == null) {
8990                                p.info.authority = names[j];
8991                            } else {
8992                                p.info.authority = p.info.authority + ";" + names[j];
8993                            }
8994                            if (DEBUG_PACKAGE_SCANNING) {
8995                                if (chatty)
8996                                    Log.d(TAG, "Registered content provider: " + names[j]
8997                                            + ", className = " + p.info.name + ", isSyncable = "
8998                                            + p.info.isSyncable);
8999                            }
9000                        } else {
9001                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9002                            Slog.w(TAG, "Skipping provider name " + names[j] +
9003                                    " (in package " + pkg.applicationInfo.packageName +
9004                                    "): name already used by "
9005                                    + ((other != null && other.getComponentName() != null)
9006                                            ? other.getComponentName().getPackageName() : "?"));
9007                        }
9008                    }
9009                }
9010                if (chatty) {
9011                    if (r == null) {
9012                        r = new StringBuilder(256);
9013                    } else {
9014                        r.append(' ');
9015                    }
9016                    r.append(p.info.name);
9017                }
9018            }
9019            if (r != null) {
9020                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9021            }
9022
9023            N = pkg.services.size();
9024            r = null;
9025            for (i=0; i<N; i++) {
9026                PackageParser.Service s = pkg.services.get(i);
9027                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9028                        s.info.processName);
9029                mServices.addService(s);
9030                if (chatty) {
9031                    if (r == null) {
9032                        r = new StringBuilder(256);
9033                    } else {
9034                        r.append(' ');
9035                    }
9036                    r.append(s.info.name);
9037                }
9038            }
9039            if (r != null) {
9040                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9041            }
9042
9043            N = pkg.receivers.size();
9044            r = null;
9045            for (i=0; i<N; i++) {
9046                PackageParser.Activity a = pkg.receivers.get(i);
9047                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9048                        a.info.processName);
9049                mReceivers.addActivity(a, "receiver");
9050                if (chatty) {
9051                    if (r == null) {
9052                        r = new StringBuilder(256);
9053                    } else {
9054                        r.append(' ');
9055                    }
9056                    r.append(a.info.name);
9057                }
9058            }
9059            if (r != null) {
9060                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9061            }
9062
9063            N = pkg.activities.size();
9064            r = null;
9065            for (i=0; i<N; i++) {
9066                PackageParser.Activity a = pkg.activities.get(i);
9067                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9068                        a.info.processName);
9069                mActivities.addActivity(a, "activity");
9070                if (chatty) {
9071                    if (r == null) {
9072                        r = new StringBuilder(256);
9073                    } else {
9074                        r.append(' ');
9075                    }
9076                    r.append(a.info.name);
9077                }
9078            }
9079            if (r != null) {
9080                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9081            }
9082
9083            N = pkg.permissionGroups.size();
9084            r = null;
9085            for (i=0; i<N; i++) {
9086                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9087                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9088                final String curPackageName = cur == null ? null : cur.info.packageName;
9089                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9090                if (cur == null || isPackageUpdate) {
9091                    mPermissionGroups.put(pg.info.name, pg);
9092                    if (chatty) {
9093                        if (r == null) {
9094                            r = new StringBuilder(256);
9095                        } else {
9096                            r.append(' ');
9097                        }
9098                        if (isPackageUpdate) {
9099                            r.append("UPD:");
9100                        }
9101                        r.append(pg.info.name);
9102                    }
9103                } else {
9104                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9105                            + pg.info.packageName + " ignored: original from "
9106                            + cur.info.packageName);
9107                    if (chatty) {
9108                        if (r == null) {
9109                            r = new StringBuilder(256);
9110                        } else {
9111                            r.append(' ');
9112                        }
9113                        r.append("DUP:");
9114                        r.append(pg.info.name);
9115                    }
9116                }
9117            }
9118            if (r != null) {
9119                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9120            }
9121
9122            N = pkg.permissions.size();
9123            r = null;
9124            for (i=0; i<N; i++) {
9125                PackageParser.Permission p = pkg.permissions.get(i);
9126
9127                // Assume by default that we did not install this permission into the system.
9128                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9129
9130                // Now that permission groups have a special meaning, we ignore permission
9131                // groups for legacy apps to prevent unexpected behavior. In particular,
9132                // permissions for one app being granted to someone just becase they happen
9133                // to be in a group defined by another app (before this had no implications).
9134                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9135                    p.group = mPermissionGroups.get(p.info.group);
9136                    // Warn for a permission in an unknown group.
9137                    if (p.info.group != null && p.group == null) {
9138                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9139                                + p.info.packageName + " in an unknown group " + p.info.group);
9140                    }
9141                }
9142
9143                ArrayMap<String, BasePermission> permissionMap =
9144                        p.tree ? mSettings.mPermissionTrees
9145                                : mSettings.mPermissions;
9146                BasePermission bp = permissionMap.get(p.info.name);
9147
9148                // Allow system apps to redefine non-system permissions
9149                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9150                    final boolean currentOwnerIsSystem = (bp.perm != null
9151                            && isSystemApp(bp.perm.owner));
9152                    if (isSystemApp(p.owner)) {
9153                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9154                            // It's a built-in permission and no owner, take ownership now
9155                            bp.packageSetting = pkgSetting;
9156                            bp.perm = p;
9157                            bp.uid = pkg.applicationInfo.uid;
9158                            bp.sourcePackage = p.info.packageName;
9159                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9160                        } else if (!currentOwnerIsSystem) {
9161                            String msg = "New decl " + p.owner + " of permission  "
9162                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9163                            reportSettingsProblem(Log.WARN, msg);
9164                            bp = null;
9165                        }
9166                    }
9167                }
9168
9169                if (bp == null) {
9170                    bp = new BasePermission(p.info.name, p.info.packageName,
9171                            BasePermission.TYPE_NORMAL);
9172                    permissionMap.put(p.info.name, bp);
9173                }
9174
9175                if (bp.perm == null) {
9176                    if (bp.sourcePackage == null
9177                            || bp.sourcePackage.equals(p.info.packageName)) {
9178                        BasePermission tree = findPermissionTreeLP(p.info.name);
9179                        if (tree == null
9180                                || tree.sourcePackage.equals(p.info.packageName)) {
9181                            bp.packageSetting = pkgSetting;
9182                            bp.perm = p;
9183                            bp.uid = pkg.applicationInfo.uid;
9184                            bp.sourcePackage = p.info.packageName;
9185                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9186                            if (chatty) {
9187                                if (r == null) {
9188                                    r = new StringBuilder(256);
9189                                } else {
9190                                    r.append(' ');
9191                                }
9192                                r.append(p.info.name);
9193                            }
9194                        } else {
9195                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9196                                    + p.info.packageName + " ignored: base tree "
9197                                    + tree.name + " is from package "
9198                                    + tree.sourcePackage);
9199                        }
9200                    } else {
9201                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9202                                + p.info.packageName + " ignored: original from "
9203                                + bp.sourcePackage);
9204                    }
9205                } else if (chatty) {
9206                    if (r == null) {
9207                        r = new StringBuilder(256);
9208                    } else {
9209                        r.append(' ');
9210                    }
9211                    r.append("DUP:");
9212                    r.append(p.info.name);
9213                }
9214                if (bp.perm == p) {
9215                    bp.protectionLevel = p.info.protectionLevel;
9216                }
9217            }
9218
9219            if (r != null) {
9220                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9221            }
9222
9223            N = pkg.instrumentation.size();
9224            r = null;
9225            for (i=0; i<N; i++) {
9226                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9227                a.info.packageName = pkg.applicationInfo.packageName;
9228                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9229                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9230                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9231                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9232                a.info.dataDir = pkg.applicationInfo.dataDir;
9233                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9234                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9235                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9236                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9237                mInstrumentation.put(a.getComponentName(), a);
9238                if (chatty) {
9239                    if (r == null) {
9240                        r = new StringBuilder(256);
9241                    } else {
9242                        r.append(' ');
9243                    }
9244                    r.append(a.info.name);
9245                }
9246            }
9247            if (r != null) {
9248                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9249            }
9250
9251            if (pkg.protectedBroadcasts != null) {
9252                N = pkg.protectedBroadcasts.size();
9253                for (i=0; i<N; i++) {
9254                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9255                }
9256            }
9257
9258            // Create idmap files for pairs of (packages, overlay packages).
9259            // Note: "android", ie framework-res.apk, is handled by native layers.
9260            if (pkg.mOverlayTarget != null) {
9261                // This is an overlay package.
9262                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9263                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9264                        mOverlays.put(pkg.mOverlayTarget,
9265                                new ArrayMap<String, PackageParser.Package>());
9266                    }
9267                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9268                    map.put(pkg.packageName, pkg);
9269                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9270                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9271                        createIdmapFailed = true;
9272                    }
9273                }
9274            } else if (mOverlays.containsKey(pkg.packageName) &&
9275                    !pkg.packageName.equals("android")) {
9276                // This is a regular package, with one or more known overlay packages.
9277                createIdmapsForPackageLI(pkg);
9278            }
9279        }
9280
9281        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9282
9283        if (createIdmapFailed) {
9284            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9285                    "scanPackageLI failed to createIdmap");
9286        }
9287    }
9288
9289    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9290            PackageParser.Package update, int[] userIds) {
9291        if (existing.applicationInfo == null || update.applicationInfo == null) {
9292            // This isn't due to an app installation.
9293            return;
9294        }
9295
9296        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9297        final File newCodePath = new File(update.applicationInfo.getCodePath());
9298
9299        // The codePath hasn't changed, so there's nothing for us to do.
9300        if (Objects.equals(oldCodePath, newCodePath)) {
9301            return;
9302        }
9303
9304        File canonicalNewCodePath;
9305        try {
9306            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9307        } catch (IOException e) {
9308            Slog.w(TAG, "Failed to get canonical path.", e);
9309            return;
9310        }
9311
9312        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9313        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9314        // that the last component of the path (i.e, the name) doesn't need canonicalization
9315        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9316        // but may change in the future. Hopefully this function won't exist at that point.
9317        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9318                oldCodePath.getName());
9319
9320        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9321        // with "@".
9322        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9323        if (!oldMarkerPrefix.endsWith("@")) {
9324            oldMarkerPrefix += "@";
9325        }
9326        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9327        if (!newMarkerPrefix.endsWith("@")) {
9328            newMarkerPrefix += "@";
9329        }
9330
9331        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9332        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9333        for (String updatedPath : updatedPaths) {
9334            String updatedPathName = new File(updatedPath).getName();
9335            markerSuffixes.add(updatedPathName.replace('/', '@'));
9336        }
9337
9338        for (int userId : userIds) {
9339            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9340
9341            for (String markerSuffix : markerSuffixes) {
9342                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9343                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9344                if (oldForeignUseMark.exists()) {
9345                    try {
9346                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9347                                newForeignUseMark.getAbsolutePath());
9348                    } catch (ErrnoException e) {
9349                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9350                        oldForeignUseMark.delete();
9351                    }
9352                }
9353            }
9354        }
9355    }
9356
9357    /**
9358     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9359     * is derived purely on the basis of the contents of {@code scanFile} and
9360     * {@code cpuAbiOverride}.
9361     *
9362     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9363     */
9364    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9365                                 String cpuAbiOverride, boolean extractLibs,
9366                                 File appLib32InstallDir)
9367            throws PackageManagerException {
9368        // Give ourselves some initial paths; we'll come back for another
9369        // pass once we've determined ABI below.
9370        setNativeLibraryPaths(pkg, appLib32InstallDir);
9371
9372        // We would never need to extract libs for forward-locked and external packages,
9373        // since the container service will do it for us. We shouldn't attempt to
9374        // extract libs from system app when it was not updated.
9375        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9376                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9377            extractLibs = false;
9378        }
9379
9380        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9381        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9382
9383        NativeLibraryHelper.Handle handle = null;
9384        try {
9385            handle = NativeLibraryHelper.Handle.create(pkg);
9386            // TODO(multiArch): This can be null for apps that didn't go through the
9387            // usual installation process. We can calculate it again, like we
9388            // do during install time.
9389            //
9390            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9391            // unnecessary.
9392            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9393
9394            // Null out the abis so that they can be recalculated.
9395            pkg.applicationInfo.primaryCpuAbi = null;
9396            pkg.applicationInfo.secondaryCpuAbi = null;
9397            if (isMultiArch(pkg.applicationInfo)) {
9398                // Warn if we've set an abiOverride for multi-lib packages..
9399                // By definition, we need to copy both 32 and 64 bit libraries for
9400                // such packages.
9401                if (pkg.cpuAbiOverride != null
9402                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9403                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9404                }
9405
9406                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9407                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9408                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9409                    if (extractLibs) {
9410                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9411                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9412                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9413                                useIsaSpecificSubdirs);
9414                    } else {
9415                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9416                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9417                    }
9418                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9419                }
9420
9421                maybeThrowExceptionForMultiArchCopy(
9422                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9423
9424                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9425                    if (extractLibs) {
9426                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9427                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9428                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9429                                useIsaSpecificSubdirs);
9430                    } else {
9431                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9432                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9433                    }
9434                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9435                }
9436
9437                maybeThrowExceptionForMultiArchCopy(
9438                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9439
9440                if (abi64 >= 0) {
9441                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9442                }
9443
9444                if (abi32 >= 0) {
9445                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9446                    if (abi64 >= 0) {
9447                        if (pkg.use32bitAbi) {
9448                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9449                            pkg.applicationInfo.primaryCpuAbi = abi;
9450                        } else {
9451                            pkg.applicationInfo.secondaryCpuAbi = abi;
9452                        }
9453                    } else {
9454                        pkg.applicationInfo.primaryCpuAbi = abi;
9455                    }
9456                }
9457
9458            } else {
9459                String[] abiList = (cpuAbiOverride != null) ?
9460                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9461
9462                // Enable gross and lame hacks for apps that are built with old
9463                // SDK tools. We must scan their APKs for renderscript bitcode and
9464                // not launch them if it's present. Don't bother checking on devices
9465                // that don't have 64 bit support.
9466                boolean needsRenderScriptOverride = false;
9467                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9468                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9469                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9470                    needsRenderScriptOverride = true;
9471                }
9472
9473                final int copyRet;
9474                if (extractLibs) {
9475                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9476                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9477                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9478                } else {
9479                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9480                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9481                }
9482                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9483
9484                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9485                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9486                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9487                }
9488
9489                if (copyRet >= 0) {
9490                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9491                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9492                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9493                } else if (needsRenderScriptOverride) {
9494                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9495                }
9496            }
9497        } catch (IOException ioe) {
9498            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9499        } finally {
9500            IoUtils.closeQuietly(handle);
9501        }
9502
9503        // Now that we've calculated the ABIs and determined if it's an internal app,
9504        // we will go ahead and populate the nativeLibraryPath.
9505        setNativeLibraryPaths(pkg, appLib32InstallDir);
9506    }
9507
9508    /**
9509     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9510     * i.e, so that all packages can be run inside a single process if required.
9511     *
9512     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9513     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9514     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9515     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9516     * updating a package that belongs to a shared user.
9517     *
9518     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9519     * adds unnecessary complexity.
9520     */
9521    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9522            PackageParser.Package scannedPackage) {
9523        String requiredInstructionSet = null;
9524        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9525            requiredInstructionSet = VMRuntime.getInstructionSet(
9526                     scannedPackage.applicationInfo.primaryCpuAbi);
9527        }
9528
9529        PackageSetting requirer = null;
9530        for (PackageSetting ps : packagesForUser) {
9531            // If packagesForUser contains scannedPackage, we skip it. This will happen
9532            // when scannedPackage is an update of an existing package. Without this check,
9533            // we will never be able to change the ABI of any package belonging to a shared
9534            // user, even if it's compatible with other packages.
9535            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9536                if (ps.primaryCpuAbiString == null) {
9537                    continue;
9538                }
9539
9540                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9541                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9542                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9543                    // this but there's not much we can do.
9544                    String errorMessage = "Instruction set mismatch, "
9545                            + ((requirer == null) ? "[caller]" : requirer)
9546                            + " requires " + requiredInstructionSet + " whereas " + ps
9547                            + " requires " + instructionSet;
9548                    Slog.w(TAG, errorMessage);
9549                }
9550
9551                if (requiredInstructionSet == null) {
9552                    requiredInstructionSet = instructionSet;
9553                    requirer = ps;
9554                }
9555            }
9556        }
9557
9558        if (requiredInstructionSet != null) {
9559            String adjustedAbi;
9560            if (requirer != null) {
9561                // requirer != null implies that either scannedPackage was null or that scannedPackage
9562                // did not require an ABI, in which case we have to adjust scannedPackage to match
9563                // the ABI of the set (which is the same as requirer's ABI)
9564                adjustedAbi = requirer.primaryCpuAbiString;
9565                if (scannedPackage != null) {
9566                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9567                }
9568            } else {
9569                // requirer == null implies that we're updating all ABIs in the set to
9570                // match scannedPackage.
9571                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9572            }
9573
9574            for (PackageSetting ps : packagesForUser) {
9575                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9576                    if (ps.primaryCpuAbiString != null) {
9577                        continue;
9578                    }
9579
9580                    ps.primaryCpuAbiString = adjustedAbi;
9581                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9582                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9583                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9584                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9585                                + " (requirer="
9586                                + (requirer == null ? "null" : requirer.pkg.packageName)
9587                                + ", scannedPackage="
9588                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9589                                + ")");
9590                        try {
9591                            mInstaller.rmdex(ps.codePathString,
9592                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9593                        } catch (InstallerException ignored) {
9594                        }
9595                    }
9596                }
9597            }
9598        }
9599    }
9600
9601    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9602        synchronized (mPackages) {
9603            mResolverReplaced = true;
9604            // Set up information for custom user intent resolution activity.
9605            mResolveActivity.applicationInfo = pkg.applicationInfo;
9606            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9607            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9608            mResolveActivity.processName = pkg.applicationInfo.packageName;
9609            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9610            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9611                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9612            mResolveActivity.theme = 0;
9613            mResolveActivity.exported = true;
9614            mResolveActivity.enabled = true;
9615            mResolveInfo.activityInfo = mResolveActivity;
9616            mResolveInfo.priority = 0;
9617            mResolveInfo.preferredOrder = 0;
9618            mResolveInfo.match = 0;
9619            mResolveComponentName = mCustomResolverComponentName;
9620            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9621                    mResolveComponentName);
9622        }
9623    }
9624
9625    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9626        if (installerComponent == null) {
9627            if (DEBUG_EPHEMERAL) {
9628                Slog.d(TAG, "Clear ephemeral installer activity");
9629            }
9630            mEphemeralInstallerActivity.applicationInfo = null;
9631            return;
9632        }
9633
9634        if (DEBUG_EPHEMERAL) {
9635            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9636        }
9637        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9638        // Set up information for ephemeral installer activity
9639        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9640        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9641        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9642        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9643        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9644        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9645                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9646        mEphemeralInstallerActivity.theme = 0;
9647        mEphemeralInstallerActivity.exported = true;
9648        mEphemeralInstallerActivity.enabled = true;
9649        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9650        mEphemeralInstallerInfo.priority = 0;
9651        mEphemeralInstallerInfo.preferredOrder = 1;
9652        mEphemeralInstallerInfo.isDefault = true;
9653        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9654                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9655    }
9656
9657    private static String calculateBundledApkRoot(final String codePathString) {
9658        final File codePath = new File(codePathString);
9659        final File codeRoot;
9660        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9661            codeRoot = Environment.getRootDirectory();
9662        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9663            codeRoot = Environment.getOemDirectory();
9664        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9665            codeRoot = Environment.getVendorDirectory();
9666        } else {
9667            // Unrecognized code path; take its top real segment as the apk root:
9668            // e.g. /something/app/blah.apk => /something
9669            try {
9670                File f = codePath.getCanonicalFile();
9671                File parent = f.getParentFile();    // non-null because codePath is a file
9672                File tmp;
9673                while ((tmp = parent.getParentFile()) != null) {
9674                    f = parent;
9675                    parent = tmp;
9676                }
9677                codeRoot = f;
9678                Slog.w(TAG, "Unrecognized code path "
9679                        + codePath + " - using " + codeRoot);
9680            } catch (IOException e) {
9681                // Can't canonicalize the code path -- shenanigans?
9682                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9683                return Environment.getRootDirectory().getPath();
9684            }
9685        }
9686        return codeRoot.getPath();
9687    }
9688
9689    /**
9690     * Derive and set the location of native libraries for the given package,
9691     * which varies depending on where and how the package was installed.
9692     */
9693    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9694        final ApplicationInfo info = pkg.applicationInfo;
9695        final String codePath = pkg.codePath;
9696        final File codeFile = new File(codePath);
9697        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9698        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9699
9700        info.nativeLibraryRootDir = null;
9701        info.nativeLibraryRootRequiresIsa = false;
9702        info.nativeLibraryDir = null;
9703        info.secondaryNativeLibraryDir = null;
9704
9705        if (isApkFile(codeFile)) {
9706            // Monolithic install
9707            if (bundledApp) {
9708                // If "/system/lib64/apkname" exists, assume that is the per-package
9709                // native library directory to use; otherwise use "/system/lib/apkname".
9710                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9711                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9712                        getPrimaryInstructionSet(info));
9713
9714                // This is a bundled system app so choose the path based on the ABI.
9715                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9716                // is just the default path.
9717                final String apkName = deriveCodePathName(codePath);
9718                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9719                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9720                        apkName).getAbsolutePath();
9721
9722                if (info.secondaryCpuAbi != null) {
9723                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9724                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9725                            secondaryLibDir, apkName).getAbsolutePath();
9726                }
9727            } else if (asecApp) {
9728                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9729                        .getAbsolutePath();
9730            } else {
9731                final String apkName = deriveCodePathName(codePath);
9732                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9733                        .getAbsolutePath();
9734            }
9735
9736            info.nativeLibraryRootRequiresIsa = false;
9737            info.nativeLibraryDir = info.nativeLibraryRootDir;
9738        } else {
9739            // Cluster install
9740            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9741            info.nativeLibraryRootRequiresIsa = true;
9742
9743            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9744                    getPrimaryInstructionSet(info)).getAbsolutePath();
9745
9746            if (info.secondaryCpuAbi != null) {
9747                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9748                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9749            }
9750        }
9751    }
9752
9753    /**
9754     * Calculate the abis and roots for a bundled app. These can uniquely
9755     * be determined from the contents of the system partition, i.e whether
9756     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9757     * of this information, and instead assume that the system was built
9758     * sensibly.
9759     */
9760    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9761                                           PackageSetting pkgSetting) {
9762        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9763
9764        // If "/system/lib64/apkname" exists, assume that is the per-package
9765        // native library directory to use; otherwise use "/system/lib/apkname".
9766        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9767        setBundledAppAbi(pkg, apkRoot, apkName);
9768        // pkgSetting might be null during rescan following uninstall of updates
9769        // to a bundled app, so accommodate that possibility.  The settings in
9770        // that case will be established later from the parsed package.
9771        //
9772        // If the settings aren't null, sync them up with what we've just derived.
9773        // note that apkRoot isn't stored in the package settings.
9774        if (pkgSetting != null) {
9775            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9776            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9777        }
9778    }
9779
9780    /**
9781     * Deduces the ABI of a bundled app and sets the relevant fields on the
9782     * parsed pkg object.
9783     *
9784     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9785     *        under which system libraries are installed.
9786     * @param apkName the name of the installed package.
9787     */
9788    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9789        final File codeFile = new File(pkg.codePath);
9790
9791        final boolean has64BitLibs;
9792        final boolean has32BitLibs;
9793        if (isApkFile(codeFile)) {
9794            // Monolithic install
9795            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9796            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9797        } else {
9798            // Cluster install
9799            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9800            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9801                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9802                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9803                has64BitLibs = (new File(rootDir, isa)).exists();
9804            } else {
9805                has64BitLibs = false;
9806            }
9807            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9808                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9809                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9810                has32BitLibs = (new File(rootDir, isa)).exists();
9811            } else {
9812                has32BitLibs = false;
9813            }
9814        }
9815
9816        if (has64BitLibs && !has32BitLibs) {
9817            // The package has 64 bit libs, but not 32 bit libs. Its primary
9818            // ABI should be 64 bit. We can safely assume here that the bundled
9819            // native libraries correspond to the most preferred ABI in the list.
9820
9821            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9822            pkg.applicationInfo.secondaryCpuAbi = null;
9823        } else if (has32BitLibs && !has64BitLibs) {
9824            // The package has 32 bit libs but not 64 bit libs. Its primary
9825            // ABI should be 32 bit.
9826
9827            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9828            pkg.applicationInfo.secondaryCpuAbi = null;
9829        } else if (has32BitLibs && has64BitLibs) {
9830            // The application has both 64 and 32 bit bundled libraries. We check
9831            // here that the app declares multiArch support, and warn if it doesn't.
9832            //
9833            // We will be lenient here and record both ABIs. The primary will be the
9834            // ABI that's higher on the list, i.e, a device that's configured to prefer
9835            // 64 bit apps will see a 64 bit primary ABI,
9836
9837            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9838                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9839            }
9840
9841            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9842                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9843                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9844            } else {
9845                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9846                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9847            }
9848        } else {
9849            pkg.applicationInfo.primaryCpuAbi = null;
9850            pkg.applicationInfo.secondaryCpuAbi = null;
9851        }
9852    }
9853
9854    private void killApplication(String pkgName, int appId, String reason) {
9855        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9856    }
9857
9858    private void killApplication(String pkgName, int appId, int userId, String reason) {
9859        // Request the ActivityManager to kill the process(only for existing packages)
9860        // so that we do not end up in a confused state while the user is still using the older
9861        // version of the application while the new one gets installed.
9862        final long token = Binder.clearCallingIdentity();
9863        try {
9864            IActivityManager am = ActivityManager.getService();
9865            if (am != null) {
9866                try {
9867                    am.killApplication(pkgName, appId, userId, reason);
9868                } catch (RemoteException e) {
9869                }
9870            }
9871        } finally {
9872            Binder.restoreCallingIdentity(token);
9873        }
9874    }
9875
9876    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9877        // Remove the parent package setting
9878        PackageSetting ps = (PackageSetting) pkg.mExtras;
9879        if (ps != null) {
9880            removePackageLI(ps, chatty);
9881        }
9882        // Remove the child package setting
9883        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9884        for (int i = 0; i < childCount; i++) {
9885            PackageParser.Package childPkg = pkg.childPackages.get(i);
9886            ps = (PackageSetting) childPkg.mExtras;
9887            if (ps != null) {
9888                removePackageLI(ps, chatty);
9889            }
9890        }
9891    }
9892
9893    void removePackageLI(PackageSetting ps, boolean chatty) {
9894        if (DEBUG_INSTALL) {
9895            if (chatty)
9896                Log.d(TAG, "Removing package " + ps.name);
9897        }
9898
9899        // writer
9900        synchronized (mPackages) {
9901            mPackages.remove(ps.name);
9902            final PackageParser.Package pkg = ps.pkg;
9903            if (pkg != null) {
9904                cleanPackageDataStructuresLILPw(pkg, chatty);
9905            }
9906        }
9907    }
9908
9909    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9910        if (DEBUG_INSTALL) {
9911            if (chatty)
9912                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9913        }
9914
9915        // writer
9916        synchronized (mPackages) {
9917            // Remove the parent package
9918            mPackages.remove(pkg.applicationInfo.packageName);
9919            cleanPackageDataStructuresLILPw(pkg, chatty);
9920
9921            // Remove the child packages
9922            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9923            for (int i = 0; i < childCount; i++) {
9924                PackageParser.Package childPkg = pkg.childPackages.get(i);
9925                mPackages.remove(childPkg.applicationInfo.packageName);
9926                cleanPackageDataStructuresLILPw(childPkg, chatty);
9927            }
9928        }
9929    }
9930
9931    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9932        int N = pkg.providers.size();
9933        StringBuilder r = null;
9934        int i;
9935        for (i=0; i<N; i++) {
9936            PackageParser.Provider p = pkg.providers.get(i);
9937            mProviders.removeProvider(p);
9938            if (p.info.authority == null) {
9939
9940                /* There was another ContentProvider with this authority when
9941                 * this app was installed so this authority is null,
9942                 * Ignore it as we don't have to unregister the provider.
9943                 */
9944                continue;
9945            }
9946            String names[] = p.info.authority.split(";");
9947            for (int j = 0; j < names.length; j++) {
9948                if (mProvidersByAuthority.get(names[j]) == p) {
9949                    mProvidersByAuthority.remove(names[j]);
9950                    if (DEBUG_REMOVE) {
9951                        if (chatty)
9952                            Log.d(TAG, "Unregistered content provider: " + names[j]
9953                                    + ", className = " + p.info.name + ", isSyncable = "
9954                                    + p.info.isSyncable);
9955                    }
9956                }
9957            }
9958            if (DEBUG_REMOVE && chatty) {
9959                if (r == null) {
9960                    r = new StringBuilder(256);
9961                } else {
9962                    r.append(' ');
9963                }
9964                r.append(p.info.name);
9965            }
9966        }
9967        if (r != null) {
9968            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9969        }
9970
9971        N = pkg.services.size();
9972        r = null;
9973        for (i=0; i<N; i++) {
9974            PackageParser.Service s = pkg.services.get(i);
9975            mServices.removeService(s);
9976            if (chatty) {
9977                if (r == null) {
9978                    r = new StringBuilder(256);
9979                } else {
9980                    r.append(' ');
9981                }
9982                r.append(s.info.name);
9983            }
9984        }
9985        if (r != null) {
9986            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9987        }
9988
9989        N = pkg.receivers.size();
9990        r = null;
9991        for (i=0; i<N; i++) {
9992            PackageParser.Activity a = pkg.receivers.get(i);
9993            mReceivers.removeActivity(a, "receiver");
9994            if (DEBUG_REMOVE && chatty) {
9995                if (r == null) {
9996                    r = new StringBuilder(256);
9997                } else {
9998                    r.append(' ');
9999                }
10000                r.append(a.info.name);
10001            }
10002        }
10003        if (r != null) {
10004            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10005        }
10006
10007        N = pkg.activities.size();
10008        r = null;
10009        for (i=0; i<N; i++) {
10010            PackageParser.Activity a = pkg.activities.get(i);
10011            mActivities.removeActivity(a, "activity");
10012            if (DEBUG_REMOVE && chatty) {
10013                if (r == null) {
10014                    r = new StringBuilder(256);
10015                } else {
10016                    r.append(' ');
10017                }
10018                r.append(a.info.name);
10019            }
10020        }
10021        if (r != null) {
10022            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10023        }
10024
10025        N = pkg.permissions.size();
10026        r = null;
10027        for (i=0; i<N; i++) {
10028            PackageParser.Permission p = pkg.permissions.get(i);
10029            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10030            if (bp == null) {
10031                bp = mSettings.mPermissionTrees.get(p.info.name);
10032            }
10033            if (bp != null && bp.perm == p) {
10034                bp.perm = null;
10035                if (DEBUG_REMOVE && chatty) {
10036                    if (r == null) {
10037                        r = new StringBuilder(256);
10038                    } else {
10039                        r.append(' ');
10040                    }
10041                    r.append(p.info.name);
10042                }
10043            }
10044            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10045                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10046                if (appOpPkgs != null) {
10047                    appOpPkgs.remove(pkg.packageName);
10048                }
10049            }
10050        }
10051        if (r != null) {
10052            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10053        }
10054
10055        N = pkg.requestedPermissions.size();
10056        r = null;
10057        for (i=0; i<N; i++) {
10058            String perm = pkg.requestedPermissions.get(i);
10059            BasePermission bp = mSettings.mPermissions.get(perm);
10060            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10061                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10062                if (appOpPkgs != null) {
10063                    appOpPkgs.remove(pkg.packageName);
10064                    if (appOpPkgs.isEmpty()) {
10065                        mAppOpPermissionPackages.remove(perm);
10066                    }
10067                }
10068            }
10069        }
10070        if (r != null) {
10071            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10072        }
10073
10074        N = pkg.instrumentation.size();
10075        r = null;
10076        for (i=0; i<N; i++) {
10077            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10078            mInstrumentation.remove(a.getComponentName());
10079            if (DEBUG_REMOVE && chatty) {
10080                if (r == null) {
10081                    r = new StringBuilder(256);
10082                } else {
10083                    r.append(' ');
10084                }
10085                r.append(a.info.name);
10086            }
10087        }
10088        if (r != null) {
10089            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10090        }
10091
10092        r = null;
10093        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10094            // Only system apps can hold shared libraries.
10095            if (pkg.libraryNames != null) {
10096                for (i=0; i<pkg.libraryNames.size(); i++) {
10097                    String name = pkg.libraryNames.get(i);
10098                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10099                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10100                        mSharedLibraries.remove(name);
10101                        if (DEBUG_REMOVE && chatty) {
10102                            if (r == null) {
10103                                r = new StringBuilder(256);
10104                            } else {
10105                                r.append(' ');
10106                            }
10107                            r.append(name);
10108                        }
10109                    }
10110                }
10111            }
10112        }
10113        if (r != null) {
10114            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10115        }
10116    }
10117
10118    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10119        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10120            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10121                return true;
10122            }
10123        }
10124        return false;
10125    }
10126
10127    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10128    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10129    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10130
10131    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10132        // Update the parent permissions
10133        updatePermissionsLPw(pkg.packageName, pkg, flags);
10134        // Update the child permissions
10135        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10136        for (int i = 0; i < childCount; i++) {
10137            PackageParser.Package childPkg = pkg.childPackages.get(i);
10138            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10139        }
10140    }
10141
10142    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10143            int flags) {
10144        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10145        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10146    }
10147
10148    private void updatePermissionsLPw(String changingPkg,
10149            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10150        // Make sure there are no dangling permission trees.
10151        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10152        while (it.hasNext()) {
10153            final BasePermission bp = it.next();
10154            if (bp.packageSetting == null) {
10155                // We may not yet have parsed the package, so just see if
10156                // we still know about its settings.
10157                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10158            }
10159            if (bp.packageSetting == null) {
10160                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10161                        + " from package " + bp.sourcePackage);
10162                it.remove();
10163            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10164                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10165                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10166                            + " from package " + bp.sourcePackage);
10167                    flags |= UPDATE_PERMISSIONS_ALL;
10168                    it.remove();
10169                }
10170            }
10171        }
10172
10173        // Make sure all dynamic permissions have been assigned to a package,
10174        // and make sure there are no dangling permissions.
10175        it = mSettings.mPermissions.values().iterator();
10176        while (it.hasNext()) {
10177            final BasePermission bp = it.next();
10178            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10179                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10180                        + bp.name + " pkg=" + bp.sourcePackage
10181                        + " info=" + bp.pendingInfo);
10182                if (bp.packageSetting == null && bp.pendingInfo != null) {
10183                    final BasePermission tree = findPermissionTreeLP(bp.name);
10184                    if (tree != null && tree.perm != null) {
10185                        bp.packageSetting = tree.packageSetting;
10186                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10187                                new PermissionInfo(bp.pendingInfo));
10188                        bp.perm.info.packageName = tree.perm.info.packageName;
10189                        bp.perm.info.name = bp.name;
10190                        bp.uid = tree.uid;
10191                    }
10192                }
10193            }
10194            if (bp.packageSetting == null) {
10195                // We may not yet have parsed the package, so just see if
10196                // we still know about its settings.
10197                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10198            }
10199            if (bp.packageSetting == null) {
10200                Slog.w(TAG, "Removing dangling permission: " + bp.name
10201                        + " from package " + bp.sourcePackage);
10202                it.remove();
10203            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10204                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10205                    Slog.i(TAG, "Removing old permission: " + bp.name
10206                            + " from package " + bp.sourcePackage);
10207                    flags |= UPDATE_PERMISSIONS_ALL;
10208                    it.remove();
10209                }
10210            }
10211        }
10212
10213        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10214        // Now update the permissions for all packages, in particular
10215        // replace the granted permissions of the system packages.
10216        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10217            for (PackageParser.Package pkg : mPackages.values()) {
10218                if (pkg != pkgInfo) {
10219                    // Only replace for packages on requested volume
10220                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10221                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10222                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10223                    grantPermissionsLPw(pkg, replace, changingPkg);
10224                }
10225            }
10226        }
10227
10228        if (pkgInfo != null) {
10229            // Only replace for packages on requested volume
10230            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10231            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10232                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10233            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10234        }
10235        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10236    }
10237
10238    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10239            String packageOfInterest) {
10240        // IMPORTANT: There are two types of permissions: install and runtime.
10241        // Install time permissions are granted when the app is installed to
10242        // all device users and users added in the future. Runtime permissions
10243        // are granted at runtime explicitly to specific users. Normal and signature
10244        // protected permissions are install time permissions. Dangerous permissions
10245        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10246        // otherwise they are runtime permissions. This function does not manage
10247        // runtime permissions except for the case an app targeting Lollipop MR1
10248        // being upgraded to target a newer SDK, in which case dangerous permissions
10249        // are transformed from install time to runtime ones.
10250
10251        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10252        if (ps == null) {
10253            return;
10254        }
10255
10256        PermissionsState permissionsState = ps.getPermissionsState();
10257        PermissionsState origPermissions = permissionsState;
10258
10259        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10260
10261        boolean runtimePermissionsRevoked = false;
10262        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10263
10264        boolean changedInstallPermission = false;
10265
10266        if (replace) {
10267            ps.installPermissionsFixed = false;
10268            if (!ps.isSharedUser()) {
10269                origPermissions = new PermissionsState(permissionsState);
10270                permissionsState.reset();
10271            } else {
10272                // We need to know only about runtime permission changes since the
10273                // calling code always writes the install permissions state but
10274                // the runtime ones are written only if changed. The only cases of
10275                // changed runtime permissions here are promotion of an install to
10276                // runtime and revocation of a runtime from a shared user.
10277                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10278                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10279                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10280                    runtimePermissionsRevoked = true;
10281                }
10282            }
10283        }
10284
10285        permissionsState.setGlobalGids(mGlobalGids);
10286
10287        final int N = pkg.requestedPermissions.size();
10288        for (int i=0; i<N; i++) {
10289            final String name = pkg.requestedPermissions.get(i);
10290            final BasePermission bp = mSettings.mPermissions.get(name);
10291
10292            if (DEBUG_INSTALL) {
10293                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10294            }
10295
10296            if (bp == null || bp.packageSetting == null) {
10297                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10298                    Slog.w(TAG, "Unknown permission " + name
10299                            + " in package " + pkg.packageName);
10300                }
10301                continue;
10302            }
10303
10304
10305            // Limit ephemeral apps to ephemeral allowed permissions.
10306            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10307                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10308                        + pkg.packageName);
10309                continue;
10310            }
10311
10312            final String perm = bp.name;
10313            boolean allowedSig = false;
10314            int grant = GRANT_DENIED;
10315
10316            // Keep track of app op permissions.
10317            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10318                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10319                if (pkgs == null) {
10320                    pkgs = new ArraySet<>();
10321                    mAppOpPermissionPackages.put(bp.name, pkgs);
10322                }
10323                pkgs.add(pkg.packageName);
10324            }
10325
10326            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10327            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10328                    >= Build.VERSION_CODES.M;
10329            switch (level) {
10330                case PermissionInfo.PROTECTION_NORMAL: {
10331                    // For all apps normal permissions are install time ones.
10332                    grant = GRANT_INSTALL;
10333                } break;
10334
10335                case PermissionInfo.PROTECTION_DANGEROUS: {
10336                    // If a permission review is required for legacy apps we represent
10337                    // their permissions as always granted runtime ones since we need
10338                    // to keep the review required permission flag per user while an
10339                    // install permission's state is shared across all users.
10340                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10341                        // For legacy apps dangerous permissions are install time ones.
10342                        grant = GRANT_INSTALL;
10343                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10344                        // For legacy apps that became modern, install becomes runtime.
10345                        grant = GRANT_UPGRADE;
10346                    } else if (mPromoteSystemApps
10347                            && isSystemApp(ps)
10348                            && mExistingSystemPackages.contains(ps.name)) {
10349                        // For legacy system apps, install becomes runtime.
10350                        // We cannot check hasInstallPermission() for system apps since those
10351                        // permissions were granted implicitly and not persisted pre-M.
10352                        grant = GRANT_UPGRADE;
10353                    } else {
10354                        // For modern apps keep runtime permissions unchanged.
10355                        grant = GRANT_RUNTIME;
10356                    }
10357                } break;
10358
10359                case PermissionInfo.PROTECTION_SIGNATURE: {
10360                    // For all apps signature permissions are install time ones.
10361                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10362                    if (allowedSig) {
10363                        grant = GRANT_INSTALL;
10364                    }
10365                } break;
10366            }
10367
10368            if (DEBUG_INSTALL) {
10369                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10370            }
10371
10372            if (grant != GRANT_DENIED) {
10373                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10374                    // If this is an existing, non-system package, then
10375                    // we can't add any new permissions to it.
10376                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10377                        // Except...  if this is a permission that was added
10378                        // to the platform (note: need to only do this when
10379                        // updating the platform).
10380                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10381                            grant = GRANT_DENIED;
10382                        }
10383                    }
10384                }
10385
10386                switch (grant) {
10387                    case GRANT_INSTALL: {
10388                        // Revoke this as runtime permission to handle the case of
10389                        // a runtime permission being downgraded to an install one.
10390                        // Also in permission review mode we keep dangerous permissions
10391                        // for legacy apps
10392                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10393                            if (origPermissions.getRuntimePermissionState(
10394                                    bp.name, userId) != null) {
10395                                // Revoke the runtime permission and clear the flags.
10396                                origPermissions.revokeRuntimePermission(bp, userId);
10397                                origPermissions.updatePermissionFlags(bp, userId,
10398                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10399                                // If we revoked a permission permission, we have to write.
10400                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10401                                        changedRuntimePermissionUserIds, userId);
10402                            }
10403                        }
10404                        // Grant an install permission.
10405                        if (permissionsState.grantInstallPermission(bp) !=
10406                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10407                            changedInstallPermission = true;
10408                        }
10409                    } break;
10410
10411                    case GRANT_RUNTIME: {
10412                        // Grant previously granted runtime permissions.
10413                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10414                            PermissionState permissionState = origPermissions
10415                                    .getRuntimePermissionState(bp.name, userId);
10416                            int flags = permissionState != null
10417                                    ? permissionState.getFlags() : 0;
10418                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10419                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10420                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10421                                    // If we cannot put the permission as it was, we have to write.
10422                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10423                                            changedRuntimePermissionUserIds, userId);
10424                                }
10425                                // If the app supports runtime permissions no need for a review.
10426                                if (mPermissionReviewRequired
10427                                        && appSupportsRuntimePermissions
10428                                        && (flags & PackageManager
10429                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10430                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10431                                    // Since we changed the flags, we have to write.
10432                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10433                                            changedRuntimePermissionUserIds, userId);
10434                                }
10435                            } else if (mPermissionReviewRequired
10436                                    && !appSupportsRuntimePermissions) {
10437                                // For legacy apps that need a permission review, every new
10438                                // runtime permission is granted but it is pending a review.
10439                                // We also need to review only platform defined runtime
10440                                // permissions as these are the only ones the platform knows
10441                                // how to disable the API to simulate revocation as legacy
10442                                // apps don't expect to run with revoked permissions.
10443                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10444                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10445                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10446                                        // We changed the flags, hence have to write.
10447                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10448                                                changedRuntimePermissionUserIds, userId);
10449                                    }
10450                                }
10451                                if (permissionsState.grantRuntimePermission(bp, userId)
10452                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10453                                    // We changed the permission, hence have to write.
10454                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10455                                            changedRuntimePermissionUserIds, userId);
10456                                }
10457                            }
10458                            // Propagate the permission flags.
10459                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10460                        }
10461                    } break;
10462
10463                    case GRANT_UPGRADE: {
10464                        // Grant runtime permissions for a previously held install permission.
10465                        PermissionState permissionState = origPermissions
10466                                .getInstallPermissionState(bp.name);
10467                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10468
10469                        if (origPermissions.revokeInstallPermission(bp)
10470                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10471                            // We will be transferring the permission flags, so clear them.
10472                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10473                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10474                            changedInstallPermission = true;
10475                        }
10476
10477                        // If the permission is not to be promoted to runtime we ignore it and
10478                        // also its other flags as they are not applicable to install permissions.
10479                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10480                            for (int userId : currentUserIds) {
10481                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10482                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10483                                    // Transfer the permission flags.
10484                                    permissionsState.updatePermissionFlags(bp, userId,
10485                                            flags, flags);
10486                                    // If we granted the permission, we have to write.
10487                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10488                                            changedRuntimePermissionUserIds, userId);
10489                                }
10490                            }
10491                        }
10492                    } break;
10493
10494                    default: {
10495                        if (packageOfInterest == null
10496                                || packageOfInterest.equals(pkg.packageName)) {
10497                            Slog.w(TAG, "Not granting permission " + perm
10498                                    + " to package " + pkg.packageName
10499                                    + " because it was previously installed without");
10500                        }
10501                    } break;
10502                }
10503            } else {
10504                if (permissionsState.revokeInstallPermission(bp) !=
10505                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10506                    // Also drop the permission flags.
10507                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10508                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10509                    changedInstallPermission = true;
10510                    Slog.i(TAG, "Un-granting permission " + perm
10511                            + " from package " + pkg.packageName
10512                            + " (protectionLevel=" + bp.protectionLevel
10513                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10514                            + ")");
10515                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10516                    // Don't print warning for app op permissions, since it is fine for them
10517                    // not to be granted, there is a UI for the user to decide.
10518                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10519                        Slog.w(TAG, "Not granting permission " + perm
10520                                + " to package " + pkg.packageName
10521                                + " (protectionLevel=" + bp.protectionLevel
10522                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10523                                + ")");
10524                    }
10525                }
10526            }
10527        }
10528
10529        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10530                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10531            // This is the first that we have heard about this package, so the
10532            // permissions we have now selected are fixed until explicitly
10533            // changed.
10534            ps.installPermissionsFixed = true;
10535        }
10536
10537        // Persist the runtime permissions state for users with changes. If permissions
10538        // were revoked because no app in the shared user declares them we have to
10539        // write synchronously to avoid losing runtime permissions state.
10540        for (int userId : changedRuntimePermissionUserIds) {
10541            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10542        }
10543    }
10544
10545    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10546        boolean allowed = false;
10547        final int NP = PackageParser.NEW_PERMISSIONS.length;
10548        for (int ip=0; ip<NP; ip++) {
10549            final PackageParser.NewPermissionInfo npi
10550                    = PackageParser.NEW_PERMISSIONS[ip];
10551            if (npi.name.equals(perm)
10552                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10553                allowed = true;
10554                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10555                        + pkg.packageName);
10556                break;
10557            }
10558        }
10559        return allowed;
10560    }
10561
10562    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10563            BasePermission bp, PermissionsState origPermissions) {
10564        boolean privilegedPermission = (bp.protectionLevel
10565                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10566        boolean privappPermissionsDisable =
10567                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10568        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10569        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10570        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10571                && !platformPackage && platformPermission) {
10572            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10573                    .getPrivAppPermissions(pkg.packageName);
10574            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10575            if (!whitelisted) {
10576                Slog.w(TAG, "Privileged permission " + perm + " for package "
10577                        + pkg.packageName + " - not in privapp-permissions whitelist");
10578                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10579                    return false;
10580                }
10581            }
10582        }
10583        boolean allowed = (compareSignatures(
10584                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10585                        == PackageManager.SIGNATURE_MATCH)
10586                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10587                        == PackageManager.SIGNATURE_MATCH);
10588        if (!allowed && privilegedPermission) {
10589            if (isSystemApp(pkg)) {
10590                // For updated system applications, a system permission
10591                // is granted only if it had been defined by the original application.
10592                if (pkg.isUpdatedSystemApp()) {
10593                    final PackageSetting sysPs = mSettings
10594                            .getDisabledSystemPkgLPr(pkg.packageName);
10595                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10596                        // If the original was granted this permission, we take
10597                        // that grant decision as read and propagate it to the
10598                        // update.
10599                        if (sysPs.isPrivileged()) {
10600                            allowed = true;
10601                        }
10602                    } else {
10603                        // The system apk may have been updated with an older
10604                        // version of the one on the data partition, but which
10605                        // granted a new system permission that it didn't have
10606                        // before.  In this case we do want to allow the app to
10607                        // now get the new permission if the ancestral apk is
10608                        // privileged to get it.
10609                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10610                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10611                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10612                                    allowed = true;
10613                                    break;
10614                                }
10615                            }
10616                        }
10617                        // Also if a privileged parent package on the system image or any of
10618                        // its children requested a privileged permission, the updated child
10619                        // packages can also get the permission.
10620                        if (pkg.parentPackage != null) {
10621                            final PackageSetting disabledSysParentPs = mSettings
10622                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10623                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10624                                    && disabledSysParentPs.isPrivileged()) {
10625                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10626                                    allowed = true;
10627                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10628                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10629                                    for (int i = 0; i < count; i++) {
10630                                        PackageParser.Package disabledSysChildPkg =
10631                                                disabledSysParentPs.pkg.childPackages.get(i);
10632                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10633                                                perm)) {
10634                                            allowed = true;
10635                                            break;
10636                                        }
10637                                    }
10638                                }
10639                            }
10640                        }
10641                    }
10642                } else {
10643                    allowed = isPrivilegedApp(pkg);
10644                }
10645            }
10646        }
10647        if (!allowed) {
10648            if (!allowed && (bp.protectionLevel
10649                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10650                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10651                // If this was a previously normal/dangerous permission that got moved
10652                // to a system permission as part of the runtime permission redesign, then
10653                // we still want to blindly grant it to old apps.
10654                allowed = true;
10655            }
10656            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10657                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10658                // If this permission is to be granted to the system installer and
10659                // this app is an installer, then it gets the permission.
10660                allowed = true;
10661            }
10662            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10663                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10664                // If this permission is to be granted to the system verifier and
10665                // this app is a verifier, then it gets the permission.
10666                allowed = true;
10667            }
10668            if (!allowed && (bp.protectionLevel
10669                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10670                    && isSystemApp(pkg)) {
10671                // Any pre-installed system app is allowed to get this permission.
10672                allowed = true;
10673            }
10674            if (!allowed && (bp.protectionLevel
10675                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10676                // For development permissions, a development permission
10677                // is granted only if it was already granted.
10678                allowed = origPermissions.hasInstallPermission(perm);
10679            }
10680            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10681                    && pkg.packageName.equals(mSetupWizardPackage)) {
10682                // If this permission is to be granted to the system setup wizard and
10683                // this app is a setup wizard, then it gets the permission.
10684                allowed = true;
10685            }
10686        }
10687        return allowed;
10688    }
10689
10690    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10691        final int permCount = pkg.requestedPermissions.size();
10692        for (int j = 0; j < permCount; j++) {
10693            String requestedPermission = pkg.requestedPermissions.get(j);
10694            if (permission.equals(requestedPermission)) {
10695                return true;
10696            }
10697        }
10698        return false;
10699    }
10700
10701    final class ActivityIntentResolver
10702            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10703        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10704                boolean defaultOnly, int userId) {
10705            if (!sUserManager.exists(userId)) return null;
10706            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10707            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10708        }
10709
10710        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10711                int userId) {
10712            if (!sUserManager.exists(userId)) return null;
10713            mFlags = flags;
10714            return super.queryIntent(intent, resolvedType,
10715                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10716        }
10717
10718        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10719                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10720            if (!sUserManager.exists(userId)) return null;
10721            if (packageActivities == null) {
10722                return null;
10723            }
10724            mFlags = flags;
10725            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10726            final int N = packageActivities.size();
10727            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10728                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10729
10730            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10731            for (int i = 0; i < N; ++i) {
10732                intentFilters = packageActivities.get(i).intents;
10733                if (intentFilters != null && intentFilters.size() > 0) {
10734                    PackageParser.ActivityIntentInfo[] array =
10735                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10736                    intentFilters.toArray(array);
10737                    listCut.add(array);
10738                }
10739            }
10740            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10741        }
10742
10743        /**
10744         * Finds a privileged activity that matches the specified activity names.
10745         */
10746        private PackageParser.Activity findMatchingActivity(
10747                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10748            for (PackageParser.Activity sysActivity : activityList) {
10749                if (sysActivity.info.name.equals(activityInfo.name)) {
10750                    return sysActivity;
10751                }
10752                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10753                    return sysActivity;
10754                }
10755                if (sysActivity.info.targetActivity != null) {
10756                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10757                        return sysActivity;
10758                    }
10759                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10760                        return sysActivity;
10761                    }
10762                }
10763            }
10764            return null;
10765        }
10766
10767        public class IterGenerator<E> {
10768            public Iterator<E> generate(ActivityIntentInfo info) {
10769                return null;
10770            }
10771        }
10772
10773        public class ActionIterGenerator extends IterGenerator<String> {
10774            @Override
10775            public Iterator<String> generate(ActivityIntentInfo info) {
10776                return info.actionsIterator();
10777            }
10778        }
10779
10780        public class CategoriesIterGenerator extends IterGenerator<String> {
10781            @Override
10782            public Iterator<String> generate(ActivityIntentInfo info) {
10783                return info.categoriesIterator();
10784            }
10785        }
10786
10787        public class SchemesIterGenerator extends IterGenerator<String> {
10788            @Override
10789            public Iterator<String> generate(ActivityIntentInfo info) {
10790                return info.schemesIterator();
10791            }
10792        }
10793
10794        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10795            @Override
10796            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10797                return info.authoritiesIterator();
10798            }
10799        }
10800
10801        /**
10802         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10803         * MODIFIED. Do not pass in a list that should not be changed.
10804         */
10805        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10806                IterGenerator<T> generator, Iterator<T> searchIterator) {
10807            // loop through the set of actions; every one must be found in the intent filter
10808            while (searchIterator.hasNext()) {
10809                // we must have at least one filter in the list to consider a match
10810                if (intentList.size() == 0) {
10811                    break;
10812                }
10813
10814                final T searchAction = searchIterator.next();
10815
10816                // loop through the set of intent filters
10817                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10818                while (intentIter.hasNext()) {
10819                    final ActivityIntentInfo intentInfo = intentIter.next();
10820                    boolean selectionFound = false;
10821
10822                    // loop through the intent filter's selection criteria; at least one
10823                    // of them must match the searched criteria
10824                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10825                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10826                        final T intentSelection = intentSelectionIter.next();
10827                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10828                            selectionFound = true;
10829                            break;
10830                        }
10831                    }
10832
10833                    // the selection criteria wasn't found in this filter's set; this filter
10834                    // is not a potential match
10835                    if (!selectionFound) {
10836                        intentIter.remove();
10837                    }
10838                }
10839            }
10840        }
10841
10842        private boolean isProtectedAction(ActivityIntentInfo filter) {
10843            final Iterator<String> actionsIter = filter.actionsIterator();
10844            while (actionsIter != null && actionsIter.hasNext()) {
10845                final String filterAction = actionsIter.next();
10846                if (PROTECTED_ACTIONS.contains(filterAction)) {
10847                    return true;
10848                }
10849            }
10850            return false;
10851        }
10852
10853        /**
10854         * Adjusts the priority of the given intent filter according to policy.
10855         * <p>
10856         * <ul>
10857         * <li>The priority for non privileged applications is capped to '0'</li>
10858         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10859         * <li>The priority for unbundled updates to privileged applications is capped to the
10860         *      priority defined on the system partition</li>
10861         * </ul>
10862         * <p>
10863         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10864         * allowed to obtain any priority on any action.
10865         */
10866        private void adjustPriority(
10867                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10868            // nothing to do; priority is fine as-is
10869            if (intent.getPriority() <= 0) {
10870                return;
10871            }
10872
10873            final ActivityInfo activityInfo = intent.activity.info;
10874            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10875
10876            final boolean privilegedApp =
10877                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10878            if (!privilegedApp) {
10879                // non-privileged applications can never define a priority >0
10880                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10881                        + " package: " + applicationInfo.packageName
10882                        + " activity: " + intent.activity.className
10883                        + " origPrio: " + intent.getPriority());
10884                intent.setPriority(0);
10885                return;
10886            }
10887
10888            if (systemActivities == null) {
10889                // the system package is not disabled; we're parsing the system partition
10890                if (isProtectedAction(intent)) {
10891                    if (mDeferProtectedFilters) {
10892                        // We can't deal with these just yet. No component should ever obtain a
10893                        // >0 priority for a protected actions, with ONE exception -- the setup
10894                        // wizard. The setup wizard, however, cannot be known until we're able to
10895                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10896                        // until all intent filters have been processed. Chicken, meet egg.
10897                        // Let the filter temporarily have a high priority and rectify the
10898                        // priorities after all system packages have been scanned.
10899                        mProtectedFilters.add(intent);
10900                        if (DEBUG_FILTERS) {
10901                            Slog.i(TAG, "Protected action; save for later;"
10902                                    + " package: " + applicationInfo.packageName
10903                                    + " activity: " + intent.activity.className
10904                                    + " origPrio: " + intent.getPriority());
10905                        }
10906                        return;
10907                    } else {
10908                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10909                            Slog.i(TAG, "No setup wizard;"
10910                                + " All protected intents capped to priority 0");
10911                        }
10912                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10913                            if (DEBUG_FILTERS) {
10914                                Slog.i(TAG, "Found setup wizard;"
10915                                    + " allow priority " + intent.getPriority() + ";"
10916                                    + " package: " + intent.activity.info.packageName
10917                                    + " activity: " + intent.activity.className
10918                                    + " priority: " + intent.getPriority());
10919                            }
10920                            // setup wizard gets whatever it wants
10921                            return;
10922                        }
10923                        Slog.w(TAG, "Protected action; cap priority to 0;"
10924                                + " package: " + intent.activity.info.packageName
10925                                + " activity: " + intent.activity.className
10926                                + " origPrio: " + intent.getPriority());
10927                        intent.setPriority(0);
10928                        return;
10929                    }
10930                }
10931                // privileged apps on the system image get whatever priority they request
10932                return;
10933            }
10934
10935            // privileged app unbundled update ... try to find the same activity
10936            final PackageParser.Activity foundActivity =
10937                    findMatchingActivity(systemActivities, activityInfo);
10938            if (foundActivity == null) {
10939                // this is a new activity; it cannot obtain >0 priority
10940                if (DEBUG_FILTERS) {
10941                    Slog.i(TAG, "New activity; cap priority to 0;"
10942                            + " package: " + applicationInfo.packageName
10943                            + " activity: " + intent.activity.className
10944                            + " origPrio: " + intent.getPriority());
10945                }
10946                intent.setPriority(0);
10947                return;
10948            }
10949
10950            // found activity, now check for filter equivalence
10951
10952            // a shallow copy is enough; we modify the list, not its contents
10953            final List<ActivityIntentInfo> intentListCopy =
10954                    new ArrayList<>(foundActivity.intents);
10955            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10956
10957            // find matching action subsets
10958            final Iterator<String> actionsIterator = intent.actionsIterator();
10959            if (actionsIterator != null) {
10960                getIntentListSubset(
10961                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10962                if (intentListCopy.size() == 0) {
10963                    // no more intents to match; we're not equivalent
10964                    if (DEBUG_FILTERS) {
10965                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10966                                + " package: " + applicationInfo.packageName
10967                                + " activity: " + intent.activity.className
10968                                + " origPrio: " + intent.getPriority());
10969                    }
10970                    intent.setPriority(0);
10971                    return;
10972                }
10973            }
10974
10975            // find matching category subsets
10976            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10977            if (categoriesIterator != null) {
10978                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10979                        categoriesIterator);
10980                if (intentListCopy.size() == 0) {
10981                    // no more intents to match; we're not equivalent
10982                    if (DEBUG_FILTERS) {
10983                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10984                                + " package: " + applicationInfo.packageName
10985                                + " activity: " + intent.activity.className
10986                                + " origPrio: " + intent.getPriority());
10987                    }
10988                    intent.setPriority(0);
10989                    return;
10990                }
10991            }
10992
10993            // find matching schemes subsets
10994            final Iterator<String> schemesIterator = intent.schemesIterator();
10995            if (schemesIterator != null) {
10996                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10997                        schemesIterator);
10998                if (intentListCopy.size() == 0) {
10999                    // no more intents to match; we're not equivalent
11000                    if (DEBUG_FILTERS) {
11001                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11002                                + " package: " + applicationInfo.packageName
11003                                + " activity: " + intent.activity.className
11004                                + " origPrio: " + intent.getPriority());
11005                    }
11006                    intent.setPriority(0);
11007                    return;
11008                }
11009            }
11010
11011            // find matching authorities subsets
11012            final Iterator<IntentFilter.AuthorityEntry>
11013                    authoritiesIterator = intent.authoritiesIterator();
11014            if (authoritiesIterator != null) {
11015                getIntentListSubset(intentListCopy,
11016                        new AuthoritiesIterGenerator(),
11017                        authoritiesIterator);
11018                if (intentListCopy.size() == 0) {
11019                    // no more intents to match; we're not equivalent
11020                    if (DEBUG_FILTERS) {
11021                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11022                                + " package: " + applicationInfo.packageName
11023                                + " activity: " + intent.activity.className
11024                                + " origPrio: " + intent.getPriority());
11025                    }
11026                    intent.setPriority(0);
11027                    return;
11028                }
11029            }
11030
11031            // we found matching filter(s); app gets the max priority of all intents
11032            int cappedPriority = 0;
11033            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11034                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11035            }
11036            if (intent.getPriority() > cappedPriority) {
11037                if (DEBUG_FILTERS) {
11038                    Slog.i(TAG, "Found matching filter(s);"
11039                            + " cap priority to " + cappedPriority + ";"
11040                            + " package: " + applicationInfo.packageName
11041                            + " activity: " + intent.activity.className
11042                            + " origPrio: " + intent.getPriority());
11043                }
11044                intent.setPriority(cappedPriority);
11045                return;
11046            }
11047            // all this for nothing; the requested priority was <= what was on the system
11048        }
11049
11050        public final void addActivity(PackageParser.Activity a, String type) {
11051            mActivities.put(a.getComponentName(), a);
11052            if (DEBUG_SHOW_INFO)
11053                Log.v(
11054                TAG, "  " + type + " " +
11055                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11056            if (DEBUG_SHOW_INFO)
11057                Log.v(TAG, "    Class=" + a.info.name);
11058            final int NI = a.intents.size();
11059            for (int j=0; j<NI; j++) {
11060                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11061                if ("activity".equals(type)) {
11062                    final PackageSetting ps =
11063                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11064                    final List<PackageParser.Activity> systemActivities =
11065                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11066                    adjustPriority(systemActivities, intent);
11067                }
11068                if (DEBUG_SHOW_INFO) {
11069                    Log.v(TAG, "    IntentFilter:");
11070                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11071                }
11072                if (!intent.debugCheck()) {
11073                    Log.w(TAG, "==> For Activity " + a.info.name);
11074                }
11075                addFilter(intent);
11076            }
11077        }
11078
11079        public final void removeActivity(PackageParser.Activity a, String type) {
11080            mActivities.remove(a.getComponentName());
11081            if (DEBUG_SHOW_INFO) {
11082                Log.v(TAG, "  " + type + " "
11083                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11084                                : a.info.name) + ":");
11085                Log.v(TAG, "    Class=" + a.info.name);
11086            }
11087            final int NI = a.intents.size();
11088            for (int j=0; j<NI; j++) {
11089                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11090                if (DEBUG_SHOW_INFO) {
11091                    Log.v(TAG, "    IntentFilter:");
11092                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11093                }
11094                removeFilter(intent);
11095            }
11096        }
11097
11098        @Override
11099        protected boolean allowFilterResult(
11100                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11101            ActivityInfo filterAi = filter.activity.info;
11102            for (int i=dest.size()-1; i>=0; i--) {
11103                ActivityInfo destAi = dest.get(i).activityInfo;
11104                if (destAi.name == filterAi.name
11105                        && destAi.packageName == filterAi.packageName) {
11106                    return false;
11107                }
11108            }
11109            return true;
11110        }
11111
11112        @Override
11113        protected ActivityIntentInfo[] newArray(int size) {
11114            return new ActivityIntentInfo[size];
11115        }
11116
11117        @Override
11118        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11119            if (!sUserManager.exists(userId)) return true;
11120            PackageParser.Package p = filter.activity.owner;
11121            if (p != null) {
11122                PackageSetting ps = (PackageSetting)p.mExtras;
11123                if (ps != null) {
11124                    // System apps are never considered stopped for purposes of
11125                    // filtering, because there may be no way for the user to
11126                    // actually re-launch them.
11127                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11128                            && ps.getStopped(userId);
11129                }
11130            }
11131            return false;
11132        }
11133
11134        @Override
11135        protected boolean isPackageForFilter(String packageName,
11136                PackageParser.ActivityIntentInfo info) {
11137            return packageName.equals(info.activity.owner.packageName);
11138        }
11139
11140        @Override
11141        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11142                int match, int userId) {
11143            if (!sUserManager.exists(userId)) return null;
11144            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11145                return null;
11146            }
11147            final PackageParser.Activity activity = info.activity;
11148            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11149            if (ps == null) {
11150                return null;
11151            }
11152            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11153                    ps.readUserState(userId), userId);
11154            if (ai == null) {
11155                return null;
11156            }
11157            final ResolveInfo res = new ResolveInfo();
11158            res.activityInfo = ai;
11159            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11160                res.filter = info;
11161            }
11162            if (info != null) {
11163                res.handleAllWebDataURI = info.handleAllWebDataURI();
11164            }
11165            res.priority = info.getPriority();
11166            res.preferredOrder = activity.owner.mPreferredOrder;
11167            //System.out.println("Result: " + res.activityInfo.className +
11168            //                   " = " + res.priority);
11169            res.match = match;
11170            res.isDefault = info.hasDefault;
11171            res.labelRes = info.labelRes;
11172            res.nonLocalizedLabel = info.nonLocalizedLabel;
11173            if (userNeedsBadging(userId)) {
11174                res.noResourceId = true;
11175            } else {
11176                res.icon = info.icon;
11177            }
11178            res.iconResourceId = info.icon;
11179            res.system = res.activityInfo.applicationInfo.isSystemApp();
11180            return res;
11181        }
11182
11183        @Override
11184        protected void sortResults(List<ResolveInfo> results) {
11185            Collections.sort(results, mResolvePrioritySorter);
11186        }
11187
11188        @Override
11189        protected void dumpFilter(PrintWriter out, String prefix,
11190                PackageParser.ActivityIntentInfo filter) {
11191            out.print(prefix); out.print(
11192                    Integer.toHexString(System.identityHashCode(filter.activity)));
11193                    out.print(' ');
11194                    filter.activity.printComponentShortName(out);
11195                    out.print(" filter ");
11196                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11197        }
11198
11199        @Override
11200        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11201            return filter.activity;
11202        }
11203
11204        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11205            PackageParser.Activity activity = (PackageParser.Activity)label;
11206            out.print(prefix); out.print(
11207                    Integer.toHexString(System.identityHashCode(activity)));
11208                    out.print(' ');
11209                    activity.printComponentShortName(out);
11210            if (count > 1) {
11211                out.print(" ("); out.print(count); out.print(" filters)");
11212            }
11213            out.println();
11214        }
11215
11216        // Keys are String (activity class name), values are Activity.
11217        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11218                = new ArrayMap<ComponentName, PackageParser.Activity>();
11219        private int mFlags;
11220    }
11221
11222    private final class ServiceIntentResolver
11223            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11224        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11225                boolean defaultOnly, int userId) {
11226            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11227            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11228        }
11229
11230        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11231                int userId) {
11232            if (!sUserManager.exists(userId)) return null;
11233            mFlags = flags;
11234            return super.queryIntent(intent, resolvedType,
11235                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11236        }
11237
11238        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11239                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11240            if (!sUserManager.exists(userId)) return null;
11241            if (packageServices == null) {
11242                return null;
11243            }
11244            mFlags = flags;
11245            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11246            final int N = packageServices.size();
11247            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11248                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11249
11250            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11251            for (int i = 0; i < N; ++i) {
11252                intentFilters = packageServices.get(i).intents;
11253                if (intentFilters != null && intentFilters.size() > 0) {
11254                    PackageParser.ServiceIntentInfo[] array =
11255                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11256                    intentFilters.toArray(array);
11257                    listCut.add(array);
11258                }
11259            }
11260            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11261        }
11262
11263        public final void addService(PackageParser.Service s) {
11264            mServices.put(s.getComponentName(), s);
11265            if (DEBUG_SHOW_INFO) {
11266                Log.v(TAG, "  "
11267                        + (s.info.nonLocalizedLabel != null
11268                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11269                Log.v(TAG, "    Class=" + s.info.name);
11270            }
11271            final int NI = s.intents.size();
11272            int j;
11273            for (j=0; j<NI; j++) {
11274                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11275                if (DEBUG_SHOW_INFO) {
11276                    Log.v(TAG, "    IntentFilter:");
11277                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11278                }
11279                if (!intent.debugCheck()) {
11280                    Log.w(TAG, "==> For Service " + s.info.name);
11281                }
11282                addFilter(intent);
11283            }
11284        }
11285
11286        public final void removeService(PackageParser.Service s) {
11287            mServices.remove(s.getComponentName());
11288            if (DEBUG_SHOW_INFO) {
11289                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11290                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11291                Log.v(TAG, "    Class=" + s.info.name);
11292            }
11293            final int NI = s.intents.size();
11294            int j;
11295            for (j=0; j<NI; j++) {
11296                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11297                if (DEBUG_SHOW_INFO) {
11298                    Log.v(TAG, "    IntentFilter:");
11299                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11300                }
11301                removeFilter(intent);
11302            }
11303        }
11304
11305        @Override
11306        protected boolean allowFilterResult(
11307                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11308            ServiceInfo filterSi = filter.service.info;
11309            for (int i=dest.size()-1; i>=0; i--) {
11310                ServiceInfo destAi = dest.get(i).serviceInfo;
11311                if (destAi.name == filterSi.name
11312                        && destAi.packageName == filterSi.packageName) {
11313                    return false;
11314                }
11315            }
11316            return true;
11317        }
11318
11319        @Override
11320        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11321            return new PackageParser.ServiceIntentInfo[size];
11322        }
11323
11324        @Override
11325        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11326            if (!sUserManager.exists(userId)) return true;
11327            PackageParser.Package p = filter.service.owner;
11328            if (p != null) {
11329                PackageSetting ps = (PackageSetting)p.mExtras;
11330                if (ps != null) {
11331                    // System apps are never considered stopped for purposes of
11332                    // filtering, because there may be no way for the user to
11333                    // actually re-launch them.
11334                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11335                            && ps.getStopped(userId);
11336                }
11337            }
11338            return false;
11339        }
11340
11341        @Override
11342        protected boolean isPackageForFilter(String packageName,
11343                PackageParser.ServiceIntentInfo info) {
11344            return packageName.equals(info.service.owner.packageName);
11345        }
11346
11347        @Override
11348        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11349                int match, int userId) {
11350            if (!sUserManager.exists(userId)) return null;
11351            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11352            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11353                return null;
11354            }
11355            final PackageParser.Service service = info.service;
11356            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11357            if (ps == null) {
11358                return null;
11359            }
11360            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11361                    ps.readUserState(userId), userId);
11362            if (si == null) {
11363                return null;
11364            }
11365            final ResolveInfo res = new ResolveInfo();
11366            res.serviceInfo = si;
11367            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11368                res.filter = filter;
11369            }
11370            res.priority = info.getPriority();
11371            res.preferredOrder = service.owner.mPreferredOrder;
11372            res.match = match;
11373            res.isDefault = info.hasDefault;
11374            res.labelRes = info.labelRes;
11375            res.nonLocalizedLabel = info.nonLocalizedLabel;
11376            res.icon = info.icon;
11377            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11378            return res;
11379        }
11380
11381        @Override
11382        protected void sortResults(List<ResolveInfo> results) {
11383            Collections.sort(results, mResolvePrioritySorter);
11384        }
11385
11386        @Override
11387        protected void dumpFilter(PrintWriter out, String prefix,
11388                PackageParser.ServiceIntentInfo filter) {
11389            out.print(prefix); out.print(
11390                    Integer.toHexString(System.identityHashCode(filter.service)));
11391                    out.print(' ');
11392                    filter.service.printComponentShortName(out);
11393                    out.print(" filter ");
11394                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11395        }
11396
11397        @Override
11398        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11399            return filter.service;
11400        }
11401
11402        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11403            PackageParser.Service service = (PackageParser.Service)label;
11404            out.print(prefix); out.print(
11405                    Integer.toHexString(System.identityHashCode(service)));
11406                    out.print(' ');
11407                    service.printComponentShortName(out);
11408            if (count > 1) {
11409                out.print(" ("); out.print(count); out.print(" filters)");
11410            }
11411            out.println();
11412        }
11413
11414//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11415//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11416//            final List<ResolveInfo> retList = Lists.newArrayList();
11417//            while (i.hasNext()) {
11418//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11419//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11420//                    retList.add(resolveInfo);
11421//                }
11422//            }
11423//            return retList;
11424//        }
11425
11426        // Keys are String (activity class name), values are Activity.
11427        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11428                = new ArrayMap<ComponentName, PackageParser.Service>();
11429        private int mFlags;
11430    };
11431
11432    private final class ProviderIntentResolver
11433            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11434        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11435                boolean defaultOnly, int userId) {
11436            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11437            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11438        }
11439
11440        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11441                int userId) {
11442            if (!sUserManager.exists(userId))
11443                return null;
11444            mFlags = flags;
11445            return super.queryIntent(intent, resolvedType,
11446                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11447        }
11448
11449        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11450                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11451            if (!sUserManager.exists(userId))
11452                return null;
11453            if (packageProviders == null) {
11454                return null;
11455            }
11456            mFlags = flags;
11457            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11458            final int N = packageProviders.size();
11459            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11460                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11461
11462            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11463            for (int i = 0; i < N; ++i) {
11464                intentFilters = packageProviders.get(i).intents;
11465                if (intentFilters != null && intentFilters.size() > 0) {
11466                    PackageParser.ProviderIntentInfo[] array =
11467                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11468                    intentFilters.toArray(array);
11469                    listCut.add(array);
11470                }
11471            }
11472            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11473        }
11474
11475        public final void addProvider(PackageParser.Provider p) {
11476            if (mProviders.containsKey(p.getComponentName())) {
11477                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11478                return;
11479            }
11480
11481            mProviders.put(p.getComponentName(), p);
11482            if (DEBUG_SHOW_INFO) {
11483                Log.v(TAG, "  "
11484                        + (p.info.nonLocalizedLabel != null
11485                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11486                Log.v(TAG, "    Class=" + p.info.name);
11487            }
11488            final int NI = p.intents.size();
11489            int j;
11490            for (j = 0; j < NI; j++) {
11491                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11492                if (DEBUG_SHOW_INFO) {
11493                    Log.v(TAG, "    IntentFilter:");
11494                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11495                }
11496                if (!intent.debugCheck()) {
11497                    Log.w(TAG, "==> For Provider " + p.info.name);
11498                }
11499                addFilter(intent);
11500            }
11501        }
11502
11503        public final void removeProvider(PackageParser.Provider p) {
11504            mProviders.remove(p.getComponentName());
11505            if (DEBUG_SHOW_INFO) {
11506                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11507                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11508                Log.v(TAG, "    Class=" + p.info.name);
11509            }
11510            final int NI = p.intents.size();
11511            int j;
11512            for (j = 0; j < NI; j++) {
11513                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11514                if (DEBUG_SHOW_INFO) {
11515                    Log.v(TAG, "    IntentFilter:");
11516                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11517                }
11518                removeFilter(intent);
11519            }
11520        }
11521
11522        @Override
11523        protected boolean allowFilterResult(
11524                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11525            ProviderInfo filterPi = filter.provider.info;
11526            for (int i = dest.size() - 1; i >= 0; i--) {
11527                ProviderInfo destPi = dest.get(i).providerInfo;
11528                if (destPi.name == filterPi.name
11529                        && destPi.packageName == filterPi.packageName) {
11530                    return false;
11531                }
11532            }
11533            return true;
11534        }
11535
11536        @Override
11537        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11538            return new PackageParser.ProviderIntentInfo[size];
11539        }
11540
11541        @Override
11542        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11543            if (!sUserManager.exists(userId))
11544                return true;
11545            PackageParser.Package p = filter.provider.owner;
11546            if (p != null) {
11547                PackageSetting ps = (PackageSetting) p.mExtras;
11548                if (ps != null) {
11549                    // System apps are never considered stopped for purposes of
11550                    // filtering, because there may be no way for the user to
11551                    // actually re-launch them.
11552                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11553                            && ps.getStopped(userId);
11554                }
11555            }
11556            return false;
11557        }
11558
11559        @Override
11560        protected boolean isPackageForFilter(String packageName,
11561                PackageParser.ProviderIntentInfo info) {
11562            return packageName.equals(info.provider.owner.packageName);
11563        }
11564
11565        @Override
11566        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11567                int match, int userId) {
11568            if (!sUserManager.exists(userId))
11569                return null;
11570            final PackageParser.ProviderIntentInfo info = filter;
11571            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11572                return null;
11573            }
11574            final PackageParser.Provider provider = info.provider;
11575            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11576            if (ps == null) {
11577                return null;
11578            }
11579            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11580                    ps.readUserState(userId), userId);
11581            if (pi == null) {
11582                return null;
11583            }
11584            final ResolveInfo res = new ResolveInfo();
11585            res.providerInfo = pi;
11586            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11587                res.filter = filter;
11588            }
11589            res.priority = info.getPriority();
11590            res.preferredOrder = provider.owner.mPreferredOrder;
11591            res.match = match;
11592            res.isDefault = info.hasDefault;
11593            res.labelRes = info.labelRes;
11594            res.nonLocalizedLabel = info.nonLocalizedLabel;
11595            res.icon = info.icon;
11596            res.system = res.providerInfo.applicationInfo.isSystemApp();
11597            return res;
11598        }
11599
11600        @Override
11601        protected void sortResults(List<ResolveInfo> results) {
11602            Collections.sort(results, mResolvePrioritySorter);
11603        }
11604
11605        @Override
11606        protected void dumpFilter(PrintWriter out, String prefix,
11607                PackageParser.ProviderIntentInfo filter) {
11608            out.print(prefix);
11609            out.print(
11610                    Integer.toHexString(System.identityHashCode(filter.provider)));
11611            out.print(' ');
11612            filter.provider.printComponentShortName(out);
11613            out.print(" filter ");
11614            out.println(Integer.toHexString(System.identityHashCode(filter)));
11615        }
11616
11617        @Override
11618        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11619            return filter.provider;
11620        }
11621
11622        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11623            PackageParser.Provider provider = (PackageParser.Provider)label;
11624            out.print(prefix); out.print(
11625                    Integer.toHexString(System.identityHashCode(provider)));
11626                    out.print(' ');
11627                    provider.printComponentShortName(out);
11628            if (count > 1) {
11629                out.print(" ("); out.print(count); out.print(" filters)");
11630            }
11631            out.println();
11632        }
11633
11634        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11635                = new ArrayMap<ComponentName, PackageParser.Provider>();
11636        private int mFlags;
11637    }
11638
11639    static final class EphemeralIntentResolver
11640            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11641        /**
11642         * The result that has the highest defined order. Ordering applies on a
11643         * per-package basis. Mapping is from package name to Pair of order and
11644         * EphemeralResolveInfo.
11645         * <p>
11646         * NOTE: This is implemented as a field variable for convenience and efficiency.
11647         * By having a field variable, we're able to track filter ordering as soon as
11648         * a non-zero order is defined. Otherwise, multiple loops across the result set
11649         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11650         * this needs to be contained entirely within {@link #filterResults()}.
11651         */
11652        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11653
11654        @Override
11655        protected EphemeralResponse[] newArray(int size) {
11656            return new EphemeralResponse[size];
11657        }
11658
11659        @Override
11660        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11661            return true;
11662        }
11663
11664        @Override
11665        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11666                int userId) {
11667            if (!sUserManager.exists(userId)) {
11668                return null;
11669            }
11670            final String packageName = responseObj.resolveInfo.getPackageName();
11671            final Integer order = responseObj.getOrder();
11672            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11673                    mOrderResult.get(packageName);
11674            // ordering is enabled and this item's order isn't high enough
11675            if (lastOrderResult != null && lastOrderResult.first >= order) {
11676                return null;
11677            }
11678            final EphemeralResolveInfo res = responseObj.resolveInfo;
11679            if (order > 0) {
11680                // non-zero order, enable ordering
11681                mOrderResult.put(packageName, new Pair<>(order, res));
11682            }
11683            return responseObj;
11684        }
11685
11686        @Override
11687        protected void filterResults(List<EphemeralResponse> results) {
11688            // only do work if ordering is enabled [most of the time it won't be]
11689            if (mOrderResult.size() == 0) {
11690                return;
11691            }
11692            int resultSize = results.size();
11693            for (int i = 0; i < resultSize; i++) {
11694                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11695                final String packageName = info.getPackageName();
11696                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11697                if (savedInfo == null) {
11698                    // package doesn't having ordering
11699                    continue;
11700                }
11701                if (savedInfo.second == info) {
11702                    // circled back to the highest ordered item; remove from order list
11703                    mOrderResult.remove(savedInfo);
11704                    if (mOrderResult.size() == 0) {
11705                        // no more ordered items
11706                        break;
11707                    }
11708                    continue;
11709                }
11710                // item has a worse order, remove it from the result list
11711                results.remove(i);
11712                resultSize--;
11713                i--;
11714            }
11715        }
11716    }
11717
11718    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11719            new Comparator<ResolveInfo>() {
11720        public int compare(ResolveInfo r1, ResolveInfo r2) {
11721            int v1 = r1.priority;
11722            int v2 = r2.priority;
11723            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11724            if (v1 != v2) {
11725                return (v1 > v2) ? -1 : 1;
11726            }
11727            v1 = r1.preferredOrder;
11728            v2 = r2.preferredOrder;
11729            if (v1 != v2) {
11730                return (v1 > v2) ? -1 : 1;
11731            }
11732            if (r1.isDefault != r2.isDefault) {
11733                return r1.isDefault ? -1 : 1;
11734            }
11735            v1 = r1.match;
11736            v2 = r2.match;
11737            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11738            if (v1 != v2) {
11739                return (v1 > v2) ? -1 : 1;
11740            }
11741            if (r1.system != r2.system) {
11742                return r1.system ? -1 : 1;
11743            }
11744            if (r1.activityInfo != null) {
11745                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11746            }
11747            if (r1.serviceInfo != null) {
11748                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11749            }
11750            if (r1.providerInfo != null) {
11751                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11752            }
11753            return 0;
11754        }
11755    };
11756
11757    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11758            new Comparator<ProviderInfo>() {
11759        public int compare(ProviderInfo p1, ProviderInfo p2) {
11760            final int v1 = p1.initOrder;
11761            final int v2 = p2.initOrder;
11762            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11763        }
11764    };
11765
11766    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11767            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11768            final int[] userIds) {
11769        mHandler.post(new Runnable() {
11770            @Override
11771            public void run() {
11772                try {
11773                    final IActivityManager am = ActivityManager.getService();
11774                    if (am == null) return;
11775                    final int[] resolvedUserIds;
11776                    if (userIds == null) {
11777                        resolvedUserIds = am.getRunningUserIds();
11778                    } else {
11779                        resolvedUserIds = userIds;
11780                    }
11781                    for (int id : resolvedUserIds) {
11782                        final Intent intent = new Intent(action,
11783                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11784                        if (extras != null) {
11785                            intent.putExtras(extras);
11786                        }
11787                        if (targetPkg != null) {
11788                            intent.setPackage(targetPkg);
11789                        }
11790                        // Modify the UID when posting to other users
11791                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11792                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11793                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11794                            intent.putExtra(Intent.EXTRA_UID, uid);
11795                        }
11796                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11797                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11798                        if (DEBUG_BROADCASTS) {
11799                            RuntimeException here = new RuntimeException("here");
11800                            here.fillInStackTrace();
11801                            Slog.d(TAG, "Sending to user " + id + ": "
11802                                    + intent.toShortString(false, true, false, false)
11803                                    + " " + intent.getExtras(), here);
11804                        }
11805                        am.broadcastIntent(null, intent, null, finishedReceiver,
11806                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11807                                null, finishedReceiver != null, false, id);
11808                    }
11809                } catch (RemoteException ex) {
11810                }
11811            }
11812        });
11813    }
11814
11815    /**
11816     * Check if the external storage media is available. This is true if there
11817     * is a mounted external storage medium or if the external storage is
11818     * emulated.
11819     */
11820    private boolean isExternalMediaAvailable() {
11821        return mMediaMounted || Environment.isExternalStorageEmulated();
11822    }
11823
11824    @Override
11825    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11826        // writer
11827        synchronized (mPackages) {
11828            if (!isExternalMediaAvailable()) {
11829                // If the external storage is no longer mounted at this point,
11830                // the caller may not have been able to delete all of this
11831                // packages files and can not delete any more.  Bail.
11832                return null;
11833            }
11834            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11835            if (lastPackage != null) {
11836                pkgs.remove(lastPackage);
11837            }
11838            if (pkgs.size() > 0) {
11839                return pkgs.get(0);
11840            }
11841        }
11842        return null;
11843    }
11844
11845    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11846        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11847                userId, andCode ? 1 : 0, packageName);
11848        if (mSystemReady) {
11849            msg.sendToTarget();
11850        } else {
11851            if (mPostSystemReadyMessages == null) {
11852                mPostSystemReadyMessages = new ArrayList<>();
11853            }
11854            mPostSystemReadyMessages.add(msg);
11855        }
11856    }
11857
11858    void startCleaningPackages() {
11859        // reader
11860        if (!isExternalMediaAvailable()) {
11861            return;
11862        }
11863        synchronized (mPackages) {
11864            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11865                return;
11866            }
11867        }
11868        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11869        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11870        IActivityManager am = ActivityManager.getService();
11871        if (am != null) {
11872            try {
11873                am.startService(null, intent, null, mContext.getOpPackageName(),
11874                        UserHandle.USER_SYSTEM);
11875            } catch (RemoteException e) {
11876            }
11877        }
11878    }
11879
11880    @Override
11881    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11882            int installFlags, String installerPackageName, int userId) {
11883        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11884
11885        final int callingUid = Binder.getCallingUid();
11886        enforceCrossUserPermission(callingUid, userId,
11887                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11888
11889        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11890            try {
11891                if (observer != null) {
11892                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11893                }
11894            } catch (RemoteException re) {
11895            }
11896            return;
11897        }
11898
11899        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11900            installFlags |= PackageManager.INSTALL_FROM_ADB;
11901
11902        } else {
11903            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11904            // about installerPackageName.
11905
11906            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11907            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11908        }
11909
11910        UserHandle user;
11911        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11912            user = UserHandle.ALL;
11913        } else {
11914            user = new UserHandle(userId);
11915        }
11916
11917        // Only system components can circumvent runtime permissions when installing.
11918        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11919                && mContext.checkCallingOrSelfPermission(Manifest.permission
11920                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11921            throw new SecurityException("You need the "
11922                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11923                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11924        }
11925
11926        final File originFile = new File(originPath);
11927        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11928
11929        final Message msg = mHandler.obtainMessage(INIT_COPY);
11930        final VerificationInfo verificationInfo = new VerificationInfo(
11931                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11932        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11933                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11934                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11935                null /*certificates*/);
11936        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11937        msg.obj = params;
11938
11939        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11940                System.identityHashCode(msg.obj));
11941        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11942                System.identityHashCode(msg.obj));
11943
11944        mHandler.sendMessage(msg);
11945    }
11946
11947    void installStage(String packageName, File stagedDir, String stagedCid,
11948            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11949            String installerPackageName, int installerUid, UserHandle user,
11950            Certificate[][] certificates) {
11951        if (DEBUG_EPHEMERAL) {
11952            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11953                Slog.d(TAG, "Ephemeral install of " + packageName);
11954            }
11955        }
11956        final VerificationInfo verificationInfo = new VerificationInfo(
11957                sessionParams.originatingUri, sessionParams.referrerUri,
11958                sessionParams.originatingUid, installerUid);
11959
11960        final OriginInfo origin;
11961        if (stagedDir != null) {
11962            origin = OriginInfo.fromStagedFile(stagedDir);
11963        } else {
11964            origin = OriginInfo.fromStagedContainer(stagedCid);
11965        }
11966
11967        final Message msg = mHandler.obtainMessage(INIT_COPY);
11968        final InstallParams params = new InstallParams(origin, null, observer,
11969                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11970                verificationInfo, user, sessionParams.abiOverride,
11971                sessionParams.grantedRuntimePermissions, certificates);
11972        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11973        msg.obj = params;
11974
11975        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11976                System.identityHashCode(msg.obj));
11977        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11978                System.identityHashCode(msg.obj));
11979
11980        mHandler.sendMessage(msg);
11981    }
11982
11983    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11984            int userId) {
11985        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11986        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
11987    }
11988
11989    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
11990            int appId, int... userIds) {
11991        if (ArrayUtils.isEmpty(userIds)) {
11992            return;
11993        }
11994        Bundle extras = new Bundle(1);
11995        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
11996        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
11997
11998        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11999                packageName, extras, 0, null, null, userIds);
12000        if (isSystem) {
12001            mHandler.post(() -> {
12002                        for (int userId : userIds) {
12003                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12004                        }
12005                    }
12006            );
12007        }
12008    }
12009
12010    /**
12011     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12012     * automatically without needing an explicit launch.
12013     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12014     */
12015    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12016        // If user is not running, the app didn't miss any broadcast
12017        if (!mUserManagerInternal.isUserRunning(userId)) {
12018            return;
12019        }
12020        final IActivityManager am = ActivityManager.getService();
12021        try {
12022            // Deliver LOCKED_BOOT_COMPLETED first
12023            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12024                    .setPackage(packageName);
12025            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12026            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12027                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12028
12029            // Deliver BOOT_COMPLETED only if user is unlocked
12030            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12031                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12032                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12033                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12034            }
12035        } catch (RemoteException e) {
12036            throw e.rethrowFromSystemServer();
12037        }
12038    }
12039
12040    @Override
12041    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12042            int userId) {
12043        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12044        PackageSetting pkgSetting;
12045        final int uid = Binder.getCallingUid();
12046        enforceCrossUserPermission(uid, userId,
12047                true /* requireFullPermission */, true /* checkShell */,
12048                "setApplicationHiddenSetting for user " + userId);
12049
12050        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12051            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12052            return false;
12053        }
12054
12055        long callingId = Binder.clearCallingIdentity();
12056        try {
12057            boolean sendAdded = false;
12058            boolean sendRemoved = false;
12059            // writer
12060            synchronized (mPackages) {
12061                pkgSetting = mSettings.mPackages.get(packageName);
12062                if (pkgSetting == null) {
12063                    return false;
12064                }
12065                // Do not allow "android" is being disabled
12066                if ("android".equals(packageName)) {
12067                    Slog.w(TAG, "Cannot hide package: android");
12068                    return false;
12069                }
12070                // Only allow protected packages to hide themselves.
12071                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12072                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12073                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12074                    return false;
12075                }
12076
12077                if (pkgSetting.getHidden(userId) != hidden) {
12078                    pkgSetting.setHidden(hidden, userId);
12079                    mSettings.writePackageRestrictionsLPr(userId);
12080                    if (hidden) {
12081                        sendRemoved = true;
12082                    } else {
12083                        sendAdded = true;
12084                    }
12085                }
12086            }
12087            if (sendAdded) {
12088                sendPackageAddedForUser(packageName, pkgSetting, userId);
12089                return true;
12090            }
12091            if (sendRemoved) {
12092                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12093                        "hiding pkg");
12094                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12095                return true;
12096            }
12097        } finally {
12098            Binder.restoreCallingIdentity(callingId);
12099        }
12100        return false;
12101    }
12102
12103    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12104            int userId) {
12105        final PackageRemovedInfo info = new PackageRemovedInfo();
12106        info.removedPackage = packageName;
12107        info.removedUsers = new int[] {userId};
12108        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12109        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12110    }
12111
12112    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12113        if (pkgList.length > 0) {
12114            Bundle extras = new Bundle(1);
12115            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12116
12117            sendPackageBroadcast(
12118                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12119                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12120                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12121                    new int[] {userId});
12122        }
12123    }
12124
12125    /**
12126     * Returns true if application is not found or there was an error. Otherwise it returns
12127     * the hidden state of the package for the given user.
12128     */
12129    @Override
12130    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12131        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12132        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12133                true /* requireFullPermission */, false /* checkShell */,
12134                "getApplicationHidden for user " + userId);
12135        PackageSetting pkgSetting;
12136        long callingId = Binder.clearCallingIdentity();
12137        try {
12138            // writer
12139            synchronized (mPackages) {
12140                pkgSetting = mSettings.mPackages.get(packageName);
12141                if (pkgSetting == null) {
12142                    return true;
12143                }
12144                return pkgSetting.getHidden(userId);
12145            }
12146        } finally {
12147            Binder.restoreCallingIdentity(callingId);
12148        }
12149    }
12150
12151    /**
12152     * @hide
12153     */
12154    @Override
12155    public int installExistingPackageAsUser(String packageName, int userId) {
12156        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12157                null);
12158        PackageSetting pkgSetting;
12159        final int uid = Binder.getCallingUid();
12160        enforceCrossUserPermission(uid, userId,
12161                true /* requireFullPermission */, true /* checkShell */,
12162                "installExistingPackage for user " + userId);
12163        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12164            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12165        }
12166
12167        long callingId = Binder.clearCallingIdentity();
12168        try {
12169            boolean installed = false;
12170
12171            // writer
12172            synchronized (mPackages) {
12173                pkgSetting = mSettings.mPackages.get(packageName);
12174                if (pkgSetting == null) {
12175                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12176                }
12177                if (!pkgSetting.getInstalled(userId)) {
12178                    pkgSetting.setInstalled(true, userId);
12179                    pkgSetting.setHidden(false, userId);
12180                    mSettings.writePackageRestrictionsLPr(userId);
12181                    installed = true;
12182                }
12183            }
12184
12185            if (installed) {
12186                if (pkgSetting.pkg != null) {
12187                    synchronized (mInstallLock) {
12188                        // We don't need to freeze for a brand new install
12189                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12190                    }
12191                }
12192                sendPackageAddedForUser(packageName, pkgSetting, userId);
12193            }
12194        } finally {
12195            Binder.restoreCallingIdentity(callingId);
12196        }
12197
12198        return PackageManager.INSTALL_SUCCEEDED;
12199    }
12200
12201    boolean isUserRestricted(int userId, String restrictionKey) {
12202        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12203        if (restrictions.getBoolean(restrictionKey, false)) {
12204            Log.w(TAG, "User is restricted: " + restrictionKey);
12205            return true;
12206        }
12207        return false;
12208    }
12209
12210    @Override
12211    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12212            int userId) {
12213        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12214        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12215                true /* requireFullPermission */, true /* checkShell */,
12216                "setPackagesSuspended for user " + userId);
12217
12218        if (ArrayUtils.isEmpty(packageNames)) {
12219            return packageNames;
12220        }
12221
12222        // List of package names for whom the suspended state has changed.
12223        List<String> changedPackages = new ArrayList<>(packageNames.length);
12224        // List of package names for whom the suspended state is not set as requested in this
12225        // method.
12226        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12227        long callingId = Binder.clearCallingIdentity();
12228        try {
12229            for (int i = 0; i < packageNames.length; i++) {
12230                String packageName = packageNames[i];
12231                boolean changed = false;
12232                final int appId;
12233                synchronized (mPackages) {
12234                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12235                    if (pkgSetting == null) {
12236                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12237                                + "\". Skipping suspending/un-suspending.");
12238                        unactionedPackages.add(packageName);
12239                        continue;
12240                    }
12241                    appId = pkgSetting.appId;
12242                    if (pkgSetting.getSuspended(userId) != suspended) {
12243                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12244                            unactionedPackages.add(packageName);
12245                            continue;
12246                        }
12247                        pkgSetting.setSuspended(suspended, userId);
12248                        mSettings.writePackageRestrictionsLPr(userId);
12249                        changed = true;
12250                        changedPackages.add(packageName);
12251                    }
12252                }
12253
12254                if (changed && suspended) {
12255                    killApplication(packageName, UserHandle.getUid(userId, appId),
12256                            "suspending package");
12257                }
12258            }
12259        } finally {
12260            Binder.restoreCallingIdentity(callingId);
12261        }
12262
12263        if (!changedPackages.isEmpty()) {
12264            sendPackagesSuspendedForUser(changedPackages.toArray(
12265                    new String[changedPackages.size()]), userId, suspended);
12266        }
12267
12268        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12269    }
12270
12271    @Override
12272    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12273        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12274                true /* requireFullPermission */, false /* checkShell */,
12275                "isPackageSuspendedForUser for user " + userId);
12276        synchronized (mPackages) {
12277            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12278            if (pkgSetting == null) {
12279                throw new IllegalArgumentException("Unknown target package: " + packageName);
12280            }
12281            return pkgSetting.getSuspended(userId);
12282        }
12283    }
12284
12285    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12286        if (isPackageDeviceAdmin(packageName, userId)) {
12287            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12288                    + "\": has an active device admin");
12289            return false;
12290        }
12291
12292        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12293        if (packageName.equals(activeLauncherPackageName)) {
12294            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12295                    + "\": contains the active launcher");
12296            return false;
12297        }
12298
12299        if (packageName.equals(mRequiredInstallerPackage)) {
12300            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12301                    + "\": required for package installation");
12302            return false;
12303        }
12304
12305        if (packageName.equals(mRequiredUninstallerPackage)) {
12306            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12307                    + "\": required for package uninstallation");
12308            return false;
12309        }
12310
12311        if (packageName.equals(mRequiredVerifierPackage)) {
12312            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12313                    + "\": required for package verification");
12314            return false;
12315        }
12316
12317        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12318            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12319                    + "\": is the default dialer");
12320            return false;
12321        }
12322
12323        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12324            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12325                    + "\": protected package");
12326            return false;
12327        }
12328
12329        return true;
12330    }
12331
12332    private String getActiveLauncherPackageName(int userId) {
12333        Intent intent = new Intent(Intent.ACTION_MAIN);
12334        intent.addCategory(Intent.CATEGORY_HOME);
12335        ResolveInfo resolveInfo = resolveIntent(
12336                intent,
12337                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12338                PackageManager.MATCH_DEFAULT_ONLY,
12339                userId);
12340
12341        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12342    }
12343
12344    private String getDefaultDialerPackageName(int userId) {
12345        synchronized (mPackages) {
12346            return mSettings.getDefaultDialerPackageNameLPw(userId);
12347        }
12348    }
12349
12350    @Override
12351    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12352        mContext.enforceCallingOrSelfPermission(
12353                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12354                "Only package verification agents can verify applications");
12355
12356        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12357        final PackageVerificationResponse response = new PackageVerificationResponse(
12358                verificationCode, Binder.getCallingUid());
12359        msg.arg1 = id;
12360        msg.obj = response;
12361        mHandler.sendMessage(msg);
12362    }
12363
12364    @Override
12365    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12366            long millisecondsToDelay) {
12367        mContext.enforceCallingOrSelfPermission(
12368                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12369                "Only package verification agents can extend verification timeouts");
12370
12371        final PackageVerificationState state = mPendingVerification.get(id);
12372        final PackageVerificationResponse response = new PackageVerificationResponse(
12373                verificationCodeAtTimeout, Binder.getCallingUid());
12374
12375        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12376            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12377        }
12378        if (millisecondsToDelay < 0) {
12379            millisecondsToDelay = 0;
12380        }
12381        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12382                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12383            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12384        }
12385
12386        if ((state != null) && !state.timeoutExtended()) {
12387            state.extendTimeout();
12388
12389            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12390            msg.arg1 = id;
12391            msg.obj = response;
12392            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12393        }
12394    }
12395
12396    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12397            int verificationCode, UserHandle user) {
12398        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12399        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12400        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12401        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12402        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12403
12404        mContext.sendBroadcastAsUser(intent, user,
12405                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12406    }
12407
12408    private ComponentName matchComponentForVerifier(String packageName,
12409            List<ResolveInfo> receivers) {
12410        ActivityInfo targetReceiver = null;
12411
12412        final int NR = receivers.size();
12413        for (int i = 0; i < NR; i++) {
12414            final ResolveInfo info = receivers.get(i);
12415            if (info.activityInfo == null) {
12416                continue;
12417            }
12418
12419            if (packageName.equals(info.activityInfo.packageName)) {
12420                targetReceiver = info.activityInfo;
12421                break;
12422            }
12423        }
12424
12425        if (targetReceiver == null) {
12426            return null;
12427        }
12428
12429        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12430    }
12431
12432    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12433            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12434        if (pkgInfo.verifiers.length == 0) {
12435            return null;
12436        }
12437
12438        final int N = pkgInfo.verifiers.length;
12439        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12440        for (int i = 0; i < N; i++) {
12441            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12442
12443            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12444                    receivers);
12445            if (comp == null) {
12446                continue;
12447            }
12448
12449            final int verifierUid = getUidForVerifier(verifierInfo);
12450            if (verifierUid == -1) {
12451                continue;
12452            }
12453
12454            if (DEBUG_VERIFY) {
12455                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12456                        + " with the correct signature");
12457            }
12458            sufficientVerifiers.add(comp);
12459            verificationState.addSufficientVerifier(verifierUid);
12460        }
12461
12462        return sufficientVerifiers;
12463    }
12464
12465    private int getUidForVerifier(VerifierInfo verifierInfo) {
12466        synchronized (mPackages) {
12467            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12468            if (pkg == null) {
12469                return -1;
12470            } else if (pkg.mSignatures.length != 1) {
12471                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12472                        + " has more than one signature; ignoring");
12473                return -1;
12474            }
12475
12476            /*
12477             * If the public key of the package's signature does not match
12478             * our expected public key, then this is a different package and
12479             * we should skip.
12480             */
12481
12482            final byte[] expectedPublicKey;
12483            try {
12484                final Signature verifierSig = pkg.mSignatures[0];
12485                final PublicKey publicKey = verifierSig.getPublicKey();
12486                expectedPublicKey = publicKey.getEncoded();
12487            } catch (CertificateException e) {
12488                return -1;
12489            }
12490
12491            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12492
12493            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12494                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12495                        + " does not have the expected public key; ignoring");
12496                return -1;
12497            }
12498
12499            return pkg.applicationInfo.uid;
12500        }
12501    }
12502
12503    @Override
12504    public void finishPackageInstall(int token, boolean didLaunch) {
12505        enforceSystemOrRoot("Only the system is allowed to finish installs");
12506
12507        if (DEBUG_INSTALL) {
12508            Slog.v(TAG, "BM finishing package install for " + token);
12509        }
12510        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12511
12512        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12513        mHandler.sendMessage(msg);
12514    }
12515
12516    /**
12517     * Get the verification agent timeout.
12518     *
12519     * @return verification timeout in milliseconds
12520     */
12521    private long getVerificationTimeout() {
12522        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12523                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12524                DEFAULT_VERIFICATION_TIMEOUT);
12525    }
12526
12527    /**
12528     * Get the default verification agent response code.
12529     *
12530     * @return default verification response code
12531     */
12532    private int getDefaultVerificationResponse() {
12533        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12534                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12535                DEFAULT_VERIFICATION_RESPONSE);
12536    }
12537
12538    /**
12539     * Check whether or not package verification has been enabled.
12540     *
12541     * @return true if verification should be performed
12542     */
12543    private boolean isVerificationEnabled(int userId, int installFlags) {
12544        if (!DEFAULT_VERIFY_ENABLE) {
12545            return false;
12546        }
12547        // Ephemeral apps don't get the full verification treatment
12548        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12549            if (DEBUG_EPHEMERAL) {
12550                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12551            }
12552            return false;
12553        }
12554
12555        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12556
12557        // Check if installing from ADB
12558        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12559            // Do not run verification in a test harness environment
12560            if (ActivityManager.isRunningInTestHarness()) {
12561                return false;
12562            }
12563            if (ensureVerifyAppsEnabled) {
12564                return true;
12565            }
12566            // Check if the developer does not want package verification for ADB installs
12567            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12568                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12569                return false;
12570            }
12571        }
12572
12573        if (ensureVerifyAppsEnabled) {
12574            return true;
12575        }
12576
12577        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12578                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12579    }
12580
12581    @Override
12582    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12583            throws RemoteException {
12584        mContext.enforceCallingOrSelfPermission(
12585                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12586                "Only intentfilter verification agents can verify applications");
12587
12588        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12589        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12590                Binder.getCallingUid(), verificationCode, failedDomains);
12591        msg.arg1 = id;
12592        msg.obj = response;
12593        mHandler.sendMessage(msg);
12594    }
12595
12596    @Override
12597    public int getIntentVerificationStatus(String packageName, int userId) {
12598        synchronized (mPackages) {
12599            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12600        }
12601    }
12602
12603    @Override
12604    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12605        mContext.enforceCallingOrSelfPermission(
12606                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12607
12608        boolean result = false;
12609        synchronized (mPackages) {
12610            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12611        }
12612        if (result) {
12613            scheduleWritePackageRestrictionsLocked(userId);
12614        }
12615        return result;
12616    }
12617
12618    @Override
12619    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12620            String packageName) {
12621        synchronized (mPackages) {
12622            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12623        }
12624    }
12625
12626    @Override
12627    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12628        if (TextUtils.isEmpty(packageName)) {
12629            return ParceledListSlice.emptyList();
12630        }
12631        synchronized (mPackages) {
12632            PackageParser.Package pkg = mPackages.get(packageName);
12633            if (pkg == null || pkg.activities == null) {
12634                return ParceledListSlice.emptyList();
12635            }
12636            final int count = pkg.activities.size();
12637            ArrayList<IntentFilter> result = new ArrayList<>();
12638            for (int n=0; n<count; n++) {
12639                PackageParser.Activity activity = pkg.activities.get(n);
12640                if (activity.intents != null && activity.intents.size() > 0) {
12641                    result.addAll(activity.intents);
12642                }
12643            }
12644            return new ParceledListSlice<>(result);
12645        }
12646    }
12647
12648    @Override
12649    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12650        mContext.enforceCallingOrSelfPermission(
12651                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12652
12653        synchronized (mPackages) {
12654            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12655            if (packageName != null) {
12656                result |= updateIntentVerificationStatus(packageName,
12657                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12658                        userId);
12659                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12660                        packageName, userId);
12661            }
12662            return result;
12663        }
12664    }
12665
12666    @Override
12667    public String getDefaultBrowserPackageName(int userId) {
12668        synchronized (mPackages) {
12669            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12670        }
12671    }
12672
12673    /**
12674     * Get the "allow unknown sources" setting.
12675     *
12676     * @return the current "allow unknown sources" setting
12677     */
12678    private int getUnknownSourcesSettings() {
12679        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12680                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12681                -1);
12682    }
12683
12684    @Override
12685    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12686        final int uid = Binder.getCallingUid();
12687        // writer
12688        synchronized (mPackages) {
12689            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12690            if (targetPackageSetting == null) {
12691                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12692            }
12693
12694            PackageSetting installerPackageSetting;
12695            if (installerPackageName != null) {
12696                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12697                if (installerPackageSetting == null) {
12698                    throw new IllegalArgumentException("Unknown installer package: "
12699                            + installerPackageName);
12700                }
12701            } else {
12702                installerPackageSetting = null;
12703            }
12704
12705            Signature[] callerSignature;
12706            Object obj = mSettings.getUserIdLPr(uid);
12707            if (obj != null) {
12708                if (obj instanceof SharedUserSetting) {
12709                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12710                } else if (obj instanceof PackageSetting) {
12711                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12712                } else {
12713                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12714                }
12715            } else {
12716                throw new SecurityException("Unknown calling UID: " + uid);
12717            }
12718
12719            // Verify: can't set installerPackageName to a package that is
12720            // not signed with the same cert as the caller.
12721            if (installerPackageSetting != null) {
12722                if (compareSignatures(callerSignature,
12723                        installerPackageSetting.signatures.mSignatures)
12724                        != PackageManager.SIGNATURE_MATCH) {
12725                    throw new SecurityException(
12726                            "Caller does not have same cert as new installer package "
12727                            + installerPackageName);
12728                }
12729            }
12730
12731            // Verify: if target already has an installer package, it must
12732            // be signed with the same cert as the caller.
12733            if (targetPackageSetting.installerPackageName != null) {
12734                PackageSetting setting = mSettings.mPackages.get(
12735                        targetPackageSetting.installerPackageName);
12736                // If the currently set package isn't valid, then it's always
12737                // okay to change it.
12738                if (setting != null) {
12739                    if (compareSignatures(callerSignature,
12740                            setting.signatures.mSignatures)
12741                            != PackageManager.SIGNATURE_MATCH) {
12742                        throw new SecurityException(
12743                                "Caller does not have same cert as old installer package "
12744                                + targetPackageSetting.installerPackageName);
12745                    }
12746                }
12747            }
12748
12749            // Okay!
12750            targetPackageSetting.installerPackageName = installerPackageName;
12751            if (installerPackageName != null) {
12752                mSettings.mInstallerPackages.add(installerPackageName);
12753            }
12754            scheduleWriteSettingsLocked();
12755        }
12756    }
12757
12758    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12759        // Queue up an async operation since the package installation may take a little while.
12760        mHandler.post(new Runnable() {
12761            public void run() {
12762                mHandler.removeCallbacks(this);
12763                 // Result object to be returned
12764                PackageInstalledInfo res = new PackageInstalledInfo();
12765                res.setReturnCode(currentStatus);
12766                res.uid = -1;
12767                res.pkg = null;
12768                res.removedInfo = null;
12769                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12770                    args.doPreInstall(res.returnCode);
12771                    synchronized (mInstallLock) {
12772                        installPackageTracedLI(args, res);
12773                    }
12774                    args.doPostInstall(res.returnCode, res.uid);
12775                }
12776
12777                // A restore should be performed at this point if (a) the install
12778                // succeeded, (b) the operation is not an update, and (c) the new
12779                // package has not opted out of backup participation.
12780                final boolean update = res.removedInfo != null
12781                        && res.removedInfo.removedPackage != null;
12782                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12783                boolean doRestore = !update
12784                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12785
12786                // Set up the post-install work request bookkeeping.  This will be used
12787                // and cleaned up by the post-install event handling regardless of whether
12788                // there's a restore pass performed.  Token values are >= 1.
12789                int token;
12790                if (mNextInstallToken < 0) mNextInstallToken = 1;
12791                token = mNextInstallToken++;
12792
12793                PostInstallData data = new PostInstallData(args, res);
12794                mRunningInstalls.put(token, data);
12795                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12796
12797                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12798                    // Pass responsibility to the Backup Manager.  It will perform a
12799                    // restore if appropriate, then pass responsibility back to the
12800                    // Package Manager to run the post-install observer callbacks
12801                    // and broadcasts.
12802                    IBackupManager bm = IBackupManager.Stub.asInterface(
12803                            ServiceManager.getService(Context.BACKUP_SERVICE));
12804                    if (bm != null) {
12805                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12806                                + " to BM for possible restore");
12807                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12808                        try {
12809                            // TODO: http://b/22388012
12810                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12811                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12812                            } else {
12813                                doRestore = false;
12814                            }
12815                        } catch (RemoteException e) {
12816                            // can't happen; the backup manager is local
12817                        } catch (Exception e) {
12818                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12819                            doRestore = false;
12820                        }
12821                    } else {
12822                        Slog.e(TAG, "Backup Manager not found!");
12823                        doRestore = false;
12824                    }
12825                }
12826
12827                if (!doRestore) {
12828                    // No restore possible, or the Backup Manager was mysteriously not
12829                    // available -- just fire the post-install work request directly.
12830                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12831
12832                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12833
12834                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12835                    mHandler.sendMessage(msg);
12836                }
12837            }
12838        });
12839    }
12840
12841    /**
12842     * Callback from PackageSettings whenever an app is first transitioned out of the
12843     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12844     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12845     * here whether the app is the target of an ongoing install, and only send the
12846     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12847     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12848     * handling.
12849     */
12850    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12851        // Serialize this with the rest of the install-process message chain.  In the
12852        // restore-at-install case, this Runnable will necessarily run before the
12853        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12854        // are coherent.  In the non-restore case, the app has already completed install
12855        // and been launched through some other means, so it is not in a problematic
12856        // state for observers to see the FIRST_LAUNCH signal.
12857        mHandler.post(new Runnable() {
12858            @Override
12859            public void run() {
12860                for (int i = 0; i < mRunningInstalls.size(); i++) {
12861                    final PostInstallData data = mRunningInstalls.valueAt(i);
12862                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12863                        continue;
12864                    }
12865                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12866                        // right package; but is it for the right user?
12867                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12868                            if (userId == data.res.newUsers[uIndex]) {
12869                                if (DEBUG_BACKUP) {
12870                                    Slog.i(TAG, "Package " + pkgName
12871                                            + " being restored so deferring FIRST_LAUNCH");
12872                                }
12873                                return;
12874                            }
12875                        }
12876                    }
12877                }
12878                // didn't find it, so not being restored
12879                if (DEBUG_BACKUP) {
12880                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12881                }
12882                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12883            }
12884        });
12885    }
12886
12887    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12888        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12889                installerPkg, null, userIds);
12890    }
12891
12892    private abstract class HandlerParams {
12893        private static final int MAX_RETRIES = 4;
12894
12895        /**
12896         * Number of times startCopy() has been attempted and had a non-fatal
12897         * error.
12898         */
12899        private int mRetries = 0;
12900
12901        /** User handle for the user requesting the information or installation. */
12902        private final UserHandle mUser;
12903        String traceMethod;
12904        int traceCookie;
12905
12906        HandlerParams(UserHandle user) {
12907            mUser = user;
12908        }
12909
12910        UserHandle getUser() {
12911            return mUser;
12912        }
12913
12914        HandlerParams setTraceMethod(String traceMethod) {
12915            this.traceMethod = traceMethod;
12916            return this;
12917        }
12918
12919        HandlerParams setTraceCookie(int traceCookie) {
12920            this.traceCookie = traceCookie;
12921            return this;
12922        }
12923
12924        final boolean startCopy() {
12925            boolean res;
12926            try {
12927                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12928
12929                if (++mRetries > MAX_RETRIES) {
12930                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12931                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12932                    handleServiceError();
12933                    return false;
12934                } else {
12935                    handleStartCopy();
12936                    res = true;
12937                }
12938            } catch (RemoteException e) {
12939                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12940                mHandler.sendEmptyMessage(MCS_RECONNECT);
12941                res = false;
12942            }
12943            handleReturnCode();
12944            return res;
12945        }
12946
12947        final void serviceError() {
12948            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12949            handleServiceError();
12950            handleReturnCode();
12951        }
12952
12953        abstract void handleStartCopy() throws RemoteException;
12954        abstract void handleServiceError();
12955        abstract void handleReturnCode();
12956    }
12957
12958    class MeasureParams extends HandlerParams {
12959        private final PackageStats mStats;
12960        private boolean mSuccess;
12961
12962        private final IPackageStatsObserver mObserver;
12963
12964        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12965            super(new UserHandle(stats.userHandle));
12966            mObserver = observer;
12967            mStats = stats;
12968        }
12969
12970        @Override
12971        public String toString() {
12972            return "MeasureParams{"
12973                + Integer.toHexString(System.identityHashCode(this))
12974                + " " + mStats.packageName + "}";
12975        }
12976
12977        @Override
12978        void handleStartCopy() throws RemoteException {
12979            synchronized (mInstallLock) {
12980                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12981            }
12982
12983            if (mSuccess) {
12984                boolean mounted = false;
12985                try {
12986                    final String status = Environment.getExternalStorageState();
12987                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12988                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12989                } catch (Exception e) {
12990                }
12991
12992                if (mounted) {
12993                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12994
12995                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12996                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12997
12998                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12999                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13000
13001                    // Always subtract cache size, since it's a subdirectory
13002                    mStats.externalDataSize -= mStats.externalCacheSize;
13003
13004                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13005                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13006
13007                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13008                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13009                }
13010            }
13011        }
13012
13013        @Override
13014        void handleReturnCode() {
13015            if (mObserver != null) {
13016                try {
13017                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13018                } catch (RemoteException e) {
13019                    Slog.i(TAG, "Observer no longer exists.");
13020                }
13021            }
13022        }
13023
13024        @Override
13025        void handleServiceError() {
13026            Slog.e(TAG, "Could not measure application " + mStats.packageName
13027                            + " external storage");
13028        }
13029    }
13030
13031    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13032            throws RemoteException {
13033        long result = 0;
13034        for (File path : paths) {
13035            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13036        }
13037        return result;
13038    }
13039
13040    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13041        for (File path : paths) {
13042            try {
13043                mcs.clearDirectory(path.getAbsolutePath());
13044            } catch (RemoteException e) {
13045            }
13046        }
13047    }
13048
13049    static class OriginInfo {
13050        /**
13051         * Location where install is coming from, before it has been
13052         * copied/renamed into place. This could be a single monolithic APK
13053         * file, or a cluster directory. This location may be untrusted.
13054         */
13055        final File file;
13056        final String cid;
13057
13058        /**
13059         * Flag indicating that {@link #file} or {@link #cid} has already been
13060         * staged, meaning downstream users don't need to defensively copy the
13061         * contents.
13062         */
13063        final boolean staged;
13064
13065        /**
13066         * Flag indicating that {@link #file} or {@link #cid} is an already
13067         * installed app that is being moved.
13068         */
13069        final boolean existing;
13070
13071        final String resolvedPath;
13072        final File resolvedFile;
13073
13074        static OriginInfo fromNothing() {
13075            return new OriginInfo(null, null, false, false);
13076        }
13077
13078        static OriginInfo fromUntrustedFile(File file) {
13079            return new OriginInfo(file, null, false, false);
13080        }
13081
13082        static OriginInfo fromExistingFile(File file) {
13083            return new OriginInfo(file, null, false, true);
13084        }
13085
13086        static OriginInfo fromStagedFile(File file) {
13087            return new OriginInfo(file, null, true, false);
13088        }
13089
13090        static OriginInfo fromStagedContainer(String cid) {
13091            return new OriginInfo(null, cid, true, false);
13092        }
13093
13094        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13095            this.file = file;
13096            this.cid = cid;
13097            this.staged = staged;
13098            this.existing = existing;
13099
13100            if (cid != null) {
13101                resolvedPath = PackageHelper.getSdDir(cid);
13102                resolvedFile = new File(resolvedPath);
13103            } else if (file != null) {
13104                resolvedPath = file.getAbsolutePath();
13105                resolvedFile = file;
13106            } else {
13107                resolvedPath = null;
13108                resolvedFile = null;
13109            }
13110        }
13111    }
13112
13113    static class MoveInfo {
13114        final int moveId;
13115        final String fromUuid;
13116        final String toUuid;
13117        final String packageName;
13118        final String dataAppName;
13119        final int appId;
13120        final String seinfo;
13121        final int targetSdkVersion;
13122
13123        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13124                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13125            this.moveId = moveId;
13126            this.fromUuid = fromUuid;
13127            this.toUuid = toUuid;
13128            this.packageName = packageName;
13129            this.dataAppName = dataAppName;
13130            this.appId = appId;
13131            this.seinfo = seinfo;
13132            this.targetSdkVersion = targetSdkVersion;
13133        }
13134    }
13135
13136    static class VerificationInfo {
13137        /** A constant used to indicate that a uid value is not present. */
13138        public static final int NO_UID = -1;
13139
13140        /** URI referencing where the package was downloaded from. */
13141        final Uri originatingUri;
13142
13143        /** HTTP referrer URI associated with the originatingURI. */
13144        final Uri referrer;
13145
13146        /** UID of the application that the install request originated from. */
13147        final int originatingUid;
13148
13149        /** UID of application requesting the install */
13150        final int installerUid;
13151
13152        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13153            this.originatingUri = originatingUri;
13154            this.referrer = referrer;
13155            this.originatingUid = originatingUid;
13156            this.installerUid = installerUid;
13157        }
13158    }
13159
13160    class InstallParams extends HandlerParams {
13161        final OriginInfo origin;
13162        final MoveInfo move;
13163        final IPackageInstallObserver2 observer;
13164        int installFlags;
13165        final String installerPackageName;
13166        final String volumeUuid;
13167        private InstallArgs mArgs;
13168        private int mRet;
13169        final String packageAbiOverride;
13170        final String[] grantedRuntimePermissions;
13171        final VerificationInfo verificationInfo;
13172        final Certificate[][] certificates;
13173
13174        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13175                int installFlags, String installerPackageName, String volumeUuid,
13176                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13177                String[] grantedPermissions, Certificate[][] certificates) {
13178            super(user);
13179            this.origin = origin;
13180            this.move = move;
13181            this.observer = observer;
13182            this.installFlags = installFlags;
13183            this.installerPackageName = installerPackageName;
13184            this.volumeUuid = volumeUuid;
13185            this.verificationInfo = verificationInfo;
13186            this.packageAbiOverride = packageAbiOverride;
13187            this.grantedRuntimePermissions = grantedPermissions;
13188            this.certificates = certificates;
13189        }
13190
13191        @Override
13192        public String toString() {
13193            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13194                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13195        }
13196
13197        private int installLocationPolicy(PackageInfoLite pkgLite) {
13198            String packageName = pkgLite.packageName;
13199            int installLocation = pkgLite.installLocation;
13200            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13201            // reader
13202            synchronized (mPackages) {
13203                // Currently installed package which the new package is attempting to replace or
13204                // null if no such package is installed.
13205                PackageParser.Package installedPkg = mPackages.get(packageName);
13206                // Package which currently owns the data which the new package will own if installed.
13207                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13208                // will be null whereas dataOwnerPkg will contain information about the package
13209                // which was uninstalled while keeping its data.
13210                PackageParser.Package dataOwnerPkg = installedPkg;
13211                if (dataOwnerPkg  == null) {
13212                    PackageSetting ps = mSettings.mPackages.get(packageName);
13213                    if (ps != null) {
13214                        dataOwnerPkg = ps.pkg;
13215                    }
13216                }
13217
13218                if (dataOwnerPkg != null) {
13219                    // If installed, the package will get access to data left on the device by its
13220                    // predecessor. As a security measure, this is permited only if this is not a
13221                    // version downgrade or if the predecessor package is marked as debuggable and
13222                    // a downgrade is explicitly requested.
13223                    //
13224                    // On debuggable platform builds, downgrades are permitted even for
13225                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13226                    // not offer security guarantees and thus it's OK to disable some security
13227                    // mechanisms to make debugging/testing easier on those builds. However, even on
13228                    // debuggable builds downgrades of packages are permitted only if requested via
13229                    // installFlags. This is because we aim to keep the behavior of debuggable
13230                    // platform builds as close as possible to the behavior of non-debuggable
13231                    // platform builds.
13232                    final boolean downgradeRequested =
13233                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13234                    final boolean packageDebuggable =
13235                                (dataOwnerPkg.applicationInfo.flags
13236                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13237                    final boolean downgradePermitted =
13238                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13239                    if (!downgradePermitted) {
13240                        try {
13241                            checkDowngrade(dataOwnerPkg, pkgLite);
13242                        } catch (PackageManagerException e) {
13243                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13244                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13245                        }
13246                    }
13247                }
13248
13249                if (installedPkg != null) {
13250                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13251                        // Check for updated system application.
13252                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13253                            if (onSd) {
13254                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13255                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13256                            }
13257                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13258                        } else {
13259                            if (onSd) {
13260                                // Install flag overrides everything.
13261                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13262                            }
13263                            // If current upgrade specifies particular preference
13264                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13265                                // Application explicitly specified internal.
13266                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13267                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13268                                // App explictly prefers external. Let policy decide
13269                            } else {
13270                                // Prefer previous location
13271                                if (isExternal(installedPkg)) {
13272                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13273                                }
13274                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13275                            }
13276                        }
13277                    } else {
13278                        // Invalid install. Return error code
13279                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13280                    }
13281                }
13282            }
13283            // All the special cases have been taken care of.
13284            // Return result based on recommended install location.
13285            if (onSd) {
13286                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13287            }
13288            return pkgLite.recommendedInstallLocation;
13289        }
13290
13291        /*
13292         * Invoke remote method to get package information and install
13293         * location values. Override install location based on default
13294         * policy if needed and then create install arguments based
13295         * on the install location.
13296         */
13297        public void handleStartCopy() throws RemoteException {
13298            int ret = PackageManager.INSTALL_SUCCEEDED;
13299
13300            // If we're already staged, we've firmly committed to an install location
13301            if (origin.staged) {
13302                if (origin.file != null) {
13303                    installFlags |= PackageManager.INSTALL_INTERNAL;
13304                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13305                } else if (origin.cid != null) {
13306                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13307                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13308                } else {
13309                    throw new IllegalStateException("Invalid stage location");
13310                }
13311            }
13312
13313            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13314            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13315            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13316            PackageInfoLite pkgLite = null;
13317
13318            if (onInt && onSd) {
13319                // Check if both bits are set.
13320                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13321                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13322            } else if (onSd && ephemeral) {
13323                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13324                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13325            } else {
13326                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13327                        packageAbiOverride);
13328
13329                if (DEBUG_EPHEMERAL && ephemeral) {
13330                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13331                }
13332
13333                /*
13334                 * If we have too little free space, try to free cache
13335                 * before giving up.
13336                 */
13337                if (!origin.staged && pkgLite.recommendedInstallLocation
13338                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13339                    // TODO: focus freeing disk space on the target device
13340                    final StorageManager storage = StorageManager.from(mContext);
13341                    final long lowThreshold = storage.getStorageLowBytes(
13342                            Environment.getDataDirectory());
13343
13344                    final long sizeBytes = mContainerService.calculateInstalledSize(
13345                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13346
13347                    try {
13348                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13349                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13350                                installFlags, packageAbiOverride);
13351                    } catch (InstallerException e) {
13352                        Slog.w(TAG, "Failed to free cache", e);
13353                    }
13354
13355                    /*
13356                     * The cache free must have deleted the file we
13357                     * downloaded to install.
13358                     *
13359                     * TODO: fix the "freeCache" call to not delete
13360                     *       the file we care about.
13361                     */
13362                    if (pkgLite.recommendedInstallLocation
13363                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13364                        pkgLite.recommendedInstallLocation
13365                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13366                    }
13367                }
13368            }
13369
13370            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13371                int loc = pkgLite.recommendedInstallLocation;
13372                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13373                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13374                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13375                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13376                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13377                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13378                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13379                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13380                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13381                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13382                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13383                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13384                } else {
13385                    // Override with defaults if needed.
13386                    loc = installLocationPolicy(pkgLite);
13387                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13388                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13389                    } else if (!onSd && !onInt) {
13390                        // Override install location with flags
13391                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13392                            // Set the flag to install on external media.
13393                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13394                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13395                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13396                            if (DEBUG_EPHEMERAL) {
13397                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13398                            }
13399                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13400                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13401                                    |PackageManager.INSTALL_INTERNAL);
13402                        } else {
13403                            // Make sure the flag for installing on external
13404                            // media is unset
13405                            installFlags |= PackageManager.INSTALL_INTERNAL;
13406                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13407                        }
13408                    }
13409                }
13410            }
13411
13412            final InstallArgs args = createInstallArgs(this);
13413            mArgs = args;
13414
13415            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13416                // TODO: http://b/22976637
13417                // Apps installed for "all" users use the device owner to verify the app
13418                UserHandle verifierUser = getUser();
13419                if (verifierUser == UserHandle.ALL) {
13420                    verifierUser = UserHandle.SYSTEM;
13421                }
13422
13423                /*
13424                 * Determine if we have any installed package verifiers. If we
13425                 * do, then we'll defer to them to verify the packages.
13426                 */
13427                final int requiredUid = mRequiredVerifierPackage == null ? -1
13428                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13429                                verifierUser.getIdentifier());
13430                if (!origin.existing && requiredUid != -1
13431                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13432                    final Intent verification = new Intent(
13433                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13434                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13435                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13436                            PACKAGE_MIME_TYPE);
13437                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13438
13439                    // Query all live verifiers based on current user state
13440                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13441                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13442
13443                    if (DEBUG_VERIFY) {
13444                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13445                                + verification.toString() + " with " + pkgLite.verifiers.length
13446                                + " optional verifiers");
13447                    }
13448
13449                    final int verificationId = mPendingVerificationToken++;
13450
13451                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13452
13453                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13454                            installerPackageName);
13455
13456                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13457                            installFlags);
13458
13459                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13460                            pkgLite.packageName);
13461
13462                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13463                            pkgLite.versionCode);
13464
13465                    if (verificationInfo != null) {
13466                        if (verificationInfo.originatingUri != null) {
13467                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13468                                    verificationInfo.originatingUri);
13469                        }
13470                        if (verificationInfo.referrer != null) {
13471                            verification.putExtra(Intent.EXTRA_REFERRER,
13472                                    verificationInfo.referrer);
13473                        }
13474                        if (verificationInfo.originatingUid >= 0) {
13475                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13476                                    verificationInfo.originatingUid);
13477                        }
13478                        if (verificationInfo.installerUid >= 0) {
13479                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13480                                    verificationInfo.installerUid);
13481                        }
13482                    }
13483
13484                    final PackageVerificationState verificationState = new PackageVerificationState(
13485                            requiredUid, args);
13486
13487                    mPendingVerification.append(verificationId, verificationState);
13488
13489                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13490                            receivers, verificationState);
13491
13492                    /*
13493                     * If any sufficient verifiers were listed in the package
13494                     * manifest, attempt to ask them.
13495                     */
13496                    if (sufficientVerifiers != null) {
13497                        final int N = sufficientVerifiers.size();
13498                        if (N == 0) {
13499                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13500                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13501                        } else {
13502                            for (int i = 0; i < N; i++) {
13503                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13504
13505                                final Intent sufficientIntent = new Intent(verification);
13506                                sufficientIntent.setComponent(verifierComponent);
13507                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13508                            }
13509                        }
13510                    }
13511
13512                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13513                            mRequiredVerifierPackage, receivers);
13514                    if (ret == PackageManager.INSTALL_SUCCEEDED
13515                            && mRequiredVerifierPackage != null) {
13516                        Trace.asyncTraceBegin(
13517                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13518                        /*
13519                         * Send the intent to the required verification agent,
13520                         * but only start the verification timeout after the
13521                         * target BroadcastReceivers have run.
13522                         */
13523                        verification.setComponent(requiredVerifierComponent);
13524                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13525                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13526                                new BroadcastReceiver() {
13527                                    @Override
13528                                    public void onReceive(Context context, Intent intent) {
13529                                        final Message msg = mHandler
13530                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13531                                        msg.arg1 = verificationId;
13532                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13533                                    }
13534                                }, null, 0, null, null);
13535
13536                        /*
13537                         * We don't want the copy to proceed until verification
13538                         * succeeds, so null out this field.
13539                         */
13540                        mArgs = null;
13541                    }
13542                } else {
13543                    /*
13544                     * No package verification is enabled, so immediately start
13545                     * the remote call to initiate copy using temporary file.
13546                     */
13547                    ret = args.copyApk(mContainerService, true);
13548                }
13549            }
13550
13551            mRet = ret;
13552        }
13553
13554        @Override
13555        void handleReturnCode() {
13556            // If mArgs is null, then MCS couldn't be reached. When it
13557            // reconnects, it will try again to install. At that point, this
13558            // will succeed.
13559            if (mArgs != null) {
13560                processPendingInstall(mArgs, mRet);
13561            }
13562        }
13563
13564        @Override
13565        void handleServiceError() {
13566            mArgs = createInstallArgs(this);
13567            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13568        }
13569
13570        public boolean isForwardLocked() {
13571            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13572        }
13573    }
13574
13575    /**
13576     * Used during creation of InstallArgs
13577     *
13578     * @param installFlags package installation flags
13579     * @return true if should be installed on external storage
13580     */
13581    private static boolean installOnExternalAsec(int installFlags) {
13582        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13583            return false;
13584        }
13585        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13586            return true;
13587        }
13588        return false;
13589    }
13590
13591    /**
13592     * Used during creation of InstallArgs
13593     *
13594     * @param installFlags package installation flags
13595     * @return true if should be installed as forward locked
13596     */
13597    private static boolean installForwardLocked(int installFlags) {
13598        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13599    }
13600
13601    private InstallArgs createInstallArgs(InstallParams params) {
13602        if (params.move != null) {
13603            return new MoveInstallArgs(params);
13604        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13605            return new AsecInstallArgs(params);
13606        } else {
13607            return new FileInstallArgs(params);
13608        }
13609    }
13610
13611    /**
13612     * Create args that describe an existing installed package. Typically used
13613     * when cleaning up old installs, or used as a move source.
13614     */
13615    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13616            String resourcePath, String[] instructionSets) {
13617        final boolean isInAsec;
13618        if (installOnExternalAsec(installFlags)) {
13619            /* Apps on SD card are always in ASEC containers. */
13620            isInAsec = true;
13621        } else if (installForwardLocked(installFlags)
13622                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13623            /*
13624             * Forward-locked apps are only in ASEC containers if they're the
13625             * new style
13626             */
13627            isInAsec = true;
13628        } else {
13629            isInAsec = false;
13630        }
13631
13632        if (isInAsec) {
13633            return new AsecInstallArgs(codePath, instructionSets,
13634                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13635        } else {
13636            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13637        }
13638    }
13639
13640    static abstract class InstallArgs {
13641        /** @see InstallParams#origin */
13642        final OriginInfo origin;
13643        /** @see InstallParams#move */
13644        final MoveInfo move;
13645
13646        final IPackageInstallObserver2 observer;
13647        // Always refers to PackageManager flags only
13648        final int installFlags;
13649        final String installerPackageName;
13650        final String volumeUuid;
13651        final UserHandle user;
13652        final String abiOverride;
13653        final String[] installGrantPermissions;
13654        /** If non-null, drop an async trace when the install completes */
13655        final String traceMethod;
13656        final int traceCookie;
13657        final Certificate[][] certificates;
13658
13659        // The list of instruction sets supported by this app. This is currently
13660        // only used during the rmdex() phase to clean up resources. We can get rid of this
13661        // if we move dex files under the common app path.
13662        /* nullable */ String[] instructionSets;
13663
13664        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13665                int installFlags, String installerPackageName, String volumeUuid,
13666                UserHandle user, String[] instructionSets,
13667                String abiOverride, String[] installGrantPermissions,
13668                String traceMethod, int traceCookie, Certificate[][] certificates) {
13669            this.origin = origin;
13670            this.move = move;
13671            this.installFlags = installFlags;
13672            this.observer = observer;
13673            this.installerPackageName = installerPackageName;
13674            this.volumeUuid = volumeUuid;
13675            this.user = user;
13676            this.instructionSets = instructionSets;
13677            this.abiOverride = abiOverride;
13678            this.installGrantPermissions = installGrantPermissions;
13679            this.traceMethod = traceMethod;
13680            this.traceCookie = traceCookie;
13681            this.certificates = certificates;
13682        }
13683
13684        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13685        abstract int doPreInstall(int status);
13686
13687        /**
13688         * Rename package into final resting place. All paths on the given
13689         * scanned package should be updated to reflect the rename.
13690         */
13691        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13692        abstract int doPostInstall(int status, int uid);
13693
13694        /** @see PackageSettingBase#codePathString */
13695        abstract String getCodePath();
13696        /** @see PackageSettingBase#resourcePathString */
13697        abstract String getResourcePath();
13698
13699        // Need installer lock especially for dex file removal.
13700        abstract void cleanUpResourcesLI();
13701        abstract boolean doPostDeleteLI(boolean delete);
13702
13703        /**
13704         * Called before the source arguments are copied. This is used mostly
13705         * for MoveParams when it needs to read the source file to put it in the
13706         * destination.
13707         */
13708        int doPreCopy() {
13709            return PackageManager.INSTALL_SUCCEEDED;
13710        }
13711
13712        /**
13713         * Called after the source arguments are copied. This is used mostly for
13714         * MoveParams when it needs to read the source file to put it in the
13715         * destination.
13716         */
13717        int doPostCopy(int uid) {
13718            return PackageManager.INSTALL_SUCCEEDED;
13719        }
13720
13721        protected boolean isFwdLocked() {
13722            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13723        }
13724
13725        protected boolean isExternalAsec() {
13726            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13727        }
13728
13729        protected boolean isEphemeral() {
13730            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13731        }
13732
13733        UserHandle getUser() {
13734            return user;
13735        }
13736    }
13737
13738    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13739        if (!allCodePaths.isEmpty()) {
13740            if (instructionSets == null) {
13741                throw new IllegalStateException("instructionSet == null");
13742            }
13743            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13744            for (String codePath : allCodePaths) {
13745                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13746                    try {
13747                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13748                    } catch (InstallerException ignored) {
13749                    }
13750                }
13751            }
13752        }
13753    }
13754
13755    /**
13756     * Logic to handle installation of non-ASEC applications, including copying
13757     * and renaming logic.
13758     */
13759    class FileInstallArgs extends InstallArgs {
13760        private File codeFile;
13761        private File resourceFile;
13762
13763        // Example topology:
13764        // /data/app/com.example/base.apk
13765        // /data/app/com.example/split_foo.apk
13766        // /data/app/com.example/lib/arm/libfoo.so
13767        // /data/app/com.example/lib/arm64/libfoo.so
13768        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13769
13770        /** New install */
13771        FileInstallArgs(InstallParams params) {
13772            super(params.origin, params.move, params.observer, params.installFlags,
13773                    params.installerPackageName, params.volumeUuid,
13774                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13775                    params.grantedRuntimePermissions,
13776                    params.traceMethod, params.traceCookie, params.certificates);
13777            if (isFwdLocked()) {
13778                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13779            }
13780        }
13781
13782        /** Existing install */
13783        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13784            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13785                    null, null, null, 0, null /*certificates*/);
13786            this.codeFile = (codePath != null) ? new File(codePath) : null;
13787            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13788        }
13789
13790        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13791            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13792            try {
13793                return doCopyApk(imcs, temp);
13794            } finally {
13795                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13796            }
13797        }
13798
13799        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13800            if (origin.staged) {
13801                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13802                codeFile = origin.file;
13803                resourceFile = origin.file;
13804                return PackageManager.INSTALL_SUCCEEDED;
13805            }
13806
13807            try {
13808                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13809                final File tempDir =
13810                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13811                codeFile = tempDir;
13812                resourceFile = tempDir;
13813            } catch (IOException e) {
13814                Slog.w(TAG, "Failed to create copy file: " + e);
13815                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13816            }
13817
13818            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13819                @Override
13820                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13821                    if (!FileUtils.isValidExtFilename(name)) {
13822                        throw new IllegalArgumentException("Invalid filename: " + name);
13823                    }
13824                    try {
13825                        final File file = new File(codeFile, name);
13826                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13827                                O_RDWR | O_CREAT, 0644);
13828                        Os.chmod(file.getAbsolutePath(), 0644);
13829                        return new ParcelFileDescriptor(fd);
13830                    } catch (ErrnoException e) {
13831                        throw new RemoteException("Failed to open: " + e.getMessage());
13832                    }
13833                }
13834            };
13835
13836            int ret = PackageManager.INSTALL_SUCCEEDED;
13837            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13838            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13839                Slog.e(TAG, "Failed to copy package");
13840                return ret;
13841            }
13842
13843            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13844            NativeLibraryHelper.Handle handle = null;
13845            try {
13846                handle = NativeLibraryHelper.Handle.create(codeFile);
13847                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13848                        abiOverride);
13849            } catch (IOException e) {
13850                Slog.e(TAG, "Copying native libraries failed", e);
13851                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13852            } finally {
13853                IoUtils.closeQuietly(handle);
13854            }
13855
13856            return ret;
13857        }
13858
13859        int doPreInstall(int status) {
13860            if (status != PackageManager.INSTALL_SUCCEEDED) {
13861                cleanUp();
13862            }
13863            return status;
13864        }
13865
13866        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13867            if (status != PackageManager.INSTALL_SUCCEEDED) {
13868                cleanUp();
13869                return false;
13870            }
13871
13872            final File targetDir = codeFile.getParentFile();
13873            final File beforeCodeFile = codeFile;
13874            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13875
13876            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13877            try {
13878                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13879            } catch (ErrnoException e) {
13880                Slog.w(TAG, "Failed to rename", e);
13881                return false;
13882            }
13883
13884            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13885                Slog.w(TAG, "Failed to restorecon");
13886                return false;
13887            }
13888
13889            // Reflect the rename internally
13890            codeFile = afterCodeFile;
13891            resourceFile = afterCodeFile;
13892
13893            // Reflect the rename in scanned details
13894            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13895            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13896                    afterCodeFile, pkg.baseCodePath));
13897            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13898                    afterCodeFile, pkg.splitCodePaths));
13899
13900            // Reflect the rename in app info
13901            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13902            pkg.setApplicationInfoCodePath(pkg.codePath);
13903            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13904            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13905            pkg.setApplicationInfoResourcePath(pkg.codePath);
13906            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13907            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13908
13909            return true;
13910        }
13911
13912        int doPostInstall(int status, int uid) {
13913            if (status != PackageManager.INSTALL_SUCCEEDED) {
13914                cleanUp();
13915            }
13916            return status;
13917        }
13918
13919        @Override
13920        String getCodePath() {
13921            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13922        }
13923
13924        @Override
13925        String getResourcePath() {
13926            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13927        }
13928
13929        private boolean cleanUp() {
13930            if (codeFile == null || !codeFile.exists()) {
13931                return false;
13932            }
13933
13934            removeCodePathLI(codeFile);
13935
13936            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13937                resourceFile.delete();
13938            }
13939
13940            return true;
13941        }
13942
13943        void cleanUpResourcesLI() {
13944            // Try enumerating all code paths before deleting
13945            List<String> allCodePaths = Collections.EMPTY_LIST;
13946            if (codeFile != null && codeFile.exists()) {
13947                try {
13948                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13949                    allCodePaths = pkg.getAllCodePaths();
13950                } catch (PackageParserException e) {
13951                    // Ignored; we tried our best
13952                }
13953            }
13954
13955            cleanUp();
13956            removeDexFiles(allCodePaths, instructionSets);
13957        }
13958
13959        boolean doPostDeleteLI(boolean delete) {
13960            // XXX err, shouldn't we respect the delete flag?
13961            cleanUpResourcesLI();
13962            return true;
13963        }
13964    }
13965
13966    private boolean isAsecExternal(String cid) {
13967        final String asecPath = PackageHelper.getSdFilesystem(cid);
13968        return !asecPath.startsWith(mAsecInternalPath);
13969    }
13970
13971    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13972            PackageManagerException {
13973        if (copyRet < 0) {
13974            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13975                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13976                throw new PackageManagerException(copyRet, message);
13977            }
13978        }
13979    }
13980
13981    /**
13982     * Extract the StorageManagerService "container ID" from the full code path of an
13983     * .apk.
13984     */
13985    static String cidFromCodePath(String fullCodePath) {
13986        int eidx = fullCodePath.lastIndexOf("/");
13987        String subStr1 = fullCodePath.substring(0, eidx);
13988        int sidx = subStr1.lastIndexOf("/");
13989        return subStr1.substring(sidx+1, eidx);
13990    }
13991
13992    /**
13993     * Logic to handle installation of ASEC applications, including copying and
13994     * renaming logic.
13995     */
13996    class AsecInstallArgs extends InstallArgs {
13997        static final String RES_FILE_NAME = "pkg.apk";
13998        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13999
14000        String cid;
14001        String packagePath;
14002        String resourcePath;
14003
14004        /** New install */
14005        AsecInstallArgs(InstallParams params) {
14006            super(params.origin, params.move, params.observer, params.installFlags,
14007                    params.installerPackageName, params.volumeUuid,
14008                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14009                    params.grantedRuntimePermissions,
14010                    params.traceMethod, params.traceCookie, params.certificates);
14011        }
14012
14013        /** Existing install */
14014        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14015                        boolean isExternal, boolean isForwardLocked) {
14016            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14017              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14018                    instructionSets, null, null, null, 0, null /*certificates*/);
14019            // Hackily pretend we're still looking at a full code path
14020            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14021                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14022            }
14023
14024            // Extract cid from fullCodePath
14025            int eidx = fullCodePath.lastIndexOf("/");
14026            String subStr1 = fullCodePath.substring(0, eidx);
14027            int sidx = subStr1.lastIndexOf("/");
14028            cid = subStr1.substring(sidx+1, eidx);
14029            setMountPath(subStr1);
14030        }
14031
14032        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14033            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14034              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14035                    instructionSets, null, null, null, 0, null /*certificates*/);
14036            this.cid = cid;
14037            setMountPath(PackageHelper.getSdDir(cid));
14038        }
14039
14040        void createCopyFile() {
14041            cid = mInstallerService.allocateExternalStageCidLegacy();
14042        }
14043
14044        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14045            if (origin.staged && origin.cid != null) {
14046                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14047                cid = origin.cid;
14048                setMountPath(PackageHelper.getSdDir(cid));
14049                return PackageManager.INSTALL_SUCCEEDED;
14050            }
14051
14052            if (temp) {
14053                createCopyFile();
14054            } else {
14055                /*
14056                 * Pre-emptively destroy the container since it's destroyed if
14057                 * copying fails due to it existing anyway.
14058                 */
14059                PackageHelper.destroySdDir(cid);
14060            }
14061
14062            final String newMountPath = imcs.copyPackageToContainer(
14063                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14064                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14065
14066            if (newMountPath != null) {
14067                setMountPath(newMountPath);
14068                return PackageManager.INSTALL_SUCCEEDED;
14069            } else {
14070                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14071            }
14072        }
14073
14074        @Override
14075        String getCodePath() {
14076            return packagePath;
14077        }
14078
14079        @Override
14080        String getResourcePath() {
14081            return resourcePath;
14082        }
14083
14084        int doPreInstall(int status) {
14085            if (status != PackageManager.INSTALL_SUCCEEDED) {
14086                // Destroy container
14087                PackageHelper.destroySdDir(cid);
14088            } else {
14089                boolean mounted = PackageHelper.isContainerMounted(cid);
14090                if (!mounted) {
14091                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14092                            Process.SYSTEM_UID);
14093                    if (newMountPath != null) {
14094                        setMountPath(newMountPath);
14095                    } else {
14096                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14097                    }
14098                }
14099            }
14100            return status;
14101        }
14102
14103        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14104            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14105            String newMountPath = null;
14106            if (PackageHelper.isContainerMounted(cid)) {
14107                // Unmount the container
14108                if (!PackageHelper.unMountSdDir(cid)) {
14109                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14110                    return false;
14111                }
14112            }
14113            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14114                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14115                        " which might be stale. Will try to clean up.");
14116                // Clean up the stale container and proceed to recreate.
14117                if (!PackageHelper.destroySdDir(newCacheId)) {
14118                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14119                    return false;
14120                }
14121                // Successfully cleaned up stale container. Try to rename again.
14122                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14123                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14124                            + " inspite of cleaning it up.");
14125                    return false;
14126                }
14127            }
14128            if (!PackageHelper.isContainerMounted(newCacheId)) {
14129                Slog.w(TAG, "Mounting container " + newCacheId);
14130                newMountPath = PackageHelper.mountSdDir(newCacheId,
14131                        getEncryptKey(), Process.SYSTEM_UID);
14132            } else {
14133                newMountPath = PackageHelper.getSdDir(newCacheId);
14134            }
14135            if (newMountPath == null) {
14136                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14137                return false;
14138            }
14139            Log.i(TAG, "Succesfully renamed " + cid +
14140                    " to " + newCacheId +
14141                    " at new path: " + newMountPath);
14142            cid = newCacheId;
14143
14144            final File beforeCodeFile = new File(packagePath);
14145            setMountPath(newMountPath);
14146            final File afterCodeFile = new File(packagePath);
14147
14148            // Reflect the rename in scanned details
14149            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14150            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14151                    afterCodeFile, pkg.baseCodePath));
14152            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14153                    afterCodeFile, pkg.splitCodePaths));
14154
14155            // Reflect the rename in app info
14156            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14157            pkg.setApplicationInfoCodePath(pkg.codePath);
14158            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14159            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14160            pkg.setApplicationInfoResourcePath(pkg.codePath);
14161            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14162            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14163
14164            return true;
14165        }
14166
14167        private void setMountPath(String mountPath) {
14168            final File mountFile = new File(mountPath);
14169
14170            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14171            if (monolithicFile.exists()) {
14172                packagePath = monolithicFile.getAbsolutePath();
14173                if (isFwdLocked()) {
14174                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14175                } else {
14176                    resourcePath = packagePath;
14177                }
14178            } else {
14179                packagePath = mountFile.getAbsolutePath();
14180                resourcePath = packagePath;
14181            }
14182        }
14183
14184        int doPostInstall(int status, int uid) {
14185            if (status != PackageManager.INSTALL_SUCCEEDED) {
14186                cleanUp();
14187            } else {
14188                final int groupOwner;
14189                final String protectedFile;
14190                if (isFwdLocked()) {
14191                    groupOwner = UserHandle.getSharedAppGid(uid);
14192                    protectedFile = RES_FILE_NAME;
14193                } else {
14194                    groupOwner = -1;
14195                    protectedFile = null;
14196                }
14197
14198                if (uid < Process.FIRST_APPLICATION_UID
14199                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14200                    Slog.e(TAG, "Failed to finalize " + cid);
14201                    PackageHelper.destroySdDir(cid);
14202                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14203                }
14204
14205                boolean mounted = PackageHelper.isContainerMounted(cid);
14206                if (!mounted) {
14207                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14208                }
14209            }
14210            return status;
14211        }
14212
14213        private void cleanUp() {
14214            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14215
14216            // Destroy secure container
14217            PackageHelper.destroySdDir(cid);
14218        }
14219
14220        private List<String> getAllCodePaths() {
14221            final File codeFile = new File(getCodePath());
14222            if (codeFile != null && codeFile.exists()) {
14223                try {
14224                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14225                    return pkg.getAllCodePaths();
14226                } catch (PackageParserException e) {
14227                    // Ignored; we tried our best
14228                }
14229            }
14230            return Collections.EMPTY_LIST;
14231        }
14232
14233        void cleanUpResourcesLI() {
14234            // Enumerate all code paths before deleting
14235            cleanUpResourcesLI(getAllCodePaths());
14236        }
14237
14238        private void cleanUpResourcesLI(List<String> allCodePaths) {
14239            cleanUp();
14240            removeDexFiles(allCodePaths, instructionSets);
14241        }
14242
14243        String getPackageName() {
14244            return getAsecPackageName(cid);
14245        }
14246
14247        boolean doPostDeleteLI(boolean delete) {
14248            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14249            final List<String> allCodePaths = getAllCodePaths();
14250            boolean mounted = PackageHelper.isContainerMounted(cid);
14251            if (mounted) {
14252                // Unmount first
14253                if (PackageHelper.unMountSdDir(cid)) {
14254                    mounted = false;
14255                }
14256            }
14257            if (!mounted && delete) {
14258                cleanUpResourcesLI(allCodePaths);
14259            }
14260            return !mounted;
14261        }
14262
14263        @Override
14264        int doPreCopy() {
14265            if (isFwdLocked()) {
14266                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14267                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14268                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14269                }
14270            }
14271
14272            return PackageManager.INSTALL_SUCCEEDED;
14273        }
14274
14275        @Override
14276        int doPostCopy(int uid) {
14277            if (isFwdLocked()) {
14278                if (uid < Process.FIRST_APPLICATION_UID
14279                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14280                                RES_FILE_NAME)) {
14281                    Slog.e(TAG, "Failed to finalize " + cid);
14282                    PackageHelper.destroySdDir(cid);
14283                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14284                }
14285            }
14286
14287            return PackageManager.INSTALL_SUCCEEDED;
14288        }
14289    }
14290
14291    /**
14292     * Logic to handle movement of existing installed applications.
14293     */
14294    class MoveInstallArgs extends InstallArgs {
14295        private File codeFile;
14296        private File resourceFile;
14297
14298        /** New install */
14299        MoveInstallArgs(InstallParams params) {
14300            super(params.origin, params.move, params.observer, params.installFlags,
14301                    params.installerPackageName, params.volumeUuid,
14302                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14303                    params.grantedRuntimePermissions,
14304                    params.traceMethod, params.traceCookie, params.certificates);
14305        }
14306
14307        int copyApk(IMediaContainerService imcs, boolean temp) {
14308            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14309                    + move.fromUuid + " to " + move.toUuid);
14310            synchronized (mInstaller) {
14311                try {
14312                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14313                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14314                } catch (InstallerException e) {
14315                    Slog.w(TAG, "Failed to move app", e);
14316                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14317                }
14318            }
14319
14320            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14321            resourceFile = codeFile;
14322            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14323
14324            return PackageManager.INSTALL_SUCCEEDED;
14325        }
14326
14327        int doPreInstall(int status) {
14328            if (status != PackageManager.INSTALL_SUCCEEDED) {
14329                cleanUp(move.toUuid);
14330            }
14331            return status;
14332        }
14333
14334        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14335            if (status != PackageManager.INSTALL_SUCCEEDED) {
14336                cleanUp(move.toUuid);
14337                return false;
14338            }
14339
14340            // Reflect the move in app info
14341            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14342            pkg.setApplicationInfoCodePath(pkg.codePath);
14343            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14344            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14345            pkg.setApplicationInfoResourcePath(pkg.codePath);
14346            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14347            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14348
14349            return true;
14350        }
14351
14352        int doPostInstall(int status, int uid) {
14353            if (status == PackageManager.INSTALL_SUCCEEDED) {
14354                cleanUp(move.fromUuid);
14355            } else {
14356                cleanUp(move.toUuid);
14357            }
14358            return status;
14359        }
14360
14361        @Override
14362        String getCodePath() {
14363            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14364        }
14365
14366        @Override
14367        String getResourcePath() {
14368            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14369        }
14370
14371        private boolean cleanUp(String volumeUuid) {
14372            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14373                    move.dataAppName);
14374            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14375            final int[] userIds = sUserManager.getUserIds();
14376            synchronized (mInstallLock) {
14377                // Clean up both app data and code
14378                // All package moves are frozen until finished
14379                for (int userId : userIds) {
14380                    try {
14381                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14382                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14383                    } catch (InstallerException e) {
14384                        Slog.w(TAG, String.valueOf(e));
14385                    }
14386                }
14387                removeCodePathLI(codeFile);
14388            }
14389            return true;
14390        }
14391
14392        void cleanUpResourcesLI() {
14393            throw new UnsupportedOperationException();
14394        }
14395
14396        boolean doPostDeleteLI(boolean delete) {
14397            throw new UnsupportedOperationException();
14398        }
14399    }
14400
14401    static String getAsecPackageName(String packageCid) {
14402        int idx = packageCid.lastIndexOf("-");
14403        if (idx == -1) {
14404            return packageCid;
14405        }
14406        return packageCid.substring(0, idx);
14407    }
14408
14409    // Utility method used to create code paths based on package name and available index.
14410    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14411        String idxStr = "";
14412        int idx = 1;
14413        // Fall back to default value of idx=1 if prefix is not
14414        // part of oldCodePath
14415        if (oldCodePath != null) {
14416            String subStr = oldCodePath;
14417            // Drop the suffix right away
14418            if (suffix != null && subStr.endsWith(suffix)) {
14419                subStr = subStr.substring(0, subStr.length() - suffix.length());
14420            }
14421            // If oldCodePath already contains prefix find out the
14422            // ending index to either increment or decrement.
14423            int sidx = subStr.lastIndexOf(prefix);
14424            if (sidx != -1) {
14425                subStr = subStr.substring(sidx + prefix.length());
14426                if (subStr != null) {
14427                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14428                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14429                    }
14430                    try {
14431                        idx = Integer.parseInt(subStr);
14432                        if (idx <= 1) {
14433                            idx++;
14434                        } else {
14435                            idx--;
14436                        }
14437                    } catch(NumberFormatException e) {
14438                    }
14439                }
14440            }
14441        }
14442        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14443        return prefix + idxStr;
14444    }
14445
14446    private File getNextCodePath(File targetDir, String packageName) {
14447        File result;
14448        SecureRandom random = new SecureRandom();
14449        byte[] bytes = new byte[16];
14450        do {
14451            random.nextBytes(bytes);
14452            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14453            result = new File(targetDir, packageName + "-" + suffix);
14454        } while (result.exists());
14455        return result;
14456    }
14457
14458    // Utility method that returns the relative package path with respect
14459    // to the installation directory. Like say for /data/data/com.test-1.apk
14460    // string com.test-1 is returned.
14461    static String deriveCodePathName(String codePath) {
14462        if (codePath == null) {
14463            return null;
14464        }
14465        final File codeFile = new File(codePath);
14466        final String name = codeFile.getName();
14467        if (codeFile.isDirectory()) {
14468            return name;
14469        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14470            final int lastDot = name.lastIndexOf('.');
14471            return name.substring(0, lastDot);
14472        } else {
14473            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14474            return null;
14475        }
14476    }
14477
14478    static class PackageInstalledInfo {
14479        String name;
14480        int uid;
14481        // The set of users that originally had this package installed.
14482        int[] origUsers;
14483        // The set of users that now have this package installed.
14484        int[] newUsers;
14485        PackageParser.Package pkg;
14486        int returnCode;
14487        String returnMsg;
14488        PackageRemovedInfo removedInfo;
14489        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14490
14491        public void setError(int code, String msg) {
14492            setReturnCode(code);
14493            setReturnMessage(msg);
14494            Slog.w(TAG, msg);
14495        }
14496
14497        public void setError(String msg, PackageParserException e) {
14498            setReturnCode(e.error);
14499            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14500            Slog.w(TAG, msg, e);
14501        }
14502
14503        public void setError(String msg, PackageManagerException e) {
14504            returnCode = e.error;
14505            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14506            Slog.w(TAG, msg, e);
14507        }
14508
14509        public void setReturnCode(int returnCode) {
14510            this.returnCode = returnCode;
14511            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14512            for (int i = 0; i < childCount; i++) {
14513                addedChildPackages.valueAt(i).returnCode = returnCode;
14514            }
14515        }
14516
14517        private void setReturnMessage(String returnMsg) {
14518            this.returnMsg = returnMsg;
14519            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14520            for (int i = 0; i < childCount; i++) {
14521                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14522            }
14523        }
14524
14525        // In some error cases we want to convey more info back to the observer
14526        String origPackage;
14527        String origPermission;
14528    }
14529
14530    /*
14531     * Install a non-existing package.
14532     */
14533    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14534            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14535            PackageInstalledInfo res) {
14536        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14537
14538        // Remember this for later, in case we need to rollback this install
14539        String pkgName = pkg.packageName;
14540
14541        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14542
14543        synchronized(mPackages) {
14544            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14545            if (renamedPackage != null) {
14546                // A package with the same name is already installed, though
14547                // it has been renamed to an older name.  The package we
14548                // are trying to install should be installed as an update to
14549                // the existing one, but that has not been requested, so bail.
14550                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14551                        + " without first uninstalling package running as "
14552                        + renamedPackage);
14553                return;
14554            }
14555            if (mPackages.containsKey(pkgName)) {
14556                // Don't allow installation over an existing package with the same name.
14557                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14558                        + " without first uninstalling.");
14559                return;
14560            }
14561        }
14562
14563        try {
14564            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14565                    System.currentTimeMillis(), user);
14566
14567            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14568
14569            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14570                prepareAppDataAfterInstallLIF(newPackage);
14571
14572            } else {
14573                // Remove package from internal structures, but keep around any
14574                // data that might have already existed
14575                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14576                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14577            }
14578        } catch (PackageManagerException e) {
14579            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14580        }
14581
14582        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14583    }
14584
14585    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14586        // Can't rotate keys during boot or if sharedUser.
14587        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14588                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14589            return false;
14590        }
14591        // app is using upgradeKeySets; make sure all are valid
14592        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14593        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14594        for (int i = 0; i < upgradeKeySets.length; i++) {
14595            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14596                Slog.wtf(TAG, "Package "
14597                         + (oldPs.name != null ? oldPs.name : "<null>")
14598                         + " contains upgrade-key-set reference to unknown key-set: "
14599                         + upgradeKeySets[i]
14600                         + " reverting to signatures check.");
14601                return false;
14602            }
14603        }
14604        return true;
14605    }
14606
14607    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14608        // Upgrade keysets are being used.  Determine if new package has a superset of the
14609        // required keys.
14610        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14611        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14612        for (int i = 0; i < upgradeKeySets.length; i++) {
14613            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14614            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14615                return true;
14616            }
14617        }
14618        return false;
14619    }
14620
14621    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14622        try (DigestInputStream digestStream =
14623                new DigestInputStream(new FileInputStream(file), digest)) {
14624            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14625        }
14626    }
14627
14628    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14629            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14630        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14631
14632        final PackageParser.Package oldPackage;
14633        final String pkgName = pkg.packageName;
14634        final int[] allUsers;
14635        final int[] installedUsers;
14636
14637        synchronized(mPackages) {
14638            oldPackage = mPackages.get(pkgName);
14639            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14640
14641            // don't allow upgrade to target a release SDK from a pre-release SDK
14642            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14643                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14644            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14645                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14646            if (oldTargetsPreRelease
14647                    && !newTargetsPreRelease
14648                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14649                Slog.w(TAG, "Can't install package targeting released sdk");
14650                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14651                return;
14652            }
14653
14654            // don't allow an upgrade from full to ephemeral
14655            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14656            if (isEphemeral && !oldIsEphemeral) {
14657                // can't downgrade from full to ephemeral
14658                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14659                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14660                return;
14661            }
14662
14663            // verify signatures are valid
14664            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14665            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14666                if (!checkUpgradeKeySetLP(ps, pkg)) {
14667                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14668                            "New package not signed by keys specified by upgrade-keysets: "
14669                                    + pkgName);
14670                    return;
14671                }
14672            } else {
14673                // default to original signature matching
14674                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14675                        != PackageManager.SIGNATURE_MATCH) {
14676                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14677                            "New package has a different signature: " + pkgName);
14678                    return;
14679                }
14680            }
14681
14682            // don't allow a system upgrade unless the upgrade hash matches
14683            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14684                byte[] digestBytes = null;
14685                try {
14686                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14687                    updateDigest(digest, new File(pkg.baseCodePath));
14688                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14689                        for (String path : pkg.splitCodePaths) {
14690                            updateDigest(digest, new File(path));
14691                        }
14692                    }
14693                    digestBytes = digest.digest();
14694                } catch (NoSuchAlgorithmException | IOException e) {
14695                    res.setError(INSTALL_FAILED_INVALID_APK,
14696                            "Could not compute hash: " + pkgName);
14697                    return;
14698                }
14699                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14700                    res.setError(INSTALL_FAILED_INVALID_APK,
14701                            "New package fails restrict-update check: " + pkgName);
14702                    return;
14703                }
14704                // retain upgrade restriction
14705                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14706            }
14707
14708            // Check for shared user id changes
14709            String invalidPackageName =
14710                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14711            if (invalidPackageName != null) {
14712                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14713                        "Package " + invalidPackageName + " tried to change user "
14714                                + oldPackage.mSharedUserId);
14715                return;
14716            }
14717
14718            // In case of rollback, remember per-user/profile install state
14719            allUsers = sUserManager.getUserIds();
14720            installedUsers = ps.queryInstalledUsers(allUsers, true);
14721        }
14722
14723        // Update what is removed
14724        res.removedInfo = new PackageRemovedInfo();
14725        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14726        res.removedInfo.removedPackage = oldPackage.packageName;
14727        res.removedInfo.isUpdate = true;
14728        res.removedInfo.origUsers = installedUsers;
14729        final int childCount = (oldPackage.childPackages != null)
14730                ? oldPackage.childPackages.size() : 0;
14731        for (int i = 0; i < childCount; i++) {
14732            boolean childPackageUpdated = false;
14733            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14734            if (res.addedChildPackages != null) {
14735                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14736                if (childRes != null) {
14737                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14738                    childRes.removedInfo.removedPackage = childPkg.packageName;
14739                    childRes.removedInfo.isUpdate = true;
14740                    childPackageUpdated = true;
14741                }
14742            }
14743            if (!childPackageUpdated) {
14744                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14745                childRemovedRes.removedPackage = childPkg.packageName;
14746                childRemovedRes.isUpdate = false;
14747                childRemovedRes.dataRemoved = true;
14748                synchronized (mPackages) {
14749                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14750                    if (childPs != null) {
14751                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14752                    }
14753                }
14754                if (res.removedInfo.removedChildPackages == null) {
14755                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14756                }
14757                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14758            }
14759        }
14760
14761        boolean sysPkg = (isSystemApp(oldPackage));
14762        if (sysPkg) {
14763            // Set the system/privileged flags as needed
14764            final boolean privileged =
14765                    (oldPackage.applicationInfo.privateFlags
14766                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14767            final int systemPolicyFlags = policyFlags
14768                    | PackageParser.PARSE_IS_SYSTEM
14769                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14770
14771            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14772                    user, allUsers, installerPackageName, res);
14773        } else {
14774            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14775                    user, allUsers, installerPackageName, res);
14776        }
14777    }
14778
14779    public List<String> getPreviousCodePaths(String packageName) {
14780        final PackageSetting ps = mSettings.mPackages.get(packageName);
14781        final List<String> result = new ArrayList<String>();
14782        if (ps != null && ps.oldCodePaths != null) {
14783            result.addAll(ps.oldCodePaths);
14784        }
14785        return result;
14786    }
14787
14788    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14789            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14790            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14791        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14792                + deletedPackage);
14793
14794        String pkgName = deletedPackage.packageName;
14795        boolean deletedPkg = true;
14796        boolean addedPkg = false;
14797        boolean updatedSettings = false;
14798        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14799        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14800                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14801
14802        final long origUpdateTime = (pkg.mExtras != null)
14803                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14804
14805        // First delete the existing package while retaining the data directory
14806        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14807                res.removedInfo, true, pkg)) {
14808            // If the existing package wasn't successfully deleted
14809            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14810            deletedPkg = false;
14811        } else {
14812            // Successfully deleted the old package; proceed with replace.
14813
14814            // If deleted package lived in a container, give users a chance to
14815            // relinquish resources before killing.
14816            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14817                if (DEBUG_INSTALL) {
14818                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14819                }
14820                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14821                final ArrayList<String> pkgList = new ArrayList<String>(1);
14822                pkgList.add(deletedPackage.applicationInfo.packageName);
14823                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14824            }
14825
14826            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14827                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14828            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14829
14830            try {
14831                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14832                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14833                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14834
14835                // Update the in-memory copy of the previous code paths.
14836                PackageSetting ps = mSettings.mPackages.get(pkgName);
14837                if (!killApp) {
14838                    if (ps.oldCodePaths == null) {
14839                        ps.oldCodePaths = new ArraySet<>();
14840                    }
14841                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14842                    if (deletedPackage.splitCodePaths != null) {
14843                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14844                    }
14845                } else {
14846                    ps.oldCodePaths = null;
14847                }
14848                if (ps.childPackageNames != null) {
14849                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14850                        final String childPkgName = ps.childPackageNames.get(i);
14851                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14852                        childPs.oldCodePaths = ps.oldCodePaths;
14853                    }
14854                }
14855                prepareAppDataAfterInstallLIF(newPackage);
14856                addedPkg = true;
14857            } catch (PackageManagerException e) {
14858                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14859            }
14860        }
14861
14862        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14863            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14864
14865            // Revert all internal state mutations and added folders for the failed install
14866            if (addedPkg) {
14867                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14868                        res.removedInfo, true, null);
14869            }
14870
14871            // Restore the old package
14872            if (deletedPkg) {
14873                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14874                File restoreFile = new File(deletedPackage.codePath);
14875                // Parse old package
14876                boolean oldExternal = isExternal(deletedPackage);
14877                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14878                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14879                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14880                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14881                try {
14882                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14883                            null);
14884                } catch (PackageManagerException e) {
14885                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14886                            + e.getMessage());
14887                    return;
14888                }
14889
14890                synchronized (mPackages) {
14891                    // Ensure the installer package name up to date
14892                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14893
14894                    // Update permissions for restored package
14895                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14896
14897                    mSettings.writeLPr();
14898                }
14899
14900                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14901            }
14902        } else {
14903            synchronized (mPackages) {
14904                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
14905                if (ps != null) {
14906                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14907                    if (res.removedInfo.removedChildPackages != null) {
14908                        final int childCount = res.removedInfo.removedChildPackages.size();
14909                        // Iterate in reverse as we may modify the collection
14910                        for (int i = childCount - 1; i >= 0; i--) {
14911                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14912                            if (res.addedChildPackages.containsKey(childPackageName)) {
14913                                res.removedInfo.removedChildPackages.removeAt(i);
14914                            } else {
14915                                PackageRemovedInfo childInfo = res.removedInfo
14916                                        .removedChildPackages.valueAt(i);
14917                                childInfo.removedForAllUsers = mPackages.get(
14918                                        childInfo.removedPackage) == null;
14919                            }
14920                        }
14921                    }
14922                }
14923            }
14924        }
14925    }
14926
14927    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14928            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14929            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14930        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14931                + ", old=" + deletedPackage);
14932
14933        final boolean disabledSystem;
14934
14935        // Remove existing system package
14936        removePackageLI(deletedPackage, true);
14937
14938        synchronized (mPackages) {
14939            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14940        }
14941        if (!disabledSystem) {
14942            // We didn't need to disable the .apk as a current system package,
14943            // which means we are replacing another update that is already
14944            // installed.  We need to make sure to delete the older one's .apk.
14945            res.removedInfo.args = createInstallArgsForExisting(0,
14946                    deletedPackage.applicationInfo.getCodePath(),
14947                    deletedPackage.applicationInfo.getResourcePath(),
14948                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14949        } else {
14950            res.removedInfo.args = null;
14951        }
14952
14953        // Successfully disabled the old package. Now proceed with re-installation
14954        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14955                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14956        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14957
14958        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14959        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14960                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14961
14962        PackageParser.Package newPackage = null;
14963        try {
14964            // Add the package to the internal data structures
14965            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14966
14967            // Set the update and install times
14968            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14969            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14970                    System.currentTimeMillis());
14971
14972            // Update the package dynamic state if succeeded
14973            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14974                // Now that the install succeeded make sure we remove data
14975                // directories for any child package the update removed.
14976                final int deletedChildCount = (deletedPackage.childPackages != null)
14977                        ? deletedPackage.childPackages.size() : 0;
14978                final int newChildCount = (newPackage.childPackages != null)
14979                        ? newPackage.childPackages.size() : 0;
14980                for (int i = 0; i < deletedChildCount; i++) {
14981                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14982                    boolean childPackageDeleted = true;
14983                    for (int j = 0; j < newChildCount; j++) {
14984                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14985                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14986                            childPackageDeleted = false;
14987                            break;
14988                        }
14989                    }
14990                    if (childPackageDeleted) {
14991                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14992                                deletedChildPkg.packageName);
14993                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14994                            PackageRemovedInfo removedChildRes = res.removedInfo
14995                                    .removedChildPackages.get(deletedChildPkg.packageName);
14996                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14997                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14998                        }
14999                    }
15000                }
15001
15002                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
15003                prepareAppDataAfterInstallLIF(newPackage);
15004            }
15005        } catch (PackageManagerException e) {
15006            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15007            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15008        }
15009
15010        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15011            // Re installation failed. Restore old information
15012            // Remove new pkg information
15013            if (newPackage != null) {
15014                removeInstalledPackageLI(newPackage, true);
15015            }
15016            // Add back the old system package
15017            try {
15018                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15019            } catch (PackageManagerException e) {
15020                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15021            }
15022
15023            synchronized (mPackages) {
15024                if (disabledSystem) {
15025                    enableSystemPackageLPw(deletedPackage);
15026                }
15027
15028                // Ensure the installer package name up to date
15029                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15030
15031                // Update permissions for restored package
15032                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15033
15034                mSettings.writeLPr();
15035            }
15036
15037            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15038                    + " after failed upgrade");
15039        }
15040    }
15041
15042    /**
15043     * Checks whether the parent or any of the child packages have a change shared
15044     * user. For a package to be a valid update the shred users of the parent and
15045     * the children should match. We may later support changing child shared users.
15046     * @param oldPkg The updated package.
15047     * @param newPkg The update package.
15048     * @return The shared user that change between the versions.
15049     */
15050    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15051            PackageParser.Package newPkg) {
15052        // Check parent shared user
15053        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15054            return newPkg.packageName;
15055        }
15056        // Check child shared users
15057        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15058        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15059        for (int i = 0; i < newChildCount; i++) {
15060            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15061            // If this child was present, did it have the same shared user?
15062            for (int j = 0; j < oldChildCount; j++) {
15063                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15064                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15065                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15066                    return newChildPkg.packageName;
15067                }
15068            }
15069        }
15070        return null;
15071    }
15072
15073    private void removeNativeBinariesLI(PackageSetting ps) {
15074        // Remove the lib path for the parent package
15075        if (ps != null) {
15076            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15077            // Remove the lib path for the child packages
15078            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15079            for (int i = 0; i < childCount; i++) {
15080                PackageSetting childPs = null;
15081                synchronized (mPackages) {
15082                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15083                }
15084                if (childPs != null) {
15085                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15086                            .legacyNativeLibraryPathString);
15087                }
15088            }
15089        }
15090    }
15091
15092    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15093        // Enable the parent package
15094        mSettings.enableSystemPackageLPw(pkg.packageName);
15095        // Enable the child packages
15096        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15097        for (int i = 0; i < childCount; i++) {
15098            PackageParser.Package childPkg = pkg.childPackages.get(i);
15099            mSettings.enableSystemPackageLPw(childPkg.packageName);
15100        }
15101    }
15102
15103    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15104            PackageParser.Package newPkg) {
15105        // Disable the parent package (parent always replaced)
15106        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15107        // Disable the child packages
15108        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15109        for (int i = 0; i < childCount; i++) {
15110            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15111            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15112            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15113        }
15114        return disabled;
15115    }
15116
15117    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15118            String installerPackageName) {
15119        // Enable the parent package
15120        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15121        // Enable the child packages
15122        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15123        for (int i = 0; i < childCount; i++) {
15124            PackageParser.Package childPkg = pkg.childPackages.get(i);
15125            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15126        }
15127    }
15128
15129    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15130        // Collect all used permissions in the UID
15131        ArraySet<String> usedPermissions = new ArraySet<>();
15132        final int packageCount = su.packages.size();
15133        for (int i = 0; i < packageCount; i++) {
15134            PackageSetting ps = su.packages.valueAt(i);
15135            if (ps.pkg == null) {
15136                continue;
15137            }
15138            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15139            for (int j = 0; j < requestedPermCount; j++) {
15140                String permission = ps.pkg.requestedPermissions.get(j);
15141                BasePermission bp = mSettings.mPermissions.get(permission);
15142                if (bp != null) {
15143                    usedPermissions.add(permission);
15144                }
15145            }
15146        }
15147
15148        PermissionsState permissionsState = su.getPermissionsState();
15149        // Prune install permissions
15150        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15151        final int installPermCount = installPermStates.size();
15152        for (int i = installPermCount - 1; i >= 0;  i--) {
15153            PermissionState permissionState = installPermStates.get(i);
15154            if (!usedPermissions.contains(permissionState.getName())) {
15155                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15156                if (bp != null) {
15157                    permissionsState.revokeInstallPermission(bp);
15158                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15159                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15160                }
15161            }
15162        }
15163
15164        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15165
15166        // Prune runtime permissions
15167        for (int userId : allUserIds) {
15168            List<PermissionState> runtimePermStates = permissionsState
15169                    .getRuntimePermissionStates(userId);
15170            final int runtimePermCount = runtimePermStates.size();
15171            for (int i = runtimePermCount - 1; i >= 0; i--) {
15172                PermissionState permissionState = runtimePermStates.get(i);
15173                if (!usedPermissions.contains(permissionState.getName())) {
15174                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15175                    if (bp != null) {
15176                        permissionsState.revokeRuntimePermission(bp, userId);
15177                        permissionsState.updatePermissionFlags(bp, userId,
15178                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15179                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15180                                runtimePermissionChangedUserIds, userId);
15181                    }
15182                }
15183            }
15184        }
15185
15186        return runtimePermissionChangedUserIds;
15187    }
15188
15189    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15190            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
15191        // Update the parent package setting
15192        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15193                res, user);
15194        // Update the child packages setting
15195        final int childCount = (newPackage.childPackages != null)
15196                ? newPackage.childPackages.size() : 0;
15197        for (int i = 0; i < childCount; i++) {
15198            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15199            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15200            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15201                    childRes.origUsers, childRes, user);
15202        }
15203    }
15204
15205    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15206            String installerPackageName, int[] allUsers, int[] installedForUsers,
15207            PackageInstalledInfo res, UserHandle user) {
15208        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15209
15210        String pkgName = newPackage.packageName;
15211        synchronized (mPackages) {
15212            //write settings. the installStatus will be incomplete at this stage.
15213            //note that the new package setting would have already been
15214            //added to mPackages. It hasn't been persisted yet.
15215            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15216            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15217            mSettings.writeLPr();
15218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15219        }
15220
15221        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15222        synchronized (mPackages) {
15223            updatePermissionsLPw(newPackage.packageName, newPackage,
15224                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15225                            ? UPDATE_PERMISSIONS_ALL : 0));
15226            // For system-bundled packages, we assume that installing an upgraded version
15227            // of the package implies that the user actually wants to run that new code,
15228            // so we enable the package.
15229            PackageSetting ps = mSettings.mPackages.get(pkgName);
15230            final int userId = user.getIdentifier();
15231            if (ps != null) {
15232                if (isSystemApp(newPackage)) {
15233                    if (DEBUG_INSTALL) {
15234                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15235                    }
15236                    // Enable system package for requested users
15237                    if (res.origUsers != null) {
15238                        for (int origUserId : res.origUsers) {
15239                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15240                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15241                                        origUserId, installerPackageName);
15242                            }
15243                        }
15244                    }
15245                    // Also convey the prior install/uninstall state
15246                    if (allUsers != null && installedForUsers != null) {
15247                        for (int currentUserId : allUsers) {
15248                            final boolean installed = ArrayUtils.contains(
15249                                    installedForUsers, currentUserId);
15250                            if (DEBUG_INSTALL) {
15251                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15252                            }
15253                            ps.setInstalled(installed, currentUserId);
15254                        }
15255                        // these install state changes will be persisted in the
15256                        // upcoming call to mSettings.writeLPr().
15257                    }
15258                }
15259                // It's implied that when a user requests installation, they want the app to be
15260                // installed and enabled.
15261                if (userId != UserHandle.USER_ALL) {
15262                    ps.setInstalled(true, userId);
15263                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15264                }
15265            }
15266            res.name = pkgName;
15267            res.uid = newPackage.applicationInfo.uid;
15268            res.pkg = newPackage;
15269            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15270            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15271            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15272            //to update install status
15273            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15274            mSettings.writeLPr();
15275            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15276        }
15277
15278        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15279    }
15280
15281    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15282        try {
15283            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15284            installPackageLI(args, res);
15285        } finally {
15286            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15287        }
15288    }
15289
15290    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15291        final int installFlags = args.installFlags;
15292        final String installerPackageName = args.installerPackageName;
15293        final String volumeUuid = args.volumeUuid;
15294        final File tmpPackageFile = new File(args.getCodePath());
15295        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15296        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15297                || (args.volumeUuid != null));
15298        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15299        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15300        boolean replace = false;
15301        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15302        if (args.move != null) {
15303            // moving a complete application; perform an initial scan on the new install location
15304            scanFlags |= SCAN_INITIAL;
15305        }
15306        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15307            scanFlags |= SCAN_DONT_KILL_APP;
15308        }
15309
15310        // Result object to be returned
15311        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15312
15313        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15314
15315        // Sanity check
15316        if (ephemeral && (forwardLocked || onExternal)) {
15317            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15318                    + " external=" + onExternal);
15319            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15320            return;
15321        }
15322
15323        // Retrieve PackageSettings and parse package
15324        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15325                | PackageParser.PARSE_ENFORCE_CODE
15326                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15327                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15328                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15329                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15330        PackageParser pp = new PackageParser();
15331        pp.setSeparateProcesses(mSeparateProcesses);
15332        pp.setDisplayMetrics(mMetrics);
15333
15334        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15335        final PackageParser.Package pkg;
15336        try {
15337            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15338        } catch (PackageParserException e) {
15339            res.setError("Failed parse during installPackageLI", e);
15340            return;
15341        } finally {
15342            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15343        }
15344
15345        // If we are installing a clustered package add results for the children
15346        if (pkg.childPackages != null) {
15347            synchronized (mPackages) {
15348                final int childCount = pkg.childPackages.size();
15349                for (int i = 0; i < childCount; i++) {
15350                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15351                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15352                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15353                    childRes.pkg = childPkg;
15354                    childRes.name = childPkg.packageName;
15355                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15356                    if (childPs != null) {
15357                        childRes.origUsers = childPs.queryInstalledUsers(
15358                                sUserManager.getUserIds(), true);
15359                    }
15360                    if ((mPackages.containsKey(childPkg.packageName))) {
15361                        childRes.removedInfo = new PackageRemovedInfo();
15362                        childRes.removedInfo.removedPackage = childPkg.packageName;
15363                    }
15364                    if (res.addedChildPackages == null) {
15365                        res.addedChildPackages = new ArrayMap<>();
15366                    }
15367                    res.addedChildPackages.put(childPkg.packageName, childRes);
15368                }
15369            }
15370        }
15371
15372        // If package doesn't declare API override, mark that we have an install
15373        // time CPU ABI override.
15374        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15375            pkg.cpuAbiOverride = args.abiOverride;
15376        }
15377
15378        String pkgName = res.name = pkg.packageName;
15379        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15380            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15381                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15382                return;
15383            }
15384        }
15385
15386        try {
15387            // either use what we've been given or parse directly from the APK
15388            if (args.certificates != null) {
15389                try {
15390                    PackageParser.populateCertificates(pkg, args.certificates);
15391                } catch (PackageParserException e) {
15392                    // there was something wrong with the certificates we were given;
15393                    // try to pull them from the APK
15394                    PackageParser.collectCertificates(pkg, parseFlags);
15395                }
15396            } else {
15397                PackageParser.collectCertificates(pkg, parseFlags);
15398            }
15399        } catch (PackageParserException e) {
15400            res.setError("Failed collect during installPackageLI", e);
15401            return;
15402        }
15403
15404        // Get rid of all references to package scan path via parser.
15405        pp = null;
15406        String oldCodePath = null;
15407        boolean systemApp = false;
15408        synchronized (mPackages) {
15409            // Check if installing already existing package
15410            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15411                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15412                if (pkg.mOriginalPackages != null
15413                        && pkg.mOriginalPackages.contains(oldName)
15414                        && mPackages.containsKey(oldName)) {
15415                    // This package is derived from an original package,
15416                    // and this device has been updating from that original
15417                    // name.  We must continue using the original name, so
15418                    // rename the new package here.
15419                    pkg.setPackageName(oldName);
15420                    pkgName = pkg.packageName;
15421                    replace = true;
15422                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15423                            + oldName + " pkgName=" + pkgName);
15424                } else if (mPackages.containsKey(pkgName)) {
15425                    // This package, under its official name, already exists
15426                    // on the device; we should replace it.
15427                    replace = true;
15428                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15429                }
15430
15431                // Child packages are installed through the parent package
15432                if (pkg.parentPackage != null) {
15433                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15434                            "Package " + pkg.packageName + " is child of package "
15435                                    + pkg.parentPackage.parentPackage + ". Child packages "
15436                                    + "can be updated only through the parent package.");
15437                    return;
15438                }
15439
15440                if (replace) {
15441                    // Prevent apps opting out from runtime permissions
15442                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15443                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15444                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15445                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15446                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15447                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15448                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15449                                        + " doesn't support runtime permissions but the old"
15450                                        + " target SDK " + oldTargetSdk + " does.");
15451                        return;
15452                    }
15453
15454                    // Prevent installing of child packages
15455                    if (oldPackage.parentPackage != null) {
15456                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15457                                "Package " + pkg.packageName + " is child of package "
15458                                        + oldPackage.parentPackage + ". Child packages "
15459                                        + "can be updated only through the parent package.");
15460                        return;
15461                    }
15462                }
15463            }
15464
15465            PackageSetting ps = mSettings.mPackages.get(pkgName);
15466            if (ps != null) {
15467                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15468
15469                // Quick sanity check that we're signed correctly if updating;
15470                // we'll check this again later when scanning, but we want to
15471                // bail early here before tripping over redefined permissions.
15472                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15473                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15474                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15475                                + pkg.packageName + " upgrade keys do not match the "
15476                                + "previously installed version");
15477                        return;
15478                    }
15479                } else {
15480                    try {
15481                        verifySignaturesLP(ps, pkg);
15482                    } catch (PackageManagerException e) {
15483                        res.setError(e.error, e.getMessage());
15484                        return;
15485                    }
15486                }
15487
15488                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15489                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15490                    systemApp = (ps.pkg.applicationInfo.flags &
15491                            ApplicationInfo.FLAG_SYSTEM) != 0;
15492                }
15493                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15494            }
15495
15496            // Check whether the newly-scanned package wants to define an already-defined perm
15497            int N = pkg.permissions.size();
15498            for (int i = N-1; i >= 0; i--) {
15499                PackageParser.Permission perm = pkg.permissions.get(i);
15500                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15501                if (bp != null) {
15502                    // If the defining package is signed with our cert, it's okay.  This
15503                    // also includes the "updating the same package" case, of course.
15504                    // "updating same package" could also involve key-rotation.
15505                    final boolean sigsOk;
15506                    if (bp.sourcePackage.equals(pkg.packageName)
15507                            && (bp.packageSetting instanceof PackageSetting)
15508                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15509                                    scanFlags))) {
15510                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15511                    } else {
15512                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15513                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15514                    }
15515                    if (!sigsOk) {
15516                        // If the owning package is the system itself, we log but allow
15517                        // install to proceed; we fail the install on all other permission
15518                        // redefinitions.
15519                        if (!bp.sourcePackage.equals("android")) {
15520                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15521                                    + pkg.packageName + " attempting to redeclare permission "
15522                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15523                            res.origPermission = perm.info.name;
15524                            res.origPackage = bp.sourcePackage;
15525                            return;
15526                        } else {
15527                            Slog.w(TAG, "Package " + pkg.packageName
15528                                    + " attempting to redeclare system permission "
15529                                    + perm.info.name + "; ignoring new declaration");
15530                            pkg.permissions.remove(i);
15531                        }
15532                    }
15533                }
15534            }
15535        }
15536
15537        if (systemApp) {
15538            if (onExternal) {
15539                // Abort update; system app can't be replaced with app on sdcard
15540                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15541                        "Cannot install updates to system apps on sdcard");
15542                return;
15543            } else if (ephemeral) {
15544                // Abort update; system app can't be replaced with an ephemeral app
15545                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15546                        "Cannot update a system app with an ephemeral app");
15547                return;
15548            }
15549        }
15550
15551        if (args.move != null) {
15552            // We did an in-place move, so dex is ready to roll
15553            scanFlags |= SCAN_NO_DEX;
15554            scanFlags |= SCAN_MOVE;
15555
15556            synchronized (mPackages) {
15557                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15558                if (ps == null) {
15559                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15560                            "Missing settings for moved package " + pkgName);
15561                }
15562
15563                // We moved the entire application as-is, so bring over the
15564                // previously derived ABI information.
15565                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15566                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15567            }
15568
15569        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15570            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15571            scanFlags |= SCAN_NO_DEX;
15572
15573            try {
15574                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15575                    args.abiOverride : pkg.cpuAbiOverride);
15576                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15577                        true /*extractLibs*/, mAppLib32InstallDir);
15578            } catch (PackageManagerException pme) {
15579                Slog.e(TAG, "Error deriving application ABI", pme);
15580                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15581                return;
15582            }
15583
15584            // Shared libraries for the package need to be updated.
15585            synchronized (mPackages) {
15586                try {
15587                    updateSharedLibrariesLPr(pkg, null);
15588                } catch (PackageManagerException e) {
15589                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15590                }
15591            }
15592            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15593            // Do not run PackageDexOptimizer through the local performDexOpt
15594            // method because `pkg` may not be in `mPackages` yet.
15595            //
15596            // Also, don't fail application installs if the dexopt step fails.
15597            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15598                    null /* instructionSets */, false /* checkProfiles */,
15599                    getCompilerFilterForReason(REASON_INSTALL),
15600                    getOrCreateCompilerPackageStats(pkg));
15601            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15602
15603            // Notify BackgroundDexOptService that the package has been changed.
15604            // If this is an update of a package which used to fail to compile,
15605            // BDOS will remove it from its blacklist.
15606            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15607        }
15608
15609        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15610            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15611            return;
15612        }
15613
15614        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15615
15616        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15617                "installPackageLI")) {
15618            if (replace) {
15619                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15620                        installerPackageName, res);
15621            } else {
15622                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15623                        args.user, installerPackageName, volumeUuid, res);
15624            }
15625        }
15626        synchronized (mPackages) {
15627            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15628            if (ps != null) {
15629                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15630            }
15631
15632            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15633            for (int i = 0; i < childCount; i++) {
15634                PackageParser.Package childPkg = pkg.childPackages.get(i);
15635                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15636                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15637                if (childPs != null) {
15638                    childRes.newUsers = childPs.queryInstalledUsers(
15639                            sUserManager.getUserIds(), true);
15640                }
15641            }
15642        }
15643    }
15644
15645    private void startIntentFilterVerifications(int userId, boolean replacing,
15646            PackageParser.Package pkg) {
15647        if (mIntentFilterVerifierComponent == null) {
15648            Slog.w(TAG, "No IntentFilter verification will not be done as "
15649                    + "there is no IntentFilterVerifier available!");
15650            return;
15651        }
15652
15653        final int verifierUid = getPackageUid(
15654                mIntentFilterVerifierComponent.getPackageName(),
15655                MATCH_DEBUG_TRIAGED_MISSING,
15656                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15657
15658        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15659        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15660        mHandler.sendMessage(msg);
15661
15662        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15663        for (int i = 0; i < childCount; i++) {
15664            PackageParser.Package childPkg = pkg.childPackages.get(i);
15665            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15666            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15667            mHandler.sendMessage(msg);
15668        }
15669    }
15670
15671    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15672            PackageParser.Package pkg) {
15673        int size = pkg.activities.size();
15674        if (size == 0) {
15675            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15676                    "No activity, so no need to verify any IntentFilter!");
15677            return;
15678        }
15679
15680        final boolean hasDomainURLs = hasDomainURLs(pkg);
15681        if (!hasDomainURLs) {
15682            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15683                    "No domain URLs, so no need to verify any IntentFilter!");
15684            return;
15685        }
15686
15687        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15688                + " if any IntentFilter from the " + size
15689                + " Activities needs verification ...");
15690
15691        int count = 0;
15692        final String packageName = pkg.packageName;
15693
15694        synchronized (mPackages) {
15695            // If this is a new install and we see that we've already run verification for this
15696            // package, we have nothing to do: it means the state was restored from backup.
15697            if (!replacing) {
15698                IntentFilterVerificationInfo ivi =
15699                        mSettings.getIntentFilterVerificationLPr(packageName);
15700                if (ivi != null) {
15701                    if (DEBUG_DOMAIN_VERIFICATION) {
15702                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15703                                + ivi.getStatusString());
15704                    }
15705                    return;
15706                }
15707            }
15708
15709            // If any filters need to be verified, then all need to be.
15710            boolean needToVerify = false;
15711            for (PackageParser.Activity a : pkg.activities) {
15712                for (ActivityIntentInfo filter : a.intents) {
15713                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15714                        if (DEBUG_DOMAIN_VERIFICATION) {
15715                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15716                        }
15717                        needToVerify = true;
15718                        break;
15719                    }
15720                }
15721            }
15722
15723            if (needToVerify) {
15724                final int verificationId = mIntentFilterVerificationToken++;
15725                for (PackageParser.Activity a : pkg.activities) {
15726                    for (ActivityIntentInfo filter : a.intents) {
15727                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15728                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15729                                    "Verification needed for IntentFilter:" + filter.toString());
15730                            mIntentFilterVerifier.addOneIntentFilterVerification(
15731                                    verifierUid, userId, verificationId, filter, packageName);
15732                            count++;
15733                        }
15734                    }
15735                }
15736            }
15737        }
15738
15739        if (count > 0) {
15740            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15741                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15742                    +  " for userId:" + userId);
15743            mIntentFilterVerifier.startVerifications(userId);
15744        } else {
15745            if (DEBUG_DOMAIN_VERIFICATION) {
15746                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15747            }
15748        }
15749    }
15750
15751    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15752        final ComponentName cn  = filter.activity.getComponentName();
15753        final String packageName = cn.getPackageName();
15754
15755        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15756                packageName);
15757        if (ivi == null) {
15758            return true;
15759        }
15760        int status = ivi.getStatus();
15761        switch (status) {
15762            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15763            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15764                return true;
15765
15766            default:
15767                // Nothing to do
15768                return false;
15769        }
15770    }
15771
15772    private static boolean isMultiArch(ApplicationInfo info) {
15773        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15774    }
15775
15776    private static boolean isExternal(PackageParser.Package pkg) {
15777        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15778    }
15779
15780    private static boolean isExternal(PackageSetting ps) {
15781        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15782    }
15783
15784    private static boolean isEphemeral(PackageParser.Package pkg) {
15785        return pkg.applicationInfo.isEphemeralApp();
15786    }
15787
15788    private static boolean isEphemeral(PackageSetting ps) {
15789        return ps.pkg != null && isEphemeral(ps.pkg);
15790    }
15791
15792    private static boolean isSystemApp(PackageParser.Package pkg) {
15793        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15794    }
15795
15796    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15797        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15798    }
15799
15800    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15801        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15802    }
15803
15804    private static boolean isSystemApp(PackageSetting ps) {
15805        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15806    }
15807
15808    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15809        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15810    }
15811
15812    private int packageFlagsToInstallFlags(PackageSetting ps) {
15813        int installFlags = 0;
15814        if (isEphemeral(ps)) {
15815            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15816        }
15817        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15818            // This existing package was an external ASEC install when we have
15819            // the external flag without a UUID
15820            installFlags |= PackageManager.INSTALL_EXTERNAL;
15821        }
15822        if (ps.isForwardLocked()) {
15823            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15824        }
15825        return installFlags;
15826    }
15827
15828    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15829        if (isExternal(pkg)) {
15830            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15831                return StorageManager.UUID_PRIMARY_PHYSICAL;
15832            } else {
15833                return pkg.volumeUuid;
15834            }
15835        } else {
15836            return StorageManager.UUID_PRIVATE_INTERNAL;
15837        }
15838    }
15839
15840    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15841        if (isExternal(pkg)) {
15842            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15843                return mSettings.getExternalVersion();
15844            } else {
15845                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15846            }
15847        } else {
15848            return mSettings.getInternalVersion();
15849        }
15850    }
15851
15852    private void deleteTempPackageFiles() {
15853        final FilenameFilter filter = new FilenameFilter() {
15854            public boolean accept(File dir, String name) {
15855                return name.startsWith("vmdl") && name.endsWith(".tmp");
15856            }
15857        };
15858        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15859            file.delete();
15860        }
15861    }
15862
15863    @Override
15864    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15865            int flags) {
15866        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15867                flags);
15868    }
15869
15870    @Override
15871    public void deletePackage(final String packageName,
15872            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15873        mContext.enforceCallingOrSelfPermission(
15874                android.Manifest.permission.DELETE_PACKAGES, null);
15875        Preconditions.checkNotNull(packageName);
15876        Preconditions.checkNotNull(observer);
15877        final int uid = Binder.getCallingUid();
15878        if (!isOrphaned(packageName)
15879                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15880            try {
15881                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15882                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15883                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15884                observer.onUserActionRequired(intent);
15885            } catch (RemoteException re) {
15886            }
15887            return;
15888        }
15889        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15890        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15891        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15892            mContext.enforceCallingOrSelfPermission(
15893                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15894                    "deletePackage for user " + userId);
15895        }
15896
15897        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15898            try {
15899                observer.onPackageDeleted(packageName,
15900                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15901            } catch (RemoteException re) {
15902            }
15903            return;
15904        }
15905
15906        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15907            try {
15908                observer.onPackageDeleted(packageName,
15909                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15910            } catch (RemoteException re) {
15911            }
15912            return;
15913        }
15914
15915        if (DEBUG_REMOVE) {
15916            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15917                    + " deleteAllUsers: " + deleteAllUsers );
15918        }
15919        // Queue up an async operation since the package deletion may take a little while.
15920        mHandler.post(new Runnable() {
15921            public void run() {
15922                mHandler.removeCallbacks(this);
15923                int returnCode;
15924                if (!deleteAllUsers) {
15925                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15926                } else {
15927                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15928                    // If nobody is blocking uninstall, proceed with delete for all users
15929                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15930                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15931                    } else {
15932                        // Otherwise uninstall individually for users with blockUninstalls=false
15933                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15934                        for (int userId : users) {
15935                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15936                                returnCode = deletePackageX(packageName, userId, userFlags);
15937                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15938                                    Slog.w(TAG, "Package delete failed for user " + userId
15939                                            + ", returnCode " + returnCode);
15940                                }
15941                            }
15942                        }
15943                        // The app has only been marked uninstalled for certain users.
15944                        // We still need to report that delete was blocked
15945                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15946                    }
15947                }
15948                try {
15949                    observer.onPackageDeleted(packageName, returnCode, null);
15950                } catch (RemoteException e) {
15951                    Log.i(TAG, "Observer no longer exists.");
15952                } //end catch
15953            } //end run
15954        });
15955    }
15956
15957    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15958        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15959              || callingUid == Process.SYSTEM_UID) {
15960            return true;
15961        }
15962        final int callingUserId = UserHandle.getUserId(callingUid);
15963        // If the caller installed the pkgName, then allow it to silently uninstall.
15964        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15965            return true;
15966        }
15967
15968        // Allow package verifier to silently uninstall.
15969        if (mRequiredVerifierPackage != null &&
15970                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15971            return true;
15972        }
15973
15974        // Allow package uninstaller to silently uninstall.
15975        if (mRequiredUninstallerPackage != null &&
15976                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15977            return true;
15978        }
15979
15980        // Allow storage manager to silently uninstall.
15981        if (mStorageManagerPackage != null &&
15982                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15983            return true;
15984        }
15985        return false;
15986    }
15987
15988    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15989        int[] result = EMPTY_INT_ARRAY;
15990        for (int userId : userIds) {
15991            if (getBlockUninstallForUser(packageName, userId)) {
15992                result = ArrayUtils.appendInt(result, userId);
15993            }
15994        }
15995        return result;
15996    }
15997
15998    @Override
15999    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16000        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16001    }
16002
16003    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16004        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16005                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16006        try {
16007            if (dpm != null) {
16008                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16009                        /* callingUserOnly =*/ false);
16010                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16011                        : deviceOwnerComponentName.getPackageName();
16012                // Does the package contains the device owner?
16013                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16014                // this check is probably not needed, since DO should be registered as a device
16015                // admin on some user too. (Original bug for this: b/17657954)
16016                if (packageName.equals(deviceOwnerPackageName)) {
16017                    return true;
16018                }
16019                // Does it contain a device admin for any user?
16020                int[] users;
16021                if (userId == UserHandle.USER_ALL) {
16022                    users = sUserManager.getUserIds();
16023                } else {
16024                    users = new int[]{userId};
16025                }
16026                for (int i = 0; i < users.length; ++i) {
16027                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16028                        return true;
16029                    }
16030                }
16031            }
16032        } catch (RemoteException e) {
16033        }
16034        return false;
16035    }
16036
16037    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16038        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16039    }
16040
16041    /**
16042     *  This method is an internal method that could be get invoked either
16043     *  to delete an installed package or to clean up a failed installation.
16044     *  After deleting an installed package, a broadcast is sent to notify any
16045     *  listeners that the package has been removed. For cleaning up a failed
16046     *  installation, the broadcast is not necessary since the package's
16047     *  installation wouldn't have sent the initial broadcast either
16048     *  The key steps in deleting a package are
16049     *  deleting the package information in internal structures like mPackages,
16050     *  deleting the packages base directories through installd
16051     *  updating mSettings to reflect current status
16052     *  persisting settings for later use
16053     *  sending a broadcast if necessary
16054     */
16055    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16056        final PackageRemovedInfo info = new PackageRemovedInfo();
16057        final boolean res;
16058
16059        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16060                ? UserHandle.USER_ALL : userId;
16061
16062        if (isPackageDeviceAdmin(packageName, removeUser)) {
16063            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16064            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16065        }
16066
16067        PackageSetting uninstalledPs = null;
16068
16069        // for the uninstall-updates case and restricted profiles, remember the per-
16070        // user handle installed state
16071        int[] allUsers;
16072        synchronized (mPackages) {
16073            uninstalledPs = mSettings.mPackages.get(packageName);
16074            if (uninstalledPs == null) {
16075                Slog.w(TAG, "Not removing non-existent package " + packageName);
16076                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16077            }
16078            allUsers = sUserManager.getUserIds();
16079            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16080        }
16081
16082        final int freezeUser;
16083        if (isUpdatedSystemApp(uninstalledPs)
16084                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16085            // We're downgrading a system app, which will apply to all users, so
16086            // freeze them all during the downgrade
16087            freezeUser = UserHandle.USER_ALL;
16088        } else {
16089            freezeUser = removeUser;
16090        }
16091
16092        synchronized (mInstallLock) {
16093            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16094            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16095                    deleteFlags, "deletePackageX")) {
16096                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16097                        deleteFlags | REMOVE_CHATTY, info, true, null);
16098            }
16099            synchronized (mPackages) {
16100                if (res) {
16101                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16102                }
16103            }
16104        }
16105
16106        if (res) {
16107            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16108            info.sendPackageRemovedBroadcasts(killApp);
16109            info.sendSystemPackageUpdatedBroadcasts();
16110            info.sendSystemPackageAppearedBroadcasts();
16111        }
16112        // Force a gc here.
16113        Runtime.getRuntime().gc();
16114        // Delete the resources here after sending the broadcast to let
16115        // other processes clean up before deleting resources.
16116        if (info.args != null) {
16117            synchronized (mInstallLock) {
16118                info.args.doPostDeleteLI(true);
16119            }
16120        }
16121
16122        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16123    }
16124
16125    class PackageRemovedInfo {
16126        String removedPackage;
16127        int uid = -1;
16128        int removedAppId = -1;
16129        int[] origUsers;
16130        int[] removedUsers = null;
16131        boolean isRemovedPackageSystemUpdate = false;
16132        boolean isUpdate;
16133        boolean dataRemoved;
16134        boolean removedForAllUsers;
16135        // Clean up resources deleted packages.
16136        InstallArgs args = null;
16137        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16138        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16139
16140        void sendPackageRemovedBroadcasts(boolean killApp) {
16141            sendPackageRemovedBroadcastInternal(killApp);
16142            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16143            for (int i = 0; i < childCount; i++) {
16144                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16145                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16146            }
16147        }
16148
16149        void sendSystemPackageUpdatedBroadcasts() {
16150            if (isRemovedPackageSystemUpdate) {
16151                sendSystemPackageUpdatedBroadcastsInternal();
16152                final int childCount = (removedChildPackages != null)
16153                        ? removedChildPackages.size() : 0;
16154                for (int i = 0; i < childCount; i++) {
16155                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16156                    if (childInfo.isRemovedPackageSystemUpdate) {
16157                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16158                    }
16159                }
16160            }
16161        }
16162
16163        void sendSystemPackageAppearedBroadcasts() {
16164            final int packageCount = (appearedChildPackages != null)
16165                    ? appearedChildPackages.size() : 0;
16166            for (int i = 0; i < packageCount; i++) {
16167                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16168                sendPackageAddedForNewUsers(installedInfo.name, true,
16169                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16170            }
16171        }
16172
16173        private void sendSystemPackageUpdatedBroadcastsInternal() {
16174            Bundle extras = new Bundle(2);
16175            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16176            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16177            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16178                    extras, 0, null, null, null);
16179            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16180                    extras, 0, null, null, null);
16181            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16182                    null, 0, removedPackage, null, null);
16183        }
16184
16185        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16186            Bundle extras = new Bundle(2);
16187            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16188            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16189            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16190            if (isUpdate || isRemovedPackageSystemUpdate) {
16191                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16192            }
16193            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16194            if (removedPackage != null) {
16195                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16196                        extras, 0, null, null, removedUsers);
16197                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16198                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16199                            removedPackage, extras, 0, null, null, removedUsers);
16200                }
16201            }
16202            if (removedAppId >= 0) {
16203                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16204                        removedUsers);
16205            }
16206        }
16207    }
16208
16209    /*
16210     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16211     * flag is not set, the data directory is removed as well.
16212     * make sure this flag is set for partially installed apps. If not its meaningless to
16213     * delete a partially installed application.
16214     */
16215    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16216            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16217        String packageName = ps.name;
16218        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16219        // Retrieve object to delete permissions for shared user later on
16220        final PackageParser.Package deletedPkg;
16221        final PackageSetting deletedPs;
16222        // reader
16223        synchronized (mPackages) {
16224            deletedPkg = mPackages.get(packageName);
16225            deletedPs = mSettings.mPackages.get(packageName);
16226            if (outInfo != null) {
16227                outInfo.removedPackage = packageName;
16228                outInfo.removedUsers = deletedPs != null
16229                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16230                        : null;
16231            }
16232        }
16233
16234        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16235
16236        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16237            final PackageParser.Package resolvedPkg;
16238            if (deletedPkg != null) {
16239                resolvedPkg = deletedPkg;
16240            } else {
16241                // We don't have a parsed package when it lives on an ejected
16242                // adopted storage device, so fake something together
16243                resolvedPkg = new PackageParser.Package(ps.name);
16244                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16245            }
16246            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16247                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16248            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16249            if (outInfo != null) {
16250                outInfo.dataRemoved = true;
16251            }
16252            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16253        }
16254
16255        // writer
16256        synchronized (mPackages) {
16257            if (deletedPs != null) {
16258                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16259                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16260                    clearDefaultBrowserIfNeeded(packageName);
16261                    if (outInfo != null) {
16262                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16263                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16264                    }
16265                    updatePermissionsLPw(deletedPs.name, null, 0);
16266                    if (deletedPs.sharedUser != null) {
16267                        // Remove permissions associated with package. Since runtime
16268                        // permissions are per user we have to kill the removed package
16269                        // or packages running under the shared user of the removed
16270                        // package if revoking the permissions requested only by the removed
16271                        // package is successful and this causes a change in gids.
16272                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16273                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16274                                    userId);
16275                            if (userIdToKill == UserHandle.USER_ALL
16276                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16277                                // If gids changed for this user, kill all affected packages.
16278                                mHandler.post(new Runnable() {
16279                                    @Override
16280                                    public void run() {
16281                                        // This has to happen with no lock held.
16282                                        killApplication(deletedPs.name, deletedPs.appId,
16283                                                KILL_APP_REASON_GIDS_CHANGED);
16284                                    }
16285                                });
16286                                break;
16287                            }
16288                        }
16289                    }
16290                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16291                }
16292                // make sure to preserve per-user disabled state if this removal was just
16293                // a downgrade of a system app to the factory package
16294                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16295                    if (DEBUG_REMOVE) {
16296                        Slog.d(TAG, "Propagating install state across downgrade");
16297                    }
16298                    for (int userId : allUserHandles) {
16299                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16300                        if (DEBUG_REMOVE) {
16301                            Slog.d(TAG, "    user " + userId + " => " + installed);
16302                        }
16303                        ps.setInstalled(installed, userId);
16304                    }
16305                }
16306            }
16307            // can downgrade to reader
16308            if (writeSettings) {
16309                // Save settings now
16310                mSettings.writeLPr();
16311            }
16312        }
16313        if (outInfo != null) {
16314            // A user ID was deleted here. Go through all users and remove it
16315            // from KeyStore.
16316            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16317        }
16318    }
16319
16320    static boolean locationIsPrivileged(File path) {
16321        try {
16322            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16323                    .getCanonicalPath();
16324            return path.getCanonicalPath().startsWith(privilegedAppDir);
16325        } catch (IOException e) {
16326            Slog.e(TAG, "Unable to access code path " + path);
16327        }
16328        return false;
16329    }
16330
16331    /*
16332     * Tries to delete system package.
16333     */
16334    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16335            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16336            boolean writeSettings) {
16337        if (deletedPs.parentPackageName != null) {
16338            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16339            return false;
16340        }
16341
16342        final boolean applyUserRestrictions
16343                = (allUserHandles != null) && (outInfo.origUsers != null);
16344        final PackageSetting disabledPs;
16345        // Confirm if the system package has been updated
16346        // An updated system app can be deleted. This will also have to restore
16347        // the system pkg from system partition
16348        // reader
16349        synchronized (mPackages) {
16350            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16351        }
16352
16353        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16354                + " disabledPs=" + disabledPs);
16355
16356        if (disabledPs == null) {
16357            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16358            return false;
16359        } else if (DEBUG_REMOVE) {
16360            Slog.d(TAG, "Deleting system pkg from data partition");
16361        }
16362
16363        if (DEBUG_REMOVE) {
16364            if (applyUserRestrictions) {
16365                Slog.d(TAG, "Remembering install states:");
16366                for (int userId : allUserHandles) {
16367                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16368                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16369                }
16370            }
16371        }
16372
16373        // Delete the updated package
16374        outInfo.isRemovedPackageSystemUpdate = true;
16375        if (outInfo.removedChildPackages != null) {
16376            final int childCount = (deletedPs.childPackageNames != null)
16377                    ? deletedPs.childPackageNames.size() : 0;
16378            for (int i = 0; i < childCount; i++) {
16379                String childPackageName = deletedPs.childPackageNames.get(i);
16380                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16381                        .contains(childPackageName)) {
16382                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16383                            childPackageName);
16384                    if (childInfo != null) {
16385                        childInfo.isRemovedPackageSystemUpdate = true;
16386                    }
16387                }
16388            }
16389        }
16390
16391        if (disabledPs.versionCode < deletedPs.versionCode) {
16392            // Delete data for downgrades
16393            flags &= ~PackageManager.DELETE_KEEP_DATA;
16394        } else {
16395            // Preserve data by setting flag
16396            flags |= PackageManager.DELETE_KEEP_DATA;
16397        }
16398
16399        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16400                outInfo, writeSettings, disabledPs.pkg);
16401        if (!ret) {
16402            return false;
16403        }
16404
16405        // writer
16406        synchronized (mPackages) {
16407            // Reinstate the old system package
16408            enableSystemPackageLPw(disabledPs.pkg);
16409            // Remove any native libraries from the upgraded package.
16410            removeNativeBinariesLI(deletedPs);
16411        }
16412
16413        // Install the system package
16414        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16415        int parseFlags = mDefParseFlags
16416                | PackageParser.PARSE_MUST_BE_APK
16417                | PackageParser.PARSE_IS_SYSTEM
16418                | PackageParser.PARSE_IS_SYSTEM_DIR;
16419        if (locationIsPrivileged(disabledPs.codePath)) {
16420            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16421        }
16422
16423        final PackageParser.Package newPkg;
16424        try {
16425            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16426                0 /* currentTime */, null);
16427        } catch (PackageManagerException e) {
16428            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16429                    + e.getMessage());
16430            return false;
16431        }
16432        try {
16433            // update shared libraries for the newly re-installed system package
16434            updateSharedLibrariesLPr(newPkg, null);
16435        } catch (PackageManagerException e) {
16436            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16437        }
16438
16439        prepareAppDataAfterInstallLIF(newPkg);
16440
16441        // writer
16442        synchronized (mPackages) {
16443            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16444
16445            // Propagate the permissions state as we do not want to drop on the floor
16446            // runtime permissions. The update permissions method below will take
16447            // care of removing obsolete permissions and grant install permissions.
16448            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16449            updatePermissionsLPw(newPkg.packageName, newPkg,
16450                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16451
16452            if (applyUserRestrictions) {
16453                if (DEBUG_REMOVE) {
16454                    Slog.d(TAG, "Propagating install state across reinstall");
16455                }
16456                for (int userId : allUserHandles) {
16457                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16458                    if (DEBUG_REMOVE) {
16459                        Slog.d(TAG, "    user " + userId + " => " + installed);
16460                    }
16461                    ps.setInstalled(installed, userId);
16462
16463                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16464                }
16465                // Regardless of writeSettings we need to ensure that this restriction
16466                // state propagation is persisted
16467                mSettings.writeAllUsersPackageRestrictionsLPr();
16468            }
16469            // can downgrade to reader here
16470            if (writeSettings) {
16471                mSettings.writeLPr();
16472            }
16473        }
16474        return true;
16475    }
16476
16477    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16478            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16479            PackageRemovedInfo outInfo, boolean writeSettings,
16480            PackageParser.Package replacingPackage) {
16481        synchronized (mPackages) {
16482            if (outInfo != null) {
16483                outInfo.uid = ps.appId;
16484            }
16485
16486            if (outInfo != null && outInfo.removedChildPackages != null) {
16487                final int childCount = (ps.childPackageNames != null)
16488                        ? ps.childPackageNames.size() : 0;
16489                for (int i = 0; i < childCount; i++) {
16490                    String childPackageName = ps.childPackageNames.get(i);
16491                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16492                    if (childPs == null) {
16493                        return false;
16494                    }
16495                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16496                            childPackageName);
16497                    if (childInfo != null) {
16498                        childInfo.uid = childPs.appId;
16499                    }
16500                }
16501            }
16502        }
16503
16504        // Delete package data from internal structures and also remove data if flag is set
16505        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16506
16507        // Delete the child packages data
16508        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16509        for (int i = 0; i < childCount; i++) {
16510            PackageSetting childPs;
16511            synchronized (mPackages) {
16512                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16513            }
16514            if (childPs != null) {
16515                PackageRemovedInfo childOutInfo = (outInfo != null
16516                        && outInfo.removedChildPackages != null)
16517                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16518                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16519                        && (replacingPackage != null
16520                        && !replacingPackage.hasChildPackage(childPs.name))
16521                        ? flags & ~DELETE_KEEP_DATA : flags;
16522                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16523                        deleteFlags, writeSettings);
16524            }
16525        }
16526
16527        // Delete application code and resources only for parent packages
16528        if (ps.parentPackageName == null) {
16529            if (deleteCodeAndResources && (outInfo != null)) {
16530                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16531                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16532                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16533            }
16534        }
16535
16536        return true;
16537    }
16538
16539    @Override
16540    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16541            int userId) {
16542        mContext.enforceCallingOrSelfPermission(
16543                android.Manifest.permission.DELETE_PACKAGES, null);
16544        synchronized (mPackages) {
16545            PackageSetting ps = mSettings.mPackages.get(packageName);
16546            if (ps == null) {
16547                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16548                return false;
16549            }
16550            if (!ps.getInstalled(userId)) {
16551                // Can't block uninstall for an app that is not installed or enabled.
16552                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16553                return false;
16554            }
16555            ps.setBlockUninstall(blockUninstall, userId);
16556            mSettings.writePackageRestrictionsLPr(userId);
16557        }
16558        return true;
16559    }
16560
16561    @Override
16562    public boolean getBlockUninstallForUser(String packageName, int userId) {
16563        synchronized (mPackages) {
16564            PackageSetting ps = mSettings.mPackages.get(packageName);
16565            if (ps == null) {
16566                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16567                return false;
16568            }
16569            return ps.getBlockUninstall(userId);
16570        }
16571    }
16572
16573    @Override
16574    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16575        int callingUid = Binder.getCallingUid();
16576        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16577            throw new SecurityException(
16578                    "setRequiredForSystemUser can only be run by the system or root");
16579        }
16580        synchronized (mPackages) {
16581            PackageSetting ps = mSettings.mPackages.get(packageName);
16582            if (ps == null) {
16583                Log.w(TAG, "Package doesn't exist: " + packageName);
16584                return false;
16585            }
16586            if (systemUserApp) {
16587                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16588            } else {
16589                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16590            }
16591            mSettings.writeLPr();
16592        }
16593        return true;
16594    }
16595
16596    /*
16597     * This method handles package deletion in general
16598     */
16599    private boolean deletePackageLIF(String packageName, UserHandle user,
16600            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16601            PackageRemovedInfo outInfo, boolean writeSettings,
16602            PackageParser.Package replacingPackage) {
16603        if (packageName == null) {
16604            Slog.w(TAG, "Attempt to delete null packageName.");
16605            return false;
16606        }
16607
16608        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16609
16610        PackageSetting ps;
16611
16612        synchronized (mPackages) {
16613            ps = mSettings.mPackages.get(packageName);
16614            if (ps == null) {
16615                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16616                return false;
16617            }
16618
16619            if (ps.parentPackageName != null && (!isSystemApp(ps)
16620                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16621                if (DEBUG_REMOVE) {
16622                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16623                            + ((user == null) ? UserHandle.USER_ALL : user));
16624                }
16625                final int removedUserId = (user != null) ? user.getIdentifier()
16626                        : UserHandle.USER_ALL;
16627                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16628                    return false;
16629                }
16630                markPackageUninstalledForUserLPw(ps, user);
16631                scheduleWritePackageRestrictionsLocked(user);
16632                return true;
16633            }
16634        }
16635
16636        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16637                && user.getIdentifier() != UserHandle.USER_ALL)) {
16638            // The caller is asking that the package only be deleted for a single
16639            // user.  To do this, we just mark its uninstalled state and delete
16640            // its data. If this is a system app, we only allow this to happen if
16641            // they have set the special DELETE_SYSTEM_APP which requests different
16642            // semantics than normal for uninstalling system apps.
16643            markPackageUninstalledForUserLPw(ps, user);
16644
16645            if (!isSystemApp(ps)) {
16646                // Do not uninstall the APK if an app should be cached
16647                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16648                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16649                    // Other user still have this package installed, so all
16650                    // we need to do is clear this user's data and save that
16651                    // it is uninstalled.
16652                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16653                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16654                        return false;
16655                    }
16656                    scheduleWritePackageRestrictionsLocked(user);
16657                    return true;
16658                } else {
16659                    // We need to set it back to 'installed' so the uninstall
16660                    // broadcasts will be sent correctly.
16661                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16662                    ps.setInstalled(true, user.getIdentifier());
16663                }
16664            } else {
16665                // This is a system app, so we assume that the
16666                // other users still have this package installed, so all
16667                // we need to do is clear this user's data and save that
16668                // it is uninstalled.
16669                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16670                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16671                    return false;
16672                }
16673                scheduleWritePackageRestrictionsLocked(user);
16674                return true;
16675            }
16676        }
16677
16678        // If we are deleting a composite package for all users, keep track
16679        // of result for each child.
16680        if (ps.childPackageNames != null && outInfo != null) {
16681            synchronized (mPackages) {
16682                final int childCount = ps.childPackageNames.size();
16683                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16684                for (int i = 0; i < childCount; i++) {
16685                    String childPackageName = ps.childPackageNames.get(i);
16686                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16687                    childInfo.removedPackage = childPackageName;
16688                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16689                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16690                    if (childPs != null) {
16691                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16692                    }
16693                }
16694            }
16695        }
16696
16697        boolean ret = false;
16698        if (isSystemApp(ps)) {
16699            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16700            // When an updated system application is deleted we delete the existing resources
16701            // as well and fall back to existing code in system partition
16702            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16703        } else {
16704            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16705            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16706                    outInfo, writeSettings, replacingPackage);
16707        }
16708
16709        // Take a note whether we deleted the package for all users
16710        if (outInfo != null) {
16711            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16712            if (outInfo.removedChildPackages != null) {
16713                synchronized (mPackages) {
16714                    final int childCount = outInfo.removedChildPackages.size();
16715                    for (int i = 0; i < childCount; i++) {
16716                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16717                        if (childInfo != null) {
16718                            childInfo.removedForAllUsers = mPackages.get(
16719                                    childInfo.removedPackage) == null;
16720                        }
16721                    }
16722                }
16723            }
16724            // If we uninstalled an update to a system app there may be some
16725            // child packages that appeared as they are declared in the system
16726            // app but were not declared in the update.
16727            if (isSystemApp(ps)) {
16728                synchronized (mPackages) {
16729                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16730                    final int childCount = (updatedPs.childPackageNames != null)
16731                            ? updatedPs.childPackageNames.size() : 0;
16732                    for (int i = 0; i < childCount; i++) {
16733                        String childPackageName = updatedPs.childPackageNames.get(i);
16734                        if (outInfo.removedChildPackages == null
16735                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16736                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16737                            if (childPs == null) {
16738                                continue;
16739                            }
16740                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16741                            installRes.name = childPackageName;
16742                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16743                            installRes.pkg = mPackages.get(childPackageName);
16744                            installRes.uid = childPs.pkg.applicationInfo.uid;
16745                            if (outInfo.appearedChildPackages == null) {
16746                                outInfo.appearedChildPackages = new ArrayMap<>();
16747                            }
16748                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16749                        }
16750                    }
16751                }
16752            }
16753        }
16754
16755        return ret;
16756    }
16757
16758    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16759        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16760                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16761        for (int nextUserId : userIds) {
16762            if (DEBUG_REMOVE) {
16763                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16764            }
16765            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16766                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16767                    false /*hidden*/, false /*suspended*/, null, null, null,
16768                    false /*blockUninstall*/,
16769                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16770        }
16771    }
16772
16773    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16774            PackageRemovedInfo outInfo) {
16775        final PackageParser.Package pkg;
16776        synchronized (mPackages) {
16777            pkg = mPackages.get(ps.name);
16778        }
16779
16780        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16781                : new int[] {userId};
16782        for (int nextUserId : userIds) {
16783            if (DEBUG_REMOVE) {
16784                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16785                        + nextUserId);
16786            }
16787
16788            destroyAppDataLIF(pkg, userId,
16789                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16790            destroyAppProfilesLIF(pkg, userId);
16791            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16792            schedulePackageCleaning(ps.name, nextUserId, false);
16793            synchronized (mPackages) {
16794                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16795                    scheduleWritePackageRestrictionsLocked(nextUserId);
16796                }
16797                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16798            }
16799        }
16800
16801        if (outInfo != null) {
16802            outInfo.removedPackage = ps.name;
16803            outInfo.removedAppId = ps.appId;
16804            outInfo.removedUsers = userIds;
16805        }
16806
16807        return true;
16808    }
16809
16810    private final class ClearStorageConnection implements ServiceConnection {
16811        IMediaContainerService mContainerService;
16812
16813        @Override
16814        public void onServiceConnected(ComponentName name, IBinder service) {
16815            synchronized (this) {
16816                mContainerService = IMediaContainerService.Stub
16817                        .asInterface(Binder.allowBlocking(service));
16818                notifyAll();
16819            }
16820        }
16821
16822        @Override
16823        public void onServiceDisconnected(ComponentName name) {
16824        }
16825    }
16826
16827    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16828        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16829
16830        final boolean mounted;
16831        if (Environment.isExternalStorageEmulated()) {
16832            mounted = true;
16833        } else {
16834            final String status = Environment.getExternalStorageState();
16835
16836            mounted = status.equals(Environment.MEDIA_MOUNTED)
16837                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16838        }
16839
16840        if (!mounted) {
16841            return;
16842        }
16843
16844        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16845        int[] users;
16846        if (userId == UserHandle.USER_ALL) {
16847            users = sUserManager.getUserIds();
16848        } else {
16849            users = new int[] { userId };
16850        }
16851        final ClearStorageConnection conn = new ClearStorageConnection();
16852        if (mContext.bindServiceAsUser(
16853                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16854            try {
16855                for (int curUser : users) {
16856                    long timeout = SystemClock.uptimeMillis() + 5000;
16857                    synchronized (conn) {
16858                        long now;
16859                        while (conn.mContainerService == null &&
16860                                (now = SystemClock.uptimeMillis()) < timeout) {
16861                            try {
16862                                conn.wait(timeout - now);
16863                            } catch (InterruptedException e) {
16864                            }
16865                        }
16866                    }
16867                    if (conn.mContainerService == null) {
16868                        return;
16869                    }
16870
16871                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16872                    clearDirectory(conn.mContainerService,
16873                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16874                    if (allData) {
16875                        clearDirectory(conn.mContainerService,
16876                                userEnv.buildExternalStorageAppDataDirs(packageName));
16877                        clearDirectory(conn.mContainerService,
16878                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16879                    }
16880                }
16881            } finally {
16882                mContext.unbindService(conn);
16883            }
16884        }
16885    }
16886
16887    @Override
16888    public void clearApplicationProfileData(String packageName) {
16889        enforceSystemOrRoot("Only the system can clear all profile data");
16890
16891        final PackageParser.Package pkg;
16892        synchronized (mPackages) {
16893            pkg = mPackages.get(packageName);
16894        }
16895
16896        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16897            synchronized (mInstallLock) {
16898                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16899                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16900                        true /* removeBaseMarker */);
16901            }
16902        }
16903    }
16904
16905    @Override
16906    public void clearApplicationUserData(final String packageName,
16907            final IPackageDataObserver observer, final int userId) {
16908        mContext.enforceCallingOrSelfPermission(
16909                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16910
16911        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16912                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16913
16914        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16915            throw new SecurityException("Cannot clear data for a protected package: "
16916                    + packageName);
16917        }
16918        // Queue up an async operation since the package deletion may take a little while.
16919        mHandler.post(new Runnable() {
16920            public void run() {
16921                mHandler.removeCallbacks(this);
16922                final boolean succeeded;
16923                try (PackageFreezer freezer = freezePackage(packageName,
16924                        "clearApplicationUserData")) {
16925                    synchronized (mInstallLock) {
16926                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16927                    }
16928                    clearExternalStorageDataSync(packageName, userId, true);
16929                }
16930                if (succeeded) {
16931                    // invoke DeviceStorageMonitor's update method to clear any notifications
16932                    DeviceStorageMonitorInternal dsm = LocalServices
16933                            .getService(DeviceStorageMonitorInternal.class);
16934                    if (dsm != null) {
16935                        dsm.checkMemory();
16936                    }
16937                }
16938                if(observer != null) {
16939                    try {
16940                        observer.onRemoveCompleted(packageName, succeeded);
16941                    } catch (RemoteException e) {
16942                        Log.i(TAG, "Observer no longer exists.");
16943                    }
16944                } //end if observer
16945            } //end run
16946        });
16947    }
16948
16949    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16950        if (packageName == null) {
16951            Slog.w(TAG, "Attempt to delete null packageName.");
16952            return false;
16953        }
16954
16955        // Try finding details about the requested package
16956        PackageParser.Package pkg;
16957        synchronized (mPackages) {
16958            pkg = mPackages.get(packageName);
16959            if (pkg == null) {
16960                final PackageSetting ps = mSettings.mPackages.get(packageName);
16961                if (ps != null) {
16962                    pkg = ps.pkg;
16963                }
16964            }
16965
16966            if (pkg == null) {
16967                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16968                return false;
16969            }
16970
16971            PackageSetting ps = (PackageSetting) pkg.mExtras;
16972            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16973        }
16974
16975        clearAppDataLIF(pkg, userId,
16976                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16977
16978        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16979        removeKeystoreDataIfNeeded(userId, appId);
16980
16981        UserManagerInternal umInternal = getUserManagerInternal();
16982        final int flags;
16983        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16984            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16985        } else if (umInternal.isUserRunning(userId)) {
16986            flags = StorageManager.FLAG_STORAGE_DE;
16987        } else {
16988            flags = 0;
16989        }
16990        prepareAppDataContentsLIF(pkg, userId, flags);
16991
16992        return true;
16993    }
16994
16995    /**
16996     * Reverts user permission state changes (permissions and flags) in
16997     * all packages for a given user.
16998     *
16999     * @param userId The device user for which to do a reset.
17000     */
17001    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17002        final int packageCount = mPackages.size();
17003        for (int i = 0; i < packageCount; i++) {
17004            PackageParser.Package pkg = mPackages.valueAt(i);
17005            PackageSetting ps = (PackageSetting) pkg.mExtras;
17006            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17007        }
17008    }
17009
17010    private void resetNetworkPolicies(int userId) {
17011        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17012    }
17013
17014    /**
17015     * Reverts user permission state changes (permissions and flags).
17016     *
17017     * @param ps The package for which to reset.
17018     * @param userId The device user for which to do a reset.
17019     */
17020    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17021            final PackageSetting ps, final int userId) {
17022        if (ps.pkg == null) {
17023            return;
17024        }
17025
17026        // These are flags that can change base on user actions.
17027        final int userSettableMask = FLAG_PERMISSION_USER_SET
17028                | FLAG_PERMISSION_USER_FIXED
17029                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17030                | FLAG_PERMISSION_REVIEW_REQUIRED;
17031
17032        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17033                | FLAG_PERMISSION_POLICY_FIXED;
17034
17035        boolean writeInstallPermissions = false;
17036        boolean writeRuntimePermissions = false;
17037
17038        final int permissionCount = ps.pkg.requestedPermissions.size();
17039        for (int i = 0; i < permissionCount; i++) {
17040            String permission = ps.pkg.requestedPermissions.get(i);
17041
17042            BasePermission bp = mSettings.mPermissions.get(permission);
17043            if (bp == null) {
17044                continue;
17045            }
17046
17047            // If shared user we just reset the state to which only this app contributed.
17048            if (ps.sharedUser != null) {
17049                boolean used = false;
17050                final int packageCount = ps.sharedUser.packages.size();
17051                for (int j = 0; j < packageCount; j++) {
17052                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17053                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17054                            && pkg.pkg.requestedPermissions.contains(permission)) {
17055                        used = true;
17056                        break;
17057                    }
17058                }
17059                if (used) {
17060                    continue;
17061                }
17062            }
17063
17064            PermissionsState permissionsState = ps.getPermissionsState();
17065
17066            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17067
17068            // Always clear the user settable flags.
17069            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17070                    bp.name) != null;
17071            // If permission review is enabled and this is a legacy app, mark the
17072            // permission as requiring a review as this is the initial state.
17073            int flags = 0;
17074            if (mPermissionReviewRequired
17075                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17076                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17077            }
17078            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17079                if (hasInstallState) {
17080                    writeInstallPermissions = true;
17081                } else {
17082                    writeRuntimePermissions = true;
17083                }
17084            }
17085
17086            // Below is only runtime permission handling.
17087            if (!bp.isRuntime()) {
17088                continue;
17089            }
17090
17091            // Never clobber system or policy.
17092            if ((oldFlags & policyOrSystemFlags) != 0) {
17093                continue;
17094            }
17095
17096            // If this permission was granted by default, make sure it is.
17097            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17098                if (permissionsState.grantRuntimePermission(bp, userId)
17099                        != PERMISSION_OPERATION_FAILURE) {
17100                    writeRuntimePermissions = true;
17101                }
17102            // If permission review is enabled the permissions for a legacy apps
17103            // are represented as constantly granted runtime ones, so don't revoke.
17104            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17105                // Otherwise, reset the permission.
17106                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17107                switch (revokeResult) {
17108                    case PERMISSION_OPERATION_SUCCESS:
17109                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17110                        writeRuntimePermissions = true;
17111                        final int appId = ps.appId;
17112                        mHandler.post(new Runnable() {
17113                            @Override
17114                            public void run() {
17115                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17116                            }
17117                        });
17118                    } break;
17119                }
17120            }
17121        }
17122
17123        // Synchronously write as we are taking permissions away.
17124        if (writeRuntimePermissions) {
17125            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17126        }
17127
17128        // Synchronously write as we are taking permissions away.
17129        if (writeInstallPermissions) {
17130            mSettings.writeLPr();
17131        }
17132    }
17133
17134    /**
17135     * Remove entries from the keystore daemon. Will only remove it if the
17136     * {@code appId} is valid.
17137     */
17138    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17139        if (appId < 0) {
17140            return;
17141        }
17142
17143        final KeyStore keyStore = KeyStore.getInstance();
17144        if (keyStore != null) {
17145            if (userId == UserHandle.USER_ALL) {
17146                for (final int individual : sUserManager.getUserIds()) {
17147                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17148                }
17149            } else {
17150                keyStore.clearUid(UserHandle.getUid(userId, appId));
17151            }
17152        } else {
17153            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17154        }
17155    }
17156
17157    @Override
17158    public void deleteApplicationCacheFiles(final String packageName,
17159            final IPackageDataObserver observer) {
17160        final int userId = UserHandle.getCallingUserId();
17161        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17162    }
17163
17164    @Override
17165    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17166            final IPackageDataObserver observer) {
17167        mContext.enforceCallingOrSelfPermission(
17168                android.Manifest.permission.DELETE_CACHE_FILES, null);
17169        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17170                /* requireFullPermission= */ true, /* checkShell= */ false,
17171                "delete application cache files");
17172
17173        final PackageParser.Package pkg;
17174        synchronized (mPackages) {
17175            pkg = mPackages.get(packageName);
17176        }
17177
17178        // Queue up an async operation since the package deletion may take a little while.
17179        mHandler.post(new Runnable() {
17180            public void run() {
17181                synchronized (mInstallLock) {
17182                    final int flags = StorageManager.FLAG_STORAGE_DE
17183                            | StorageManager.FLAG_STORAGE_CE;
17184                    // We're only clearing cache files, so we don't care if the
17185                    // app is unfrozen and still able to run
17186                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17187                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17188                }
17189                clearExternalStorageDataSync(packageName, userId, false);
17190                if (observer != null) {
17191                    try {
17192                        observer.onRemoveCompleted(packageName, true);
17193                    } catch (RemoteException e) {
17194                        Log.i(TAG, "Observer no longer exists.");
17195                    }
17196                }
17197            }
17198        });
17199    }
17200
17201    @Override
17202    public void getPackageSizeInfo(final String packageName, int userHandle,
17203            final IPackageStatsObserver observer) {
17204        mContext.enforceCallingOrSelfPermission(
17205                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17206        if (packageName == null) {
17207            throw new IllegalArgumentException("Attempt to get size of null packageName");
17208        }
17209
17210        PackageStats stats = new PackageStats(packageName, userHandle);
17211
17212        /*
17213         * Queue up an async operation since the package measurement may take a
17214         * little while.
17215         */
17216        Message msg = mHandler.obtainMessage(INIT_COPY);
17217        msg.obj = new MeasureParams(stats, observer);
17218        mHandler.sendMessage(msg);
17219    }
17220
17221    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17222        final PackageSetting ps;
17223        synchronized (mPackages) {
17224            ps = mSettings.mPackages.get(packageName);
17225            if (ps == null) {
17226                Slog.w(TAG, "Failed to find settings for " + packageName);
17227                return false;
17228            }
17229        }
17230        try {
17231            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17232                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17233                    ps.getCeDataInode(userId), ps.codePathString, stats);
17234        } catch (InstallerException e) {
17235            Slog.w(TAG, String.valueOf(e));
17236            return false;
17237        }
17238
17239        // For now, ignore code size of packages on system partition
17240        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17241            stats.codeSize = 0;
17242        }
17243
17244        return true;
17245    }
17246
17247    private int getUidTargetSdkVersionLockedLPr(int uid) {
17248        Object obj = mSettings.getUserIdLPr(uid);
17249        if (obj instanceof SharedUserSetting) {
17250            final SharedUserSetting sus = (SharedUserSetting) obj;
17251            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17252            final Iterator<PackageSetting> it = sus.packages.iterator();
17253            while (it.hasNext()) {
17254                final PackageSetting ps = it.next();
17255                if (ps.pkg != null) {
17256                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17257                    if (v < vers) vers = v;
17258                }
17259            }
17260            return vers;
17261        } else if (obj instanceof PackageSetting) {
17262            final PackageSetting ps = (PackageSetting) obj;
17263            if (ps.pkg != null) {
17264                return ps.pkg.applicationInfo.targetSdkVersion;
17265            }
17266        }
17267        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17268    }
17269
17270    @Override
17271    public void addPreferredActivity(IntentFilter filter, int match,
17272            ComponentName[] set, ComponentName activity, int userId) {
17273        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17274                "Adding preferred");
17275    }
17276
17277    private void addPreferredActivityInternal(IntentFilter filter, int match,
17278            ComponentName[] set, ComponentName activity, boolean always, int userId,
17279            String opname) {
17280        // writer
17281        int callingUid = Binder.getCallingUid();
17282        enforceCrossUserPermission(callingUid, userId,
17283                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17284        if (filter.countActions() == 0) {
17285            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17286            return;
17287        }
17288        synchronized (mPackages) {
17289            if (mContext.checkCallingOrSelfPermission(
17290                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17291                    != PackageManager.PERMISSION_GRANTED) {
17292                if (getUidTargetSdkVersionLockedLPr(callingUid)
17293                        < Build.VERSION_CODES.FROYO) {
17294                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17295                            + callingUid);
17296                    return;
17297                }
17298                mContext.enforceCallingOrSelfPermission(
17299                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17300            }
17301
17302            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17303            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17304                    + userId + ":");
17305            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17306            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17307            scheduleWritePackageRestrictionsLocked(userId);
17308            postPreferredActivityChangedBroadcast(userId);
17309        }
17310    }
17311
17312    private void postPreferredActivityChangedBroadcast(int userId) {
17313        mHandler.post(() -> {
17314            final IActivityManager am = ActivityManager.getService();
17315            if (am == null) {
17316                return;
17317            }
17318
17319            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17320            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17321            try {
17322                am.broadcastIntent(null, intent, null, null,
17323                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17324                        null, false, false, userId);
17325            } catch (RemoteException e) {
17326            }
17327        });
17328    }
17329
17330    @Override
17331    public void replacePreferredActivity(IntentFilter filter, int match,
17332            ComponentName[] set, ComponentName activity, int userId) {
17333        if (filter.countActions() != 1) {
17334            throw new IllegalArgumentException(
17335                    "replacePreferredActivity expects filter to have only 1 action.");
17336        }
17337        if (filter.countDataAuthorities() != 0
17338                || filter.countDataPaths() != 0
17339                || filter.countDataSchemes() > 1
17340                || filter.countDataTypes() != 0) {
17341            throw new IllegalArgumentException(
17342                    "replacePreferredActivity expects filter to have no data authorities, " +
17343                    "paths, or types; and at most one scheme.");
17344        }
17345
17346        final int callingUid = Binder.getCallingUid();
17347        enforceCrossUserPermission(callingUid, userId,
17348                true /* requireFullPermission */, false /* checkShell */,
17349                "replace preferred activity");
17350        synchronized (mPackages) {
17351            if (mContext.checkCallingOrSelfPermission(
17352                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17353                    != PackageManager.PERMISSION_GRANTED) {
17354                if (getUidTargetSdkVersionLockedLPr(callingUid)
17355                        < Build.VERSION_CODES.FROYO) {
17356                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17357                            + Binder.getCallingUid());
17358                    return;
17359                }
17360                mContext.enforceCallingOrSelfPermission(
17361                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17362            }
17363
17364            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17365            if (pir != null) {
17366                // Get all of the existing entries that exactly match this filter.
17367                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17368                if (existing != null && existing.size() == 1) {
17369                    PreferredActivity cur = existing.get(0);
17370                    if (DEBUG_PREFERRED) {
17371                        Slog.i(TAG, "Checking replace of preferred:");
17372                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17373                        if (!cur.mPref.mAlways) {
17374                            Slog.i(TAG, "  -- CUR; not mAlways!");
17375                        } else {
17376                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17377                            Slog.i(TAG, "  -- CUR: mSet="
17378                                    + Arrays.toString(cur.mPref.mSetComponents));
17379                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17380                            Slog.i(TAG, "  -- NEW: mMatch="
17381                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17382                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17383                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17384                        }
17385                    }
17386                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17387                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17388                            && cur.mPref.sameSet(set)) {
17389                        // Setting the preferred activity to what it happens to be already
17390                        if (DEBUG_PREFERRED) {
17391                            Slog.i(TAG, "Replacing with same preferred activity "
17392                                    + cur.mPref.mShortComponent + " for user "
17393                                    + userId + ":");
17394                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17395                        }
17396                        return;
17397                    }
17398                }
17399
17400                if (existing != null) {
17401                    if (DEBUG_PREFERRED) {
17402                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17403                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17404                    }
17405                    for (int i = 0; i < existing.size(); i++) {
17406                        PreferredActivity pa = existing.get(i);
17407                        if (DEBUG_PREFERRED) {
17408                            Slog.i(TAG, "Removing existing preferred activity "
17409                                    + pa.mPref.mComponent + ":");
17410                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17411                        }
17412                        pir.removeFilter(pa);
17413                    }
17414                }
17415            }
17416            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17417                    "Replacing preferred");
17418        }
17419    }
17420
17421    @Override
17422    public void clearPackagePreferredActivities(String packageName) {
17423        final int uid = Binder.getCallingUid();
17424        // writer
17425        synchronized (mPackages) {
17426            PackageParser.Package pkg = mPackages.get(packageName);
17427            if (pkg == null || pkg.applicationInfo.uid != uid) {
17428                if (mContext.checkCallingOrSelfPermission(
17429                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17430                        != PackageManager.PERMISSION_GRANTED) {
17431                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17432                            < Build.VERSION_CODES.FROYO) {
17433                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17434                                + Binder.getCallingUid());
17435                        return;
17436                    }
17437                    mContext.enforceCallingOrSelfPermission(
17438                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17439                }
17440            }
17441
17442            int user = UserHandle.getCallingUserId();
17443            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17444                scheduleWritePackageRestrictionsLocked(user);
17445            }
17446        }
17447    }
17448
17449    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17450    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17451        ArrayList<PreferredActivity> removed = null;
17452        boolean changed = false;
17453        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17454            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17455            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17456            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17457                continue;
17458            }
17459            Iterator<PreferredActivity> it = pir.filterIterator();
17460            while (it.hasNext()) {
17461                PreferredActivity pa = it.next();
17462                // Mark entry for removal only if it matches the package name
17463                // and the entry is of type "always".
17464                if (packageName == null ||
17465                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17466                                && pa.mPref.mAlways)) {
17467                    if (removed == null) {
17468                        removed = new ArrayList<PreferredActivity>();
17469                    }
17470                    removed.add(pa);
17471                }
17472            }
17473            if (removed != null) {
17474                for (int j=0; j<removed.size(); j++) {
17475                    PreferredActivity pa = removed.get(j);
17476                    pir.removeFilter(pa);
17477                }
17478                changed = true;
17479            }
17480        }
17481        if (changed) {
17482            postPreferredActivityChangedBroadcast(userId);
17483        }
17484        return changed;
17485    }
17486
17487    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17488    private void clearIntentFilterVerificationsLPw(int userId) {
17489        final int packageCount = mPackages.size();
17490        for (int i = 0; i < packageCount; i++) {
17491            PackageParser.Package pkg = mPackages.valueAt(i);
17492            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17493        }
17494    }
17495
17496    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17497    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17498        if (userId == UserHandle.USER_ALL) {
17499            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17500                    sUserManager.getUserIds())) {
17501                for (int oneUserId : sUserManager.getUserIds()) {
17502                    scheduleWritePackageRestrictionsLocked(oneUserId);
17503                }
17504            }
17505        } else {
17506            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17507                scheduleWritePackageRestrictionsLocked(userId);
17508            }
17509        }
17510    }
17511
17512    void clearDefaultBrowserIfNeeded(String packageName) {
17513        for (int oneUserId : sUserManager.getUserIds()) {
17514            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17515            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17516            if (packageName.equals(defaultBrowserPackageName)) {
17517                setDefaultBrowserPackageName(null, oneUserId);
17518            }
17519        }
17520    }
17521
17522    @Override
17523    public void resetApplicationPreferences(int userId) {
17524        mContext.enforceCallingOrSelfPermission(
17525                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17526        final long identity = Binder.clearCallingIdentity();
17527        // writer
17528        try {
17529            synchronized (mPackages) {
17530                clearPackagePreferredActivitiesLPw(null, userId);
17531                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17532                // TODO: We have to reset the default SMS and Phone. This requires
17533                // significant refactoring to keep all default apps in the package
17534                // manager (cleaner but more work) or have the services provide
17535                // callbacks to the package manager to request a default app reset.
17536                applyFactoryDefaultBrowserLPw(userId);
17537                clearIntentFilterVerificationsLPw(userId);
17538                primeDomainVerificationsLPw(userId);
17539                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17540                scheduleWritePackageRestrictionsLocked(userId);
17541            }
17542            resetNetworkPolicies(userId);
17543        } finally {
17544            Binder.restoreCallingIdentity(identity);
17545        }
17546    }
17547
17548    @Override
17549    public int getPreferredActivities(List<IntentFilter> outFilters,
17550            List<ComponentName> outActivities, String packageName) {
17551
17552        int num = 0;
17553        final int userId = UserHandle.getCallingUserId();
17554        // reader
17555        synchronized (mPackages) {
17556            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17557            if (pir != null) {
17558                final Iterator<PreferredActivity> it = pir.filterIterator();
17559                while (it.hasNext()) {
17560                    final PreferredActivity pa = it.next();
17561                    if (packageName == null
17562                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17563                                    && pa.mPref.mAlways)) {
17564                        if (outFilters != null) {
17565                            outFilters.add(new IntentFilter(pa));
17566                        }
17567                        if (outActivities != null) {
17568                            outActivities.add(pa.mPref.mComponent);
17569                        }
17570                    }
17571                }
17572            }
17573        }
17574
17575        return num;
17576    }
17577
17578    @Override
17579    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17580            int userId) {
17581        int callingUid = Binder.getCallingUid();
17582        if (callingUid != Process.SYSTEM_UID) {
17583            throw new SecurityException(
17584                    "addPersistentPreferredActivity can only be run by the system");
17585        }
17586        if (filter.countActions() == 0) {
17587            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17588            return;
17589        }
17590        synchronized (mPackages) {
17591            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17592                    ":");
17593            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17594            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17595                    new PersistentPreferredActivity(filter, activity));
17596            scheduleWritePackageRestrictionsLocked(userId);
17597            postPreferredActivityChangedBroadcast(userId);
17598        }
17599    }
17600
17601    @Override
17602    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17603        int callingUid = Binder.getCallingUid();
17604        if (callingUid != Process.SYSTEM_UID) {
17605            throw new SecurityException(
17606                    "clearPackagePersistentPreferredActivities can only be run by the system");
17607        }
17608        ArrayList<PersistentPreferredActivity> removed = null;
17609        boolean changed = false;
17610        synchronized (mPackages) {
17611            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17612                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17613                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17614                        .valueAt(i);
17615                if (userId != thisUserId) {
17616                    continue;
17617                }
17618                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17619                while (it.hasNext()) {
17620                    PersistentPreferredActivity ppa = it.next();
17621                    // Mark entry for removal only if it matches the package name.
17622                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17623                        if (removed == null) {
17624                            removed = new ArrayList<PersistentPreferredActivity>();
17625                        }
17626                        removed.add(ppa);
17627                    }
17628                }
17629                if (removed != null) {
17630                    for (int j=0; j<removed.size(); j++) {
17631                        PersistentPreferredActivity ppa = removed.get(j);
17632                        ppir.removeFilter(ppa);
17633                    }
17634                    changed = true;
17635                }
17636            }
17637
17638            if (changed) {
17639                scheduleWritePackageRestrictionsLocked(userId);
17640                postPreferredActivityChangedBroadcast(userId);
17641            }
17642        }
17643    }
17644
17645    /**
17646     * Common machinery for picking apart a restored XML blob and passing
17647     * it to a caller-supplied functor to be applied to the running system.
17648     */
17649    private void restoreFromXml(XmlPullParser parser, int userId,
17650            String expectedStartTag, BlobXmlRestorer functor)
17651            throws IOException, XmlPullParserException {
17652        int type;
17653        while ((type = parser.next()) != XmlPullParser.START_TAG
17654                && type != XmlPullParser.END_DOCUMENT) {
17655        }
17656        if (type != XmlPullParser.START_TAG) {
17657            // oops didn't find a start tag?!
17658            if (DEBUG_BACKUP) {
17659                Slog.e(TAG, "Didn't find start tag during restore");
17660            }
17661            return;
17662        }
17663Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17664        // this is supposed to be TAG_PREFERRED_BACKUP
17665        if (!expectedStartTag.equals(parser.getName())) {
17666            if (DEBUG_BACKUP) {
17667                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17668            }
17669            return;
17670        }
17671
17672        // skip interfering stuff, then we're aligned with the backing implementation
17673        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17674Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17675        functor.apply(parser, userId);
17676    }
17677
17678    private interface BlobXmlRestorer {
17679        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17680    }
17681
17682    /**
17683     * Non-Binder method, support for the backup/restore mechanism: write the
17684     * full set of preferred activities in its canonical XML format.  Returns the
17685     * XML output as a byte array, or null if there is none.
17686     */
17687    @Override
17688    public byte[] getPreferredActivityBackup(int userId) {
17689        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17690            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17691        }
17692
17693        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17694        try {
17695            final XmlSerializer serializer = new FastXmlSerializer();
17696            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17697            serializer.startDocument(null, true);
17698            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17699
17700            synchronized (mPackages) {
17701                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17702            }
17703
17704            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17705            serializer.endDocument();
17706            serializer.flush();
17707        } catch (Exception e) {
17708            if (DEBUG_BACKUP) {
17709                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17710            }
17711            return null;
17712        }
17713
17714        return dataStream.toByteArray();
17715    }
17716
17717    @Override
17718    public void restorePreferredActivities(byte[] backup, int userId) {
17719        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17720            throw new SecurityException("Only the system may call restorePreferredActivities()");
17721        }
17722
17723        try {
17724            final XmlPullParser parser = Xml.newPullParser();
17725            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17726            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17727                    new BlobXmlRestorer() {
17728                        @Override
17729                        public void apply(XmlPullParser parser, int userId)
17730                                throws XmlPullParserException, IOException {
17731                            synchronized (mPackages) {
17732                                mSettings.readPreferredActivitiesLPw(parser, userId);
17733                            }
17734                        }
17735                    } );
17736        } catch (Exception e) {
17737            if (DEBUG_BACKUP) {
17738                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17739            }
17740        }
17741    }
17742
17743    /**
17744     * Non-Binder method, support for the backup/restore mechanism: write the
17745     * default browser (etc) settings in its canonical XML format.  Returns the default
17746     * browser XML representation as a byte array, or null if there is none.
17747     */
17748    @Override
17749    public byte[] getDefaultAppsBackup(int userId) {
17750        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17751            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17752        }
17753
17754        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17755        try {
17756            final XmlSerializer serializer = new FastXmlSerializer();
17757            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17758            serializer.startDocument(null, true);
17759            serializer.startTag(null, TAG_DEFAULT_APPS);
17760
17761            synchronized (mPackages) {
17762                mSettings.writeDefaultAppsLPr(serializer, userId);
17763            }
17764
17765            serializer.endTag(null, TAG_DEFAULT_APPS);
17766            serializer.endDocument();
17767            serializer.flush();
17768        } catch (Exception e) {
17769            if (DEBUG_BACKUP) {
17770                Slog.e(TAG, "Unable to write default apps for backup", e);
17771            }
17772            return null;
17773        }
17774
17775        return dataStream.toByteArray();
17776    }
17777
17778    @Override
17779    public void restoreDefaultApps(byte[] backup, int userId) {
17780        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17781            throw new SecurityException("Only the system may call restoreDefaultApps()");
17782        }
17783
17784        try {
17785            final XmlPullParser parser = Xml.newPullParser();
17786            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17787            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17788                    new BlobXmlRestorer() {
17789                        @Override
17790                        public void apply(XmlPullParser parser, int userId)
17791                                throws XmlPullParserException, IOException {
17792                            synchronized (mPackages) {
17793                                mSettings.readDefaultAppsLPw(parser, userId);
17794                            }
17795                        }
17796                    } );
17797        } catch (Exception e) {
17798            if (DEBUG_BACKUP) {
17799                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17800            }
17801        }
17802    }
17803
17804    @Override
17805    public byte[] getIntentFilterVerificationBackup(int userId) {
17806        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17807            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17808        }
17809
17810        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17811        try {
17812            final XmlSerializer serializer = new FastXmlSerializer();
17813            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17814            serializer.startDocument(null, true);
17815            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17816
17817            synchronized (mPackages) {
17818                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17819            }
17820
17821            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17822            serializer.endDocument();
17823            serializer.flush();
17824        } catch (Exception e) {
17825            if (DEBUG_BACKUP) {
17826                Slog.e(TAG, "Unable to write default apps for backup", e);
17827            }
17828            return null;
17829        }
17830
17831        return dataStream.toByteArray();
17832    }
17833
17834    @Override
17835    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17836        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17837            throw new SecurityException("Only the system may call restorePreferredActivities()");
17838        }
17839
17840        try {
17841            final XmlPullParser parser = Xml.newPullParser();
17842            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17843            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17844                    new BlobXmlRestorer() {
17845                        @Override
17846                        public void apply(XmlPullParser parser, int userId)
17847                                throws XmlPullParserException, IOException {
17848                            synchronized (mPackages) {
17849                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17850                                mSettings.writeLPr();
17851                            }
17852                        }
17853                    } );
17854        } catch (Exception e) {
17855            if (DEBUG_BACKUP) {
17856                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17857            }
17858        }
17859    }
17860
17861    @Override
17862    public byte[] getPermissionGrantBackup(int userId) {
17863        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17864            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17865        }
17866
17867        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17868        try {
17869            final XmlSerializer serializer = new FastXmlSerializer();
17870            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17871            serializer.startDocument(null, true);
17872            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17873
17874            synchronized (mPackages) {
17875                serializeRuntimePermissionGrantsLPr(serializer, userId);
17876            }
17877
17878            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17879            serializer.endDocument();
17880            serializer.flush();
17881        } catch (Exception e) {
17882            if (DEBUG_BACKUP) {
17883                Slog.e(TAG, "Unable to write default apps for backup", e);
17884            }
17885            return null;
17886        }
17887
17888        return dataStream.toByteArray();
17889    }
17890
17891    @Override
17892    public void restorePermissionGrants(byte[] backup, int userId) {
17893        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17894            throw new SecurityException("Only the system may call restorePermissionGrants()");
17895        }
17896
17897        try {
17898            final XmlPullParser parser = Xml.newPullParser();
17899            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17900            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17901                    new BlobXmlRestorer() {
17902                        @Override
17903                        public void apply(XmlPullParser parser, int userId)
17904                                throws XmlPullParserException, IOException {
17905                            synchronized (mPackages) {
17906                                processRestoredPermissionGrantsLPr(parser, userId);
17907                            }
17908                        }
17909                    } );
17910        } catch (Exception e) {
17911            if (DEBUG_BACKUP) {
17912                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17913            }
17914        }
17915    }
17916
17917    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17918            throws IOException {
17919        serializer.startTag(null, TAG_ALL_GRANTS);
17920
17921        final int N = mSettings.mPackages.size();
17922        for (int i = 0; i < N; i++) {
17923            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17924            boolean pkgGrantsKnown = false;
17925
17926            PermissionsState packagePerms = ps.getPermissionsState();
17927
17928            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17929                final int grantFlags = state.getFlags();
17930                // only look at grants that are not system/policy fixed
17931                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17932                    final boolean isGranted = state.isGranted();
17933                    // And only back up the user-twiddled state bits
17934                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17935                        final String packageName = mSettings.mPackages.keyAt(i);
17936                        if (!pkgGrantsKnown) {
17937                            serializer.startTag(null, TAG_GRANT);
17938                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17939                            pkgGrantsKnown = true;
17940                        }
17941
17942                        final boolean userSet =
17943                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17944                        final boolean userFixed =
17945                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17946                        final boolean revoke =
17947                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17948
17949                        serializer.startTag(null, TAG_PERMISSION);
17950                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17951                        if (isGranted) {
17952                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17953                        }
17954                        if (userSet) {
17955                            serializer.attribute(null, ATTR_USER_SET, "true");
17956                        }
17957                        if (userFixed) {
17958                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17959                        }
17960                        if (revoke) {
17961                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17962                        }
17963                        serializer.endTag(null, TAG_PERMISSION);
17964                    }
17965                }
17966            }
17967
17968            if (pkgGrantsKnown) {
17969                serializer.endTag(null, TAG_GRANT);
17970            }
17971        }
17972
17973        serializer.endTag(null, TAG_ALL_GRANTS);
17974    }
17975
17976    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17977            throws XmlPullParserException, IOException {
17978        String pkgName = null;
17979        int outerDepth = parser.getDepth();
17980        int type;
17981        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17982                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17983            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17984                continue;
17985            }
17986
17987            final String tagName = parser.getName();
17988            if (tagName.equals(TAG_GRANT)) {
17989                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17990                if (DEBUG_BACKUP) {
17991                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17992                }
17993            } else if (tagName.equals(TAG_PERMISSION)) {
17994
17995                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17996                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17997
17998                int newFlagSet = 0;
17999                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18000                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18001                }
18002                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18003                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18004                }
18005                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18006                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18007                }
18008                if (DEBUG_BACKUP) {
18009                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18010                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18011                }
18012                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18013                if (ps != null) {
18014                    // Already installed so we apply the grant immediately
18015                    if (DEBUG_BACKUP) {
18016                        Slog.v(TAG, "        + already installed; applying");
18017                    }
18018                    PermissionsState perms = ps.getPermissionsState();
18019                    BasePermission bp = mSettings.mPermissions.get(permName);
18020                    if (bp != null) {
18021                        if (isGranted) {
18022                            perms.grantRuntimePermission(bp, userId);
18023                        }
18024                        if (newFlagSet != 0) {
18025                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18026                        }
18027                    }
18028                } else {
18029                    // Need to wait for post-restore install to apply the grant
18030                    if (DEBUG_BACKUP) {
18031                        Slog.v(TAG, "        - not yet installed; saving for later");
18032                    }
18033                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18034                            isGranted, newFlagSet, userId);
18035                }
18036            } else {
18037                PackageManagerService.reportSettingsProblem(Log.WARN,
18038                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18039                XmlUtils.skipCurrentTag(parser);
18040            }
18041        }
18042
18043        scheduleWriteSettingsLocked();
18044        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18045    }
18046
18047    @Override
18048    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18049            int sourceUserId, int targetUserId, int flags) {
18050        mContext.enforceCallingOrSelfPermission(
18051                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18052        int callingUid = Binder.getCallingUid();
18053        enforceOwnerRights(ownerPackage, callingUid);
18054        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18055        if (intentFilter.countActions() == 0) {
18056            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18057            return;
18058        }
18059        synchronized (mPackages) {
18060            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18061                    ownerPackage, targetUserId, flags);
18062            CrossProfileIntentResolver resolver =
18063                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18064            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18065            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18066            if (existing != null) {
18067                int size = existing.size();
18068                for (int i = 0; i < size; i++) {
18069                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18070                        return;
18071                    }
18072                }
18073            }
18074            resolver.addFilter(newFilter);
18075            scheduleWritePackageRestrictionsLocked(sourceUserId);
18076        }
18077    }
18078
18079    @Override
18080    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18081        mContext.enforceCallingOrSelfPermission(
18082                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18083        int callingUid = Binder.getCallingUid();
18084        enforceOwnerRights(ownerPackage, callingUid);
18085        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18086        synchronized (mPackages) {
18087            CrossProfileIntentResolver resolver =
18088                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18089            ArraySet<CrossProfileIntentFilter> set =
18090                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18091            for (CrossProfileIntentFilter filter : set) {
18092                if (filter.getOwnerPackage().equals(ownerPackage)) {
18093                    resolver.removeFilter(filter);
18094                }
18095            }
18096            scheduleWritePackageRestrictionsLocked(sourceUserId);
18097        }
18098    }
18099
18100    // Enforcing that callingUid is owning pkg on userId
18101    private void enforceOwnerRights(String pkg, int callingUid) {
18102        // The system owns everything.
18103        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18104            return;
18105        }
18106        int callingUserId = UserHandle.getUserId(callingUid);
18107        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18108        if (pi == null) {
18109            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18110                    + callingUserId);
18111        }
18112        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18113            throw new SecurityException("Calling uid " + callingUid
18114                    + " does not own package " + pkg);
18115        }
18116    }
18117
18118    @Override
18119    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18120        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18121    }
18122
18123    private Intent getHomeIntent() {
18124        Intent intent = new Intent(Intent.ACTION_MAIN);
18125        intent.addCategory(Intent.CATEGORY_HOME);
18126        intent.addCategory(Intent.CATEGORY_DEFAULT);
18127        return intent;
18128    }
18129
18130    private IntentFilter getHomeFilter() {
18131        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18132        filter.addCategory(Intent.CATEGORY_HOME);
18133        filter.addCategory(Intent.CATEGORY_DEFAULT);
18134        return filter;
18135    }
18136
18137    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18138            int userId) {
18139        Intent intent  = getHomeIntent();
18140        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18141                PackageManager.GET_META_DATA, userId);
18142        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18143                true, false, false, userId);
18144
18145        allHomeCandidates.clear();
18146        if (list != null) {
18147            for (ResolveInfo ri : list) {
18148                allHomeCandidates.add(ri);
18149            }
18150        }
18151        return (preferred == null || preferred.activityInfo == null)
18152                ? null
18153                : new ComponentName(preferred.activityInfo.packageName,
18154                        preferred.activityInfo.name);
18155    }
18156
18157    @Override
18158    public void setHomeActivity(ComponentName comp, int userId) {
18159        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18160        getHomeActivitiesAsUser(homeActivities, userId);
18161
18162        boolean found = false;
18163
18164        final int size = homeActivities.size();
18165        final ComponentName[] set = new ComponentName[size];
18166        for (int i = 0; i < size; i++) {
18167            final ResolveInfo candidate = homeActivities.get(i);
18168            final ActivityInfo info = candidate.activityInfo;
18169            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18170            set[i] = activityName;
18171            if (!found && activityName.equals(comp)) {
18172                found = true;
18173            }
18174        }
18175        if (!found) {
18176            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18177                    + userId);
18178        }
18179        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18180                set, comp, userId);
18181    }
18182
18183    private @Nullable String getSetupWizardPackageName() {
18184        final Intent intent = new Intent(Intent.ACTION_MAIN);
18185        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18186
18187        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18188                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18189                        | MATCH_DISABLED_COMPONENTS,
18190                UserHandle.myUserId());
18191        if (matches.size() == 1) {
18192            return matches.get(0).getComponentInfo().packageName;
18193        } else {
18194            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18195                    + ": matches=" + matches);
18196            return null;
18197        }
18198    }
18199
18200    private @Nullable String getStorageManagerPackageName() {
18201        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18202
18203        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18204                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18205                        | MATCH_DISABLED_COMPONENTS,
18206                UserHandle.myUserId());
18207        if (matches.size() == 1) {
18208            return matches.get(0).getComponentInfo().packageName;
18209        } else {
18210            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18211                    + matches.size() + ": matches=" + matches);
18212            return null;
18213        }
18214    }
18215
18216    @Override
18217    public void setApplicationEnabledSetting(String appPackageName,
18218            int newState, int flags, int userId, String callingPackage) {
18219        if (!sUserManager.exists(userId)) return;
18220        if (callingPackage == null) {
18221            callingPackage = Integer.toString(Binder.getCallingUid());
18222        }
18223        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18224    }
18225
18226    @Override
18227    public void setComponentEnabledSetting(ComponentName componentName,
18228            int newState, int flags, int userId) {
18229        if (!sUserManager.exists(userId)) return;
18230        setEnabledSetting(componentName.getPackageName(),
18231                componentName.getClassName(), newState, flags, userId, null);
18232    }
18233
18234    private void setEnabledSetting(final String packageName, String className, int newState,
18235            final int flags, int userId, String callingPackage) {
18236        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18237              || newState == COMPONENT_ENABLED_STATE_ENABLED
18238              || newState == COMPONENT_ENABLED_STATE_DISABLED
18239              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18240              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18241            throw new IllegalArgumentException("Invalid new component state: "
18242                    + newState);
18243        }
18244        PackageSetting pkgSetting;
18245        final int uid = Binder.getCallingUid();
18246        final int permission;
18247        if (uid == Process.SYSTEM_UID) {
18248            permission = PackageManager.PERMISSION_GRANTED;
18249        } else {
18250            permission = mContext.checkCallingOrSelfPermission(
18251                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18252        }
18253        enforceCrossUserPermission(uid, userId,
18254                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18255        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18256        boolean sendNow = false;
18257        boolean isApp = (className == null);
18258        String componentName = isApp ? packageName : className;
18259        int packageUid = -1;
18260        ArrayList<String> components;
18261
18262        // writer
18263        synchronized (mPackages) {
18264            pkgSetting = mSettings.mPackages.get(packageName);
18265            if (pkgSetting == null) {
18266                if (className == null) {
18267                    throw new IllegalArgumentException("Unknown package: " + packageName);
18268                }
18269                throw new IllegalArgumentException(
18270                        "Unknown component: " + packageName + "/" + className);
18271            }
18272        }
18273
18274        // Limit who can change which apps
18275        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18276            // Don't allow apps that don't have permission to modify other apps
18277            if (!allowedByPermission) {
18278                throw new SecurityException(
18279                        "Permission Denial: attempt to change component state from pid="
18280                        + Binder.getCallingPid()
18281                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18282            }
18283            // Don't allow changing protected packages.
18284            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18285                throw new SecurityException("Cannot disable a protected package: " + packageName);
18286            }
18287        }
18288
18289        synchronized (mPackages) {
18290            if (uid == Process.SHELL_UID
18291                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18292                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18293                // unless it is a test package.
18294                int oldState = pkgSetting.getEnabled(userId);
18295                if (className == null
18296                    &&
18297                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18298                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18299                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18300                    &&
18301                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18302                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18303                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18304                    // ok
18305                } else {
18306                    throw new SecurityException(
18307                            "Shell cannot change component state for " + packageName + "/"
18308                            + className + " to " + newState);
18309                }
18310            }
18311            if (className == null) {
18312                // We're dealing with an application/package level state change
18313                if (pkgSetting.getEnabled(userId) == newState) {
18314                    // Nothing to do
18315                    return;
18316                }
18317                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18318                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18319                    // Don't care about who enables an app.
18320                    callingPackage = null;
18321                }
18322                pkgSetting.setEnabled(newState, userId, callingPackage);
18323                // pkgSetting.pkg.mSetEnabled = newState;
18324            } else {
18325                // We're dealing with a component level state change
18326                // First, verify that this is a valid class name.
18327                PackageParser.Package pkg = pkgSetting.pkg;
18328                if (pkg == null || !pkg.hasComponentClassName(className)) {
18329                    if (pkg != null &&
18330                            pkg.applicationInfo.targetSdkVersion >=
18331                                    Build.VERSION_CODES.JELLY_BEAN) {
18332                        throw new IllegalArgumentException("Component class " + className
18333                                + " does not exist in " + packageName);
18334                    } else {
18335                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18336                                + className + " does not exist in " + packageName);
18337                    }
18338                }
18339                switch (newState) {
18340                case COMPONENT_ENABLED_STATE_ENABLED:
18341                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18342                        return;
18343                    }
18344                    break;
18345                case COMPONENT_ENABLED_STATE_DISABLED:
18346                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18347                        return;
18348                    }
18349                    break;
18350                case COMPONENT_ENABLED_STATE_DEFAULT:
18351                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18352                        return;
18353                    }
18354                    break;
18355                default:
18356                    Slog.e(TAG, "Invalid new component state: " + newState);
18357                    return;
18358                }
18359            }
18360            scheduleWritePackageRestrictionsLocked(userId);
18361            components = mPendingBroadcasts.get(userId, packageName);
18362            final boolean newPackage = components == null;
18363            if (newPackage) {
18364                components = new ArrayList<String>();
18365            }
18366            if (!components.contains(componentName)) {
18367                components.add(componentName);
18368            }
18369            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18370                sendNow = true;
18371                // Purge entry from pending broadcast list if another one exists already
18372                // since we are sending one right away.
18373                mPendingBroadcasts.remove(userId, packageName);
18374            } else {
18375                if (newPackage) {
18376                    mPendingBroadcasts.put(userId, packageName, components);
18377                }
18378                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18379                    // Schedule a message
18380                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18381                }
18382            }
18383        }
18384
18385        long callingId = Binder.clearCallingIdentity();
18386        try {
18387            if (sendNow) {
18388                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18389                sendPackageChangedBroadcast(packageName,
18390                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18391            }
18392        } finally {
18393            Binder.restoreCallingIdentity(callingId);
18394        }
18395    }
18396
18397    @Override
18398    public void flushPackageRestrictionsAsUser(int userId) {
18399        if (!sUserManager.exists(userId)) {
18400            return;
18401        }
18402        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18403                false /* checkShell */, "flushPackageRestrictions");
18404        synchronized (mPackages) {
18405            mSettings.writePackageRestrictionsLPr(userId);
18406            mDirtyUsers.remove(userId);
18407            if (mDirtyUsers.isEmpty()) {
18408                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18409            }
18410        }
18411    }
18412
18413    private void sendPackageChangedBroadcast(String packageName,
18414            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18415        if (DEBUG_INSTALL)
18416            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18417                    + componentNames);
18418        Bundle extras = new Bundle(4);
18419        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18420        String nameList[] = new String[componentNames.size()];
18421        componentNames.toArray(nameList);
18422        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18423        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18424        extras.putInt(Intent.EXTRA_UID, packageUid);
18425        // If this is not reporting a change of the overall package, then only send it
18426        // to registered receivers.  We don't want to launch a swath of apps for every
18427        // little component state change.
18428        final int flags = !componentNames.contains(packageName)
18429                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18430        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18431                new int[] {UserHandle.getUserId(packageUid)});
18432    }
18433
18434    @Override
18435    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18436        if (!sUserManager.exists(userId)) return;
18437        final int uid = Binder.getCallingUid();
18438        final int permission = mContext.checkCallingOrSelfPermission(
18439                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18440        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18441        enforceCrossUserPermission(uid, userId,
18442                true /* requireFullPermission */, true /* checkShell */, "stop package");
18443        // writer
18444        synchronized (mPackages) {
18445            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18446                    allowedByPermission, uid, userId)) {
18447                scheduleWritePackageRestrictionsLocked(userId);
18448            }
18449        }
18450    }
18451
18452    @Override
18453    public String getInstallerPackageName(String packageName) {
18454        // reader
18455        synchronized (mPackages) {
18456            return mSettings.getInstallerPackageNameLPr(packageName);
18457        }
18458    }
18459
18460    public boolean isOrphaned(String packageName) {
18461        // reader
18462        synchronized (mPackages) {
18463            return mSettings.isOrphaned(packageName);
18464        }
18465    }
18466
18467    @Override
18468    public int getApplicationEnabledSetting(String packageName, int userId) {
18469        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18470        int uid = Binder.getCallingUid();
18471        enforceCrossUserPermission(uid, userId,
18472                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18473        // reader
18474        synchronized (mPackages) {
18475            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18476        }
18477    }
18478
18479    @Override
18480    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18481        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18482        int uid = Binder.getCallingUid();
18483        enforceCrossUserPermission(uid, userId,
18484                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18485        // reader
18486        synchronized (mPackages) {
18487            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18488        }
18489    }
18490
18491    @Override
18492    public void enterSafeMode() {
18493        enforceSystemOrRoot("Only the system can request entering safe mode");
18494
18495        if (!mSystemReady) {
18496            mSafeMode = true;
18497        }
18498    }
18499
18500    @Override
18501    public void systemReady() {
18502        mSystemReady = true;
18503
18504        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18505        // disabled after already being started.
18506        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18507                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18508
18509        // Read the compatibilty setting when the system is ready.
18510        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18511                mContext.getContentResolver(),
18512                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18513        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18514        if (DEBUG_SETTINGS) {
18515            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18516        }
18517
18518        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18519
18520        synchronized (mPackages) {
18521            // Verify that all of the preferred activity components actually
18522            // exist.  It is possible for applications to be updated and at
18523            // that point remove a previously declared activity component that
18524            // had been set as a preferred activity.  We try to clean this up
18525            // the next time we encounter that preferred activity, but it is
18526            // possible for the user flow to never be able to return to that
18527            // situation so here we do a sanity check to make sure we haven't
18528            // left any junk around.
18529            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18530            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18531                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18532                removed.clear();
18533                for (PreferredActivity pa : pir.filterSet()) {
18534                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18535                        removed.add(pa);
18536                    }
18537                }
18538                if (removed.size() > 0) {
18539                    for (int r=0; r<removed.size(); r++) {
18540                        PreferredActivity pa = removed.get(r);
18541                        Slog.w(TAG, "Removing dangling preferred activity: "
18542                                + pa.mPref.mComponent);
18543                        pir.removeFilter(pa);
18544                    }
18545                    mSettings.writePackageRestrictionsLPr(
18546                            mSettings.mPreferredActivities.keyAt(i));
18547                }
18548            }
18549
18550            for (int userId : UserManagerService.getInstance().getUserIds()) {
18551                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18552                    grantPermissionsUserIds = ArrayUtils.appendInt(
18553                            grantPermissionsUserIds, userId);
18554                }
18555            }
18556        }
18557        sUserManager.systemReady();
18558
18559        // If we upgraded grant all default permissions before kicking off.
18560        for (int userId : grantPermissionsUserIds) {
18561            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18562        }
18563
18564        // If we did not grant default permissions, we preload from this the
18565        // default permission exceptions lazily to ensure we don't hit the
18566        // disk on a new user creation.
18567        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18568            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18569        }
18570
18571        // Kick off any messages waiting for system ready
18572        if (mPostSystemReadyMessages != null) {
18573            for (Message msg : mPostSystemReadyMessages) {
18574                msg.sendToTarget();
18575            }
18576            mPostSystemReadyMessages = null;
18577        }
18578
18579        // Watch for external volumes that come and go over time
18580        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18581        storage.registerListener(mStorageListener);
18582
18583        mInstallerService.systemReady();
18584        mPackageDexOptimizer.systemReady();
18585
18586        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18587                StorageManagerInternal.class);
18588        StorageManagerInternal.addExternalStoragePolicy(
18589                new StorageManagerInternal.ExternalStorageMountPolicy() {
18590            @Override
18591            public int getMountMode(int uid, String packageName) {
18592                if (Process.isIsolated(uid)) {
18593                    return Zygote.MOUNT_EXTERNAL_NONE;
18594                }
18595                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18596                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18597                }
18598                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18599                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18600                }
18601                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18602                    return Zygote.MOUNT_EXTERNAL_READ;
18603                }
18604                return Zygote.MOUNT_EXTERNAL_WRITE;
18605            }
18606
18607            @Override
18608            public boolean hasExternalStorage(int uid, String packageName) {
18609                return true;
18610            }
18611        });
18612
18613        // Now that we're mostly running, clean up stale users and apps
18614        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18615        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18616    }
18617
18618    @Override
18619    public boolean isSafeMode() {
18620        return mSafeMode;
18621    }
18622
18623    @Override
18624    public boolean hasSystemUidErrors() {
18625        return mHasSystemUidErrors;
18626    }
18627
18628    static String arrayToString(int[] array) {
18629        StringBuffer buf = new StringBuffer(128);
18630        buf.append('[');
18631        if (array != null) {
18632            for (int i=0; i<array.length; i++) {
18633                if (i > 0) buf.append(", ");
18634                buf.append(array[i]);
18635            }
18636        }
18637        buf.append(']');
18638        return buf.toString();
18639    }
18640
18641    static class DumpState {
18642        public static final int DUMP_LIBS = 1 << 0;
18643        public static final int DUMP_FEATURES = 1 << 1;
18644        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18645        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18646        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18647        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18648        public static final int DUMP_PERMISSIONS = 1 << 6;
18649        public static final int DUMP_PACKAGES = 1 << 7;
18650        public static final int DUMP_SHARED_USERS = 1 << 8;
18651        public static final int DUMP_MESSAGES = 1 << 9;
18652        public static final int DUMP_PROVIDERS = 1 << 10;
18653        public static final int DUMP_VERIFIERS = 1 << 11;
18654        public static final int DUMP_PREFERRED = 1 << 12;
18655        public static final int DUMP_PREFERRED_XML = 1 << 13;
18656        public static final int DUMP_KEYSETS = 1 << 14;
18657        public static final int DUMP_VERSION = 1 << 15;
18658        public static final int DUMP_INSTALLS = 1 << 16;
18659        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18660        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18661        public static final int DUMP_FROZEN = 1 << 19;
18662        public static final int DUMP_DEXOPT = 1 << 20;
18663        public static final int DUMP_COMPILER_STATS = 1 << 21;
18664
18665        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18666
18667        private int mTypes;
18668
18669        private int mOptions;
18670
18671        private boolean mTitlePrinted;
18672
18673        private SharedUserSetting mSharedUser;
18674
18675        public boolean isDumping(int type) {
18676            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18677                return true;
18678            }
18679
18680            return (mTypes & type) != 0;
18681        }
18682
18683        public void setDump(int type) {
18684            mTypes |= type;
18685        }
18686
18687        public boolean isOptionEnabled(int option) {
18688            return (mOptions & option) != 0;
18689        }
18690
18691        public void setOptionEnabled(int option) {
18692            mOptions |= option;
18693        }
18694
18695        public boolean onTitlePrinted() {
18696            final boolean printed = mTitlePrinted;
18697            mTitlePrinted = true;
18698            return printed;
18699        }
18700
18701        public boolean getTitlePrinted() {
18702            return mTitlePrinted;
18703        }
18704
18705        public void setTitlePrinted(boolean enabled) {
18706            mTitlePrinted = enabled;
18707        }
18708
18709        public SharedUserSetting getSharedUser() {
18710            return mSharedUser;
18711        }
18712
18713        public void setSharedUser(SharedUserSetting user) {
18714            mSharedUser = user;
18715        }
18716    }
18717
18718    @Override
18719    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18720            FileDescriptor err, String[] args, ShellCallback callback,
18721            ResultReceiver resultReceiver) {
18722        (new PackageManagerShellCommand(this)).exec(
18723                this, in, out, err, args, callback, resultReceiver);
18724    }
18725
18726    @Override
18727    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18728        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18729                != PackageManager.PERMISSION_GRANTED) {
18730            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18731                    + Binder.getCallingPid()
18732                    + ", uid=" + Binder.getCallingUid()
18733                    + " without permission "
18734                    + android.Manifest.permission.DUMP);
18735            return;
18736        }
18737
18738        DumpState dumpState = new DumpState();
18739        boolean fullPreferred = false;
18740        boolean checkin = false;
18741
18742        String packageName = null;
18743        ArraySet<String> permissionNames = null;
18744
18745        int opti = 0;
18746        while (opti < args.length) {
18747            String opt = args[opti];
18748            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18749                break;
18750            }
18751            opti++;
18752
18753            if ("-a".equals(opt)) {
18754                // Right now we only know how to print all.
18755            } else if ("-h".equals(opt)) {
18756                pw.println("Package manager dump options:");
18757                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18758                pw.println("    --checkin: dump for a checkin");
18759                pw.println("    -f: print details of intent filters");
18760                pw.println("    -h: print this help");
18761                pw.println("  cmd may be one of:");
18762                pw.println("    l[ibraries]: list known shared libraries");
18763                pw.println("    f[eatures]: list device features");
18764                pw.println("    k[eysets]: print known keysets");
18765                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18766                pw.println("    perm[issions]: dump permissions");
18767                pw.println("    permission [name ...]: dump declaration and use of given permission");
18768                pw.println("    pref[erred]: print preferred package settings");
18769                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18770                pw.println("    prov[iders]: dump content providers");
18771                pw.println("    p[ackages]: dump installed packages");
18772                pw.println("    s[hared-users]: dump shared user IDs");
18773                pw.println("    m[essages]: print collected runtime messages");
18774                pw.println("    v[erifiers]: print package verifier info");
18775                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18776                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18777                pw.println("    version: print database version info");
18778                pw.println("    write: write current settings now");
18779                pw.println("    installs: details about install sessions");
18780                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18781                pw.println("    dexopt: dump dexopt state");
18782                pw.println("    compiler-stats: dump compiler statistics");
18783                pw.println("    <package.name>: info about given package");
18784                return;
18785            } else if ("--checkin".equals(opt)) {
18786                checkin = true;
18787            } else if ("-f".equals(opt)) {
18788                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18789            } else {
18790                pw.println("Unknown argument: " + opt + "; use -h for help");
18791            }
18792        }
18793
18794        // Is the caller requesting to dump a particular piece of data?
18795        if (opti < args.length) {
18796            String cmd = args[opti];
18797            opti++;
18798            // Is this a package name?
18799            if ("android".equals(cmd) || cmd.contains(".")) {
18800                packageName = cmd;
18801                // When dumping a single package, we always dump all of its
18802                // filter information since the amount of data will be reasonable.
18803                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18804            } else if ("check-permission".equals(cmd)) {
18805                if (opti >= args.length) {
18806                    pw.println("Error: check-permission missing permission argument");
18807                    return;
18808                }
18809                String perm = args[opti];
18810                opti++;
18811                if (opti >= args.length) {
18812                    pw.println("Error: check-permission missing package argument");
18813                    return;
18814                }
18815                String pkg = args[opti];
18816                opti++;
18817                int user = UserHandle.getUserId(Binder.getCallingUid());
18818                if (opti < args.length) {
18819                    try {
18820                        user = Integer.parseInt(args[opti]);
18821                    } catch (NumberFormatException e) {
18822                        pw.println("Error: check-permission user argument is not a number: "
18823                                + args[opti]);
18824                        return;
18825                    }
18826                }
18827                pw.println(checkPermission(perm, pkg, user));
18828                return;
18829            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18830                dumpState.setDump(DumpState.DUMP_LIBS);
18831            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18832                dumpState.setDump(DumpState.DUMP_FEATURES);
18833            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18834                if (opti >= args.length) {
18835                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18836                            | DumpState.DUMP_SERVICE_RESOLVERS
18837                            | DumpState.DUMP_RECEIVER_RESOLVERS
18838                            | DumpState.DUMP_CONTENT_RESOLVERS);
18839                } else {
18840                    while (opti < args.length) {
18841                        String name = args[opti];
18842                        if ("a".equals(name) || "activity".equals(name)) {
18843                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18844                        } else if ("s".equals(name) || "service".equals(name)) {
18845                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18846                        } else if ("r".equals(name) || "receiver".equals(name)) {
18847                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18848                        } else if ("c".equals(name) || "content".equals(name)) {
18849                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18850                        } else {
18851                            pw.println("Error: unknown resolver table type: " + name);
18852                            return;
18853                        }
18854                        opti++;
18855                    }
18856                }
18857            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18858                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18859            } else if ("permission".equals(cmd)) {
18860                if (opti >= args.length) {
18861                    pw.println("Error: permission requires permission name");
18862                    return;
18863                }
18864                permissionNames = new ArraySet<>();
18865                while (opti < args.length) {
18866                    permissionNames.add(args[opti]);
18867                    opti++;
18868                }
18869                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18870                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18871            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18872                dumpState.setDump(DumpState.DUMP_PREFERRED);
18873            } else if ("preferred-xml".equals(cmd)) {
18874                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18875                if (opti < args.length && "--full".equals(args[opti])) {
18876                    fullPreferred = true;
18877                    opti++;
18878                }
18879            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18880                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18881            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18882                dumpState.setDump(DumpState.DUMP_PACKAGES);
18883            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18884                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18885            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18886                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18887            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18888                dumpState.setDump(DumpState.DUMP_MESSAGES);
18889            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18890                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18891            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18892                    || "intent-filter-verifiers".equals(cmd)) {
18893                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18894            } else if ("version".equals(cmd)) {
18895                dumpState.setDump(DumpState.DUMP_VERSION);
18896            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18897                dumpState.setDump(DumpState.DUMP_KEYSETS);
18898            } else if ("installs".equals(cmd)) {
18899                dumpState.setDump(DumpState.DUMP_INSTALLS);
18900            } else if ("frozen".equals(cmd)) {
18901                dumpState.setDump(DumpState.DUMP_FROZEN);
18902            } else if ("dexopt".equals(cmd)) {
18903                dumpState.setDump(DumpState.DUMP_DEXOPT);
18904            } else if ("compiler-stats".equals(cmd)) {
18905                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18906            } else if ("write".equals(cmd)) {
18907                synchronized (mPackages) {
18908                    mSettings.writeLPr();
18909                    pw.println("Settings written.");
18910                    return;
18911                }
18912            }
18913        }
18914
18915        if (checkin) {
18916            pw.println("vers,1");
18917        }
18918
18919        // reader
18920        synchronized (mPackages) {
18921            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18922                if (!checkin) {
18923                    if (dumpState.onTitlePrinted())
18924                        pw.println();
18925                    pw.println("Database versions:");
18926                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18927                }
18928            }
18929
18930            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18931                if (!checkin) {
18932                    if (dumpState.onTitlePrinted())
18933                        pw.println();
18934                    pw.println("Verifiers:");
18935                    pw.print("  Required: ");
18936                    pw.print(mRequiredVerifierPackage);
18937                    pw.print(" (uid=");
18938                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18939                            UserHandle.USER_SYSTEM));
18940                    pw.println(")");
18941                } else if (mRequiredVerifierPackage != null) {
18942                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18943                    pw.print(",");
18944                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18945                            UserHandle.USER_SYSTEM));
18946                }
18947            }
18948
18949            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18950                    packageName == null) {
18951                if (mIntentFilterVerifierComponent != null) {
18952                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18953                    if (!checkin) {
18954                        if (dumpState.onTitlePrinted())
18955                            pw.println();
18956                        pw.println("Intent Filter Verifier:");
18957                        pw.print("  Using: ");
18958                        pw.print(verifierPackageName);
18959                        pw.print(" (uid=");
18960                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18961                                UserHandle.USER_SYSTEM));
18962                        pw.println(")");
18963                    } else if (verifierPackageName != null) {
18964                        pw.print("ifv,"); pw.print(verifierPackageName);
18965                        pw.print(",");
18966                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18967                                UserHandle.USER_SYSTEM));
18968                    }
18969                } else {
18970                    pw.println();
18971                    pw.println("No Intent Filter Verifier available!");
18972                }
18973            }
18974
18975            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18976                boolean printedHeader = false;
18977                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18978                while (it.hasNext()) {
18979                    String name = it.next();
18980                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18981                    if (!checkin) {
18982                        if (!printedHeader) {
18983                            if (dumpState.onTitlePrinted())
18984                                pw.println();
18985                            pw.println("Libraries:");
18986                            printedHeader = true;
18987                        }
18988                        pw.print("  ");
18989                    } else {
18990                        pw.print("lib,");
18991                    }
18992                    pw.print(name);
18993                    if (!checkin) {
18994                        pw.print(" -> ");
18995                    }
18996                    if (ent.path != null) {
18997                        if (!checkin) {
18998                            pw.print("(jar) ");
18999                            pw.print(ent.path);
19000                        } else {
19001                            pw.print(",jar,");
19002                            pw.print(ent.path);
19003                        }
19004                    } else {
19005                        if (!checkin) {
19006                            pw.print("(apk) ");
19007                            pw.print(ent.apk);
19008                        } else {
19009                            pw.print(",apk,");
19010                            pw.print(ent.apk);
19011                        }
19012                    }
19013                    pw.println();
19014                }
19015            }
19016
19017            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19018                if (dumpState.onTitlePrinted())
19019                    pw.println();
19020                if (!checkin) {
19021                    pw.println("Features:");
19022                }
19023
19024                for (FeatureInfo feat : mAvailableFeatures.values()) {
19025                    if (checkin) {
19026                        pw.print("feat,");
19027                        pw.print(feat.name);
19028                        pw.print(",");
19029                        pw.println(feat.version);
19030                    } else {
19031                        pw.print("  ");
19032                        pw.print(feat.name);
19033                        if (feat.version > 0) {
19034                            pw.print(" version=");
19035                            pw.print(feat.version);
19036                        }
19037                        pw.println();
19038                    }
19039                }
19040            }
19041
19042            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19043                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19044                        : "Activity Resolver Table:", "  ", packageName,
19045                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19046                    dumpState.setTitlePrinted(true);
19047                }
19048            }
19049            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19050                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19051                        : "Receiver Resolver Table:", "  ", packageName,
19052                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19053                    dumpState.setTitlePrinted(true);
19054                }
19055            }
19056            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19057                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19058                        : "Service Resolver Table:", "  ", packageName,
19059                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19060                    dumpState.setTitlePrinted(true);
19061                }
19062            }
19063            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19064                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19065                        : "Provider Resolver Table:", "  ", packageName,
19066                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19067                    dumpState.setTitlePrinted(true);
19068                }
19069            }
19070
19071            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19072                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19073                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19074                    int user = mSettings.mPreferredActivities.keyAt(i);
19075                    if (pir.dump(pw,
19076                            dumpState.getTitlePrinted()
19077                                ? "\nPreferred Activities User " + user + ":"
19078                                : "Preferred Activities User " + user + ":", "  ",
19079                            packageName, true, false)) {
19080                        dumpState.setTitlePrinted(true);
19081                    }
19082                }
19083            }
19084
19085            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19086                pw.flush();
19087                FileOutputStream fout = new FileOutputStream(fd);
19088                BufferedOutputStream str = new BufferedOutputStream(fout);
19089                XmlSerializer serializer = new FastXmlSerializer();
19090                try {
19091                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19092                    serializer.startDocument(null, true);
19093                    serializer.setFeature(
19094                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19095                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19096                    serializer.endDocument();
19097                    serializer.flush();
19098                } catch (IllegalArgumentException e) {
19099                    pw.println("Failed writing: " + e);
19100                } catch (IllegalStateException e) {
19101                    pw.println("Failed writing: " + e);
19102                } catch (IOException e) {
19103                    pw.println("Failed writing: " + e);
19104                }
19105            }
19106
19107            if (!checkin
19108                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19109                    && packageName == null) {
19110                pw.println();
19111                int count = mSettings.mPackages.size();
19112                if (count == 0) {
19113                    pw.println("No applications!");
19114                    pw.println();
19115                } else {
19116                    final String prefix = "  ";
19117                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19118                    if (allPackageSettings.size() == 0) {
19119                        pw.println("No domain preferred apps!");
19120                        pw.println();
19121                    } else {
19122                        pw.println("App verification status:");
19123                        pw.println();
19124                        count = 0;
19125                        for (PackageSetting ps : allPackageSettings) {
19126                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19127                            if (ivi == null || ivi.getPackageName() == null) continue;
19128                            pw.println(prefix + "Package: " + ivi.getPackageName());
19129                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19130                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19131                            pw.println();
19132                            count++;
19133                        }
19134                        if (count == 0) {
19135                            pw.println(prefix + "No app verification established.");
19136                            pw.println();
19137                        }
19138                        for (int userId : sUserManager.getUserIds()) {
19139                            pw.println("App linkages for user " + userId + ":");
19140                            pw.println();
19141                            count = 0;
19142                            for (PackageSetting ps : allPackageSettings) {
19143                                final long status = ps.getDomainVerificationStatusForUser(userId);
19144                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19145                                    continue;
19146                                }
19147                                pw.println(prefix + "Package: " + ps.name);
19148                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19149                                String statusStr = IntentFilterVerificationInfo.
19150                                        getStatusStringFromValue(status);
19151                                pw.println(prefix + "Status:  " + statusStr);
19152                                pw.println();
19153                                count++;
19154                            }
19155                            if (count == 0) {
19156                                pw.println(prefix + "No configured app linkages.");
19157                                pw.println();
19158                            }
19159                        }
19160                    }
19161                }
19162            }
19163
19164            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19165                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19166                if (packageName == null && permissionNames == null) {
19167                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19168                        if (iperm == 0) {
19169                            if (dumpState.onTitlePrinted())
19170                                pw.println();
19171                            pw.println("AppOp Permissions:");
19172                        }
19173                        pw.print("  AppOp Permission ");
19174                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19175                        pw.println(":");
19176                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19177                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19178                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19179                        }
19180                    }
19181                }
19182            }
19183
19184            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19185                boolean printedSomething = false;
19186                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19187                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19188                        continue;
19189                    }
19190                    if (!printedSomething) {
19191                        if (dumpState.onTitlePrinted())
19192                            pw.println();
19193                        pw.println("Registered ContentProviders:");
19194                        printedSomething = true;
19195                    }
19196                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19197                    pw.print("    "); pw.println(p.toString());
19198                }
19199                printedSomething = false;
19200                for (Map.Entry<String, PackageParser.Provider> entry :
19201                        mProvidersByAuthority.entrySet()) {
19202                    PackageParser.Provider p = entry.getValue();
19203                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19204                        continue;
19205                    }
19206                    if (!printedSomething) {
19207                        if (dumpState.onTitlePrinted())
19208                            pw.println();
19209                        pw.println("ContentProvider Authorities:");
19210                        printedSomething = true;
19211                    }
19212                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19213                    pw.print("    "); pw.println(p.toString());
19214                    if (p.info != null && p.info.applicationInfo != null) {
19215                        final String appInfo = p.info.applicationInfo.toString();
19216                        pw.print("      applicationInfo="); pw.println(appInfo);
19217                    }
19218                }
19219            }
19220
19221            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19222                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19223            }
19224
19225            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19226                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19227            }
19228
19229            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19230                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19231            }
19232
19233            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19234                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19235            }
19236
19237            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19238                // XXX should handle packageName != null by dumping only install data that
19239                // the given package is involved with.
19240                if (dumpState.onTitlePrinted()) pw.println();
19241                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19242            }
19243
19244            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19245                // XXX should handle packageName != null by dumping only install data that
19246                // the given package is involved with.
19247                if (dumpState.onTitlePrinted()) pw.println();
19248
19249                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19250                ipw.println();
19251                ipw.println("Frozen packages:");
19252                ipw.increaseIndent();
19253                if (mFrozenPackages.size() == 0) {
19254                    ipw.println("(none)");
19255                } else {
19256                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19257                        ipw.println(mFrozenPackages.valueAt(i));
19258                    }
19259                }
19260                ipw.decreaseIndent();
19261            }
19262
19263            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19264                if (dumpState.onTitlePrinted()) pw.println();
19265                dumpDexoptStateLPr(pw, packageName);
19266            }
19267
19268            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19269                if (dumpState.onTitlePrinted()) pw.println();
19270                dumpCompilerStatsLPr(pw, packageName);
19271            }
19272
19273            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19274                if (dumpState.onTitlePrinted()) pw.println();
19275                mSettings.dumpReadMessagesLPr(pw, dumpState);
19276
19277                pw.println();
19278                pw.println("Package warning messages:");
19279                BufferedReader in = null;
19280                String line = null;
19281                try {
19282                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19283                    while ((line = in.readLine()) != null) {
19284                        if (line.contains("ignored: updated version")) continue;
19285                        pw.println(line);
19286                    }
19287                } catch (IOException ignored) {
19288                } finally {
19289                    IoUtils.closeQuietly(in);
19290                }
19291            }
19292
19293            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19294                BufferedReader in = null;
19295                String line = null;
19296                try {
19297                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19298                    while ((line = in.readLine()) != null) {
19299                        if (line.contains("ignored: updated version")) continue;
19300                        pw.print("msg,");
19301                        pw.println(line);
19302                    }
19303                } catch (IOException ignored) {
19304                } finally {
19305                    IoUtils.closeQuietly(in);
19306                }
19307            }
19308        }
19309    }
19310
19311    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19312        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19313        ipw.println();
19314        ipw.println("Dexopt state:");
19315        ipw.increaseIndent();
19316        Collection<PackageParser.Package> packages = null;
19317        if (packageName != null) {
19318            PackageParser.Package targetPackage = mPackages.get(packageName);
19319            if (targetPackage != null) {
19320                packages = Collections.singletonList(targetPackage);
19321            } else {
19322                ipw.println("Unable to find package: " + packageName);
19323                return;
19324            }
19325        } else {
19326            packages = mPackages.values();
19327        }
19328
19329        for (PackageParser.Package pkg : packages) {
19330            ipw.println("[" + pkg.packageName + "]");
19331            ipw.increaseIndent();
19332            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19333            ipw.decreaseIndent();
19334        }
19335    }
19336
19337    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19338        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19339        ipw.println();
19340        ipw.println("Compiler stats:");
19341        ipw.increaseIndent();
19342        Collection<PackageParser.Package> packages = null;
19343        if (packageName != null) {
19344            PackageParser.Package targetPackage = mPackages.get(packageName);
19345            if (targetPackage != null) {
19346                packages = Collections.singletonList(targetPackage);
19347            } else {
19348                ipw.println("Unable to find package: " + packageName);
19349                return;
19350            }
19351        } else {
19352            packages = mPackages.values();
19353        }
19354
19355        for (PackageParser.Package pkg : packages) {
19356            ipw.println("[" + pkg.packageName + "]");
19357            ipw.increaseIndent();
19358
19359            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19360            if (stats == null) {
19361                ipw.println("(No recorded stats)");
19362            } else {
19363                stats.dump(ipw);
19364            }
19365            ipw.decreaseIndent();
19366        }
19367    }
19368
19369    private String dumpDomainString(String packageName) {
19370        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19371                .getList();
19372        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19373
19374        ArraySet<String> result = new ArraySet<>();
19375        if (iviList.size() > 0) {
19376            for (IntentFilterVerificationInfo ivi : iviList) {
19377                for (String host : ivi.getDomains()) {
19378                    result.add(host);
19379                }
19380            }
19381        }
19382        if (filters != null && filters.size() > 0) {
19383            for (IntentFilter filter : filters) {
19384                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19385                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19386                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19387                    result.addAll(filter.getHostsList());
19388                }
19389            }
19390        }
19391
19392        StringBuilder sb = new StringBuilder(result.size() * 16);
19393        for (String domain : result) {
19394            if (sb.length() > 0) sb.append(" ");
19395            sb.append(domain);
19396        }
19397        return sb.toString();
19398    }
19399
19400    // ------- apps on sdcard specific code -------
19401    static final boolean DEBUG_SD_INSTALL = false;
19402
19403    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19404
19405    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19406
19407    private boolean mMediaMounted = false;
19408
19409    static String getEncryptKey() {
19410        try {
19411            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19412                    SD_ENCRYPTION_KEYSTORE_NAME);
19413            if (sdEncKey == null) {
19414                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19415                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19416                if (sdEncKey == null) {
19417                    Slog.e(TAG, "Failed to create encryption keys");
19418                    return null;
19419                }
19420            }
19421            return sdEncKey;
19422        } catch (NoSuchAlgorithmException nsae) {
19423            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19424            return null;
19425        } catch (IOException ioe) {
19426            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19427            return null;
19428        }
19429    }
19430
19431    /*
19432     * Update media status on PackageManager.
19433     */
19434    @Override
19435    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19436        int callingUid = Binder.getCallingUid();
19437        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19438            throw new SecurityException("Media status can only be updated by the system");
19439        }
19440        // reader; this apparently protects mMediaMounted, but should probably
19441        // be a different lock in that case.
19442        synchronized (mPackages) {
19443            Log.i(TAG, "Updating external media status from "
19444                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19445                    + (mediaStatus ? "mounted" : "unmounted"));
19446            if (DEBUG_SD_INSTALL)
19447                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19448                        + ", mMediaMounted=" + mMediaMounted);
19449            if (mediaStatus == mMediaMounted) {
19450                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19451                        : 0, -1);
19452                mHandler.sendMessage(msg);
19453                return;
19454            }
19455            mMediaMounted = mediaStatus;
19456        }
19457        // Queue up an async operation since the package installation may take a
19458        // little while.
19459        mHandler.post(new Runnable() {
19460            public void run() {
19461                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19462            }
19463        });
19464    }
19465
19466    /**
19467     * Called by StorageManagerService when the initial ASECs to scan are available.
19468     * Should block until all the ASEC containers are finished being scanned.
19469     */
19470    public void scanAvailableAsecs() {
19471        updateExternalMediaStatusInner(true, false, false);
19472    }
19473
19474    /*
19475     * Collect information of applications on external media, map them against
19476     * existing containers and update information based on current mount status.
19477     * Please note that we always have to report status if reportStatus has been
19478     * set to true especially when unloading packages.
19479     */
19480    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19481            boolean externalStorage) {
19482        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19483        int[] uidArr = EmptyArray.INT;
19484
19485        final String[] list = PackageHelper.getSecureContainerList();
19486        if (ArrayUtils.isEmpty(list)) {
19487            Log.i(TAG, "No secure containers found");
19488        } else {
19489            // Process list of secure containers and categorize them
19490            // as active or stale based on their package internal state.
19491
19492            // reader
19493            synchronized (mPackages) {
19494                for (String cid : list) {
19495                    // Leave stages untouched for now; installer service owns them
19496                    if (PackageInstallerService.isStageName(cid)) continue;
19497
19498                    if (DEBUG_SD_INSTALL)
19499                        Log.i(TAG, "Processing container " + cid);
19500                    String pkgName = getAsecPackageName(cid);
19501                    if (pkgName == null) {
19502                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19503                        continue;
19504                    }
19505                    if (DEBUG_SD_INSTALL)
19506                        Log.i(TAG, "Looking for pkg : " + pkgName);
19507
19508                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19509                    if (ps == null) {
19510                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19511                        continue;
19512                    }
19513
19514                    /*
19515                     * Skip packages that are not external if we're unmounting
19516                     * external storage.
19517                     */
19518                    if (externalStorage && !isMounted && !isExternal(ps)) {
19519                        continue;
19520                    }
19521
19522                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19523                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19524                    // The package status is changed only if the code path
19525                    // matches between settings and the container id.
19526                    if (ps.codePathString != null
19527                            && ps.codePathString.startsWith(args.getCodePath())) {
19528                        if (DEBUG_SD_INSTALL) {
19529                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19530                                    + " at code path: " + ps.codePathString);
19531                        }
19532
19533                        // We do have a valid package installed on sdcard
19534                        processCids.put(args, ps.codePathString);
19535                        final int uid = ps.appId;
19536                        if (uid != -1) {
19537                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19538                        }
19539                    } else {
19540                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19541                                + ps.codePathString);
19542                    }
19543                }
19544            }
19545
19546            Arrays.sort(uidArr);
19547        }
19548
19549        // Process packages with valid entries.
19550        if (isMounted) {
19551            if (DEBUG_SD_INSTALL)
19552                Log.i(TAG, "Loading packages");
19553            loadMediaPackages(processCids, uidArr, externalStorage);
19554            startCleaningPackages();
19555            mInstallerService.onSecureContainersAvailable();
19556        } else {
19557            if (DEBUG_SD_INSTALL)
19558                Log.i(TAG, "Unloading packages");
19559            unloadMediaPackages(processCids, uidArr, reportStatus);
19560        }
19561    }
19562
19563    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19564            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19565        final int size = infos.size();
19566        final String[] packageNames = new String[size];
19567        final int[] packageUids = new int[size];
19568        for (int i = 0; i < size; i++) {
19569            final ApplicationInfo info = infos.get(i);
19570            packageNames[i] = info.packageName;
19571            packageUids[i] = info.uid;
19572        }
19573        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19574                finishedReceiver);
19575    }
19576
19577    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19578            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19579        sendResourcesChangedBroadcast(mediaStatus, replacing,
19580                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19581    }
19582
19583    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19584            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19585        int size = pkgList.length;
19586        if (size > 0) {
19587            // Send broadcasts here
19588            Bundle extras = new Bundle();
19589            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19590            if (uidArr != null) {
19591                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19592            }
19593            if (replacing) {
19594                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19595            }
19596            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19597                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19598            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19599        }
19600    }
19601
19602   /*
19603     * Look at potentially valid container ids from processCids If package
19604     * information doesn't match the one on record or package scanning fails,
19605     * the cid is added to list of removeCids. We currently don't delete stale
19606     * containers.
19607     */
19608    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19609            boolean externalStorage) {
19610        ArrayList<String> pkgList = new ArrayList<String>();
19611        Set<AsecInstallArgs> keys = processCids.keySet();
19612
19613        for (AsecInstallArgs args : keys) {
19614            String codePath = processCids.get(args);
19615            if (DEBUG_SD_INSTALL)
19616                Log.i(TAG, "Loading container : " + args.cid);
19617            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19618            try {
19619                // Make sure there are no container errors first.
19620                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19621                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19622                            + " when installing from sdcard");
19623                    continue;
19624                }
19625                // Check code path here.
19626                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19627                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19628                            + " does not match one in settings " + codePath);
19629                    continue;
19630                }
19631                // Parse package
19632                int parseFlags = mDefParseFlags;
19633                if (args.isExternalAsec()) {
19634                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19635                }
19636                if (args.isFwdLocked()) {
19637                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19638                }
19639
19640                synchronized (mInstallLock) {
19641                    PackageParser.Package pkg = null;
19642                    try {
19643                        // Sadly we don't know the package name yet to freeze it
19644                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19645                                SCAN_IGNORE_FROZEN, 0, null);
19646                    } catch (PackageManagerException e) {
19647                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19648                    }
19649                    // Scan the package
19650                    if (pkg != null) {
19651                        /*
19652                         * TODO why is the lock being held? doPostInstall is
19653                         * called in other places without the lock. This needs
19654                         * to be straightened out.
19655                         */
19656                        // writer
19657                        synchronized (mPackages) {
19658                            retCode = PackageManager.INSTALL_SUCCEEDED;
19659                            pkgList.add(pkg.packageName);
19660                            // Post process args
19661                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19662                                    pkg.applicationInfo.uid);
19663                        }
19664                    } else {
19665                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19666                    }
19667                }
19668
19669            } finally {
19670                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19671                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19672                }
19673            }
19674        }
19675        // writer
19676        synchronized (mPackages) {
19677            // If the platform SDK has changed since the last time we booted,
19678            // we need to re-grant app permission to catch any new ones that
19679            // appear. This is really a hack, and means that apps can in some
19680            // cases get permissions that the user didn't initially explicitly
19681            // allow... it would be nice to have some better way to handle
19682            // this situation.
19683            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19684                    : mSettings.getInternalVersion();
19685            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19686                    : StorageManager.UUID_PRIVATE_INTERNAL;
19687
19688            int updateFlags = UPDATE_PERMISSIONS_ALL;
19689            if (ver.sdkVersion != mSdkVersion) {
19690                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19691                        + mSdkVersion + "; regranting permissions for external");
19692                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19693            }
19694            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19695
19696            // Yay, everything is now upgraded
19697            ver.forceCurrent();
19698
19699            // can downgrade to reader
19700            // Persist settings
19701            mSettings.writeLPr();
19702        }
19703        // Send a broadcast to let everyone know we are done processing
19704        if (pkgList.size() > 0) {
19705            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19706        }
19707    }
19708
19709   /*
19710     * Utility method to unload a list of specified containers
19711     */
19712    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19713        // Just unmount all valid containers.
19714        for (AsecInstallArgs arg : cidArgs) {
19715            synchronized (mInstallLock) {
19716                arg.doPostDeleteLI(false);
19717           }
19718       }
19719   }
19720
19721    /*
19722     * Unload packages mounted on external media. This involves deleting package
19723     * data from internal structures, sending broadcasts about disabled packages,
19724     * gc'ing to free up references, unmounting all secure containers
19725     * corresponding to packages on external media, and posting a
19726     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19727     * that we always have to post this message if status has been requested no
19728     * matter what.
19729     */
19730    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19731            final boolean reportStatus) {
19732        if (DEBUG_SD_INSTALL)
19733            Log.i(TAG, "unloading media packages");
19734        ArrayList<String> pkgList = new ArrayList<String>();
19735        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19736        final Set<AsecInstallArgs> keys = processCids.keySet();
19737        for (AsecInstallArgs args : keys) {
19738            String pkgName = args.getPackageName();
19739            if (DEBUG_SD_INSTALL)
19740                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19741            // Delete package internally
19742            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19743            synchronized (mInstallLock) {
19744                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19745                final boolean res;
19746                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19747                        "unloadMediaPackages")) {
19748                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19749                            null);
19750                }
19751                if (res) {
19752                    pkgList.add(pkgName);
19753                } else {
19754                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19755                    failedList.add(args);
19756                }
19757            }
19758        }
19759
19760        // reader
19761        synchronized (mPackages) {
19762            // We didn't update the settings after removing each package;
19763            // write them now for all packages.
19764            mSettings.writeLPr();
19765        }
19766
19767        // We have to absolutely send UPDATED_MEDIA_STATUS only
19768        // after confirming that all the receivers processed the ordered
19769        // broadcast when packages get disabled, force a gc to clean things up.
19770        // and unload all the containers.
19771        if (pkgList.size() > 0) {
19772            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19773                    new IIntentReceiver.Stub() {
19774                public void performReceive(Intent intent, int resultCode, String data,
19775                        Bundle extras, boolean ordered, boolean sticky,
19776                        int sendingUser) throws RemoteException {
19777                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19778                            reportStatus ? 1 : 0, 1, keys);
19779                    mHandler.sendMessage(msg);
19780                }
19781            });
19782        } else {
19783            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19784                    keys);
19785            mHandler.sendMessage(msg);
19786        }
19787    }
19788
19789    private void loadPrivatePackages(final VolumeInfo vol) {
19790        mHandler.post(new Runnable() {
19791            @Override
19792            public void run() {
19793                loadPrivatePackagesInner(vol);
19794            }
19795        });
19796    }
19797
19798    private void loadPrivatePackagesInner(VolumeInfo vol) {
19799        final String volumeUuid = vol.fsUuid;
19800        if (TextUtils.isEmpty(volumeUuid)) {
19801            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19802            return;
19803        }
19804
19805        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19806        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19807        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19808
19809        final VersionInfo ver;
19810        final List<PackageSetting> packages;
19811        synchronized (mPackages) {
19812            ver = mSettings.findOrCreateVersion(volumeUuid);
19813            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19814        }
19815
19816        for (PackageSetting ps : packages) {
19817            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19818            synchronized (mInstallLock) {
19819                final PackageParser.Package pkg;
19820                try {
19821                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19822                    loaded.add(pkg.applicationInfo);
19823
19824                } catch (PackageManagerException e) {
19825                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19826                }
19827
19828                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19829                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19830                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19831                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19832                }
19833            }
19834        }
19835
19836        // Reconcile app data for all started/unlocked users
19837        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19838        final UserManager um = mContext.getSystemService(UserManager.class);
19839        UserManagerInternal umInternal = getUserManagerInternal();
19840        for (UserInfo user : um.getUsers()) {
19841            final int flags;
19842            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19843                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19844            } else if (umInternal.isUserRunning(user.id)) {
19845                flags = StorageManager.FLAG_STORAGE_DE;
19846            } else {
19847                continue;
19848            }
19849
19850            try {
19851                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19852                synchronized (mInstallLock) {
19853                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19854                }
19855            } catch (IllegalStateException e) {
19856                // Device was probably ejected, and we'll process that event momentarily
19857                Slog.w(TAG, "Failed to prepare storage: " + e);
19858            }
19859        }
19860
19861        synchronized (mPackages) {
19862            int updateFlags = UPDATE_PERMISSIONS_ALL;
19863            if (ver.sdkVersion != mSdkVersion) {
19864                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19865                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19866                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19867            }
19868            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19869
19870            // Yay, everything is now upgraded
19871            ver.forceCurrent();
19872
19873            mSettings.writeLPr();
19874        }
19875
19876        for (PackageFreezer freezer : freezers) {
19877            freezer.close();
19878        }
19879
19880        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19881        sendResourcesChangedBroadcast(true, false, loaded, null);
19882    }
19883
19884    private void unloadPrivatePackages(final VolumeInfo vol) {
19885        mHandler.post(new Runnable() {
19886            @Override
19887            public void run() {
19888                unloadPrivatePackagesInner(vol);
19889            }
19890        });
19891    }
19892
19893    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19894        final String volumeUuid = vol.fsUuid;
19895        if (TextUtils.isEmpty(volumeUuid)) {
19896            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19897            return;
19898        }
19899
19900        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19901        synchronized (mInstallLock) {
19902        synchronized (mPackages) {
19903            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19904            for (PackageSetting ps : packages) {
19905                if (ps.pkg == null) continue;
19906
19907                final ApplicationInfo info = ps.pkg.applicationInfo;
19908                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19909                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19910
19911                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19912                        "unloadPrivatePackagesInner")) {
19913                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19914                            false, null)) {
19915                        unloaded.add(info);
19916                    } else {
19917                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19918                    }
19919                }
19920
19921                // Try very hard to release any references to this package
19922                // so we don't risk the system server being killed due to
19923                // open FDs
19924                AttributeCache.instance().removePackage(ps.name);
19925            }
19926
19927            mSettings.writeLPr();
19928        }
19929        }
19930
19931        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19932        sendResourcesChangedBroadcast(false, false, unloaded, null);
19933
19934        // Try very hard to release any references to this path so we don't risk
19935        // the system server being killed due to open FDs
19936        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19937
19938        for (int i = 0; i < 3; i++) {
19939            System.gc();
19940            System.runFinalization();
19941        }
19942    }
19943
19944    /**
19945     * Prepare storage areas for given user on all mounted devices.
19946     */
19947    void prepareUserData(int userId, int userSerial, int flags) {
19948        synchronized (mInstallLock) {
19949            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19950            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19951                final String volumeUuid = vol.getFsUuid();
19952                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19953            }
19954        }
19955    }
19956
19957    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19958            boolean allowRecover) {
19959        // Prepare storage and verify that serial numbers are consistent; if
19960        // there's a mismatch we need to destroy to avoid leaking data
19961        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19962        try {
19963            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19964
19965            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19966                UserManagerService.enforceSerialNumber(
19967                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19968                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19969                    UserManagerService.enforceSerialNumber(
19970                            Environment.getDataSystemDeDirectory(userId), userSerial);
19971                }
19972            }
19973            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19974                UserManagerService.enforceSerialNumber(
19975                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19976                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19977                    UserManagerService.enforceSerialNumber(
19978                            Environment.getDataSystemCeDirectory(userId), userSerial);
19979                }
19980            }
19981
19982            synchronized (mInstallLock) {
19983                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19984            }
19985        } catch (Exception e) {
19986            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19987                    + " because we failed to prepare: " + e);
19988            destroyUserDataLI(volumeUuid, userId,
19989                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19990
19991            if (allowRecover) {
19992                // Try one last time; if we fail again we're really in trouble
19993                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19994            }
19995        }
19996    }
19997
19998    /**
19999     * Destroy storage areas for given user on all mounted devices.
20000     */
20001    void destroyUserData(int userId, int flags) {
20002        synchronized (mInstallLock) {
20003            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20004            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20005                final String volumeUuid = vol.getFsUuid();
20006                destroyUserDataLI(volumeUuid, userId, flags);
20007            }
20008        }
20009    }
20010
20011    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20012        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20013        try {
20014            // Clean up app data, profile data, and media data
20015            mInstaller.destroyUserData(volumeUuid, userId, flags);
20016
20017            // Clean up system data
20018            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20019                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20020                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20021                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20022                }
20023                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20024                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20025                }
20026            }
20027
20028            // Data with special labels is now gone, so finish the job
20029            storage.destroyUserStorage(volumeUuid, userId, flags);
20030
20031        } catch (Exception e) {
20032            logCriticalInfo(Log.WARN,
20033                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20034        }
20035    }
20036
20037    /**
20038     * Examine all users present on given mounted volume, and destroy data
20039     * belonging to users that are no longer valid, or whose user ID has been
20040     * recycled.
20041     */
20042    private void reconcileUsers(String volumeUuid) {
20043        final List<File> files = new ArrayList<>();
20044        Collections.addAll(files, FileUtils
20045                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20046        Collections.addAll(files, FileUtils
20047                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20048        Collections.addAll(files, FileUtils
20049                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20050        Collections.addAll(files, FileUtils
20051                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20052        for (File file : files) {
20053            if (!file.isDirectory()) continue;
20054
20055            final int userId;
20056            final UserInfo info;
20057            try {
20058                userId = Integer.parseInt(file.getName());
20059                info = sUserManager.getUserInfo(userId);
20060            } catch (NumberFormatException e) {
20061                Slog.w(TAG, "Invalid user directory " + file);
20062                continue;
20063            }
20064
20065            boolean destroyUser = false;
20066            if (info == null) {
20067                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20068                        + " because no matching user was found");
20069                destroyUser = true;
20070            } else if (!mOnlyCore) {
20071                try {
20072                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20073                } catch (IOException e) {
20074                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20075                            + " because we failed to enforce serial number: " + e);
20076                    destroyUser = true;
20077                }
20078            }
20079
20080            if (destroyUser) {
20081                synchronized (mInstallLock) {
20082                    destroyUserDataLI(volumeUuid, userId,
20083                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20084                }
20085            }
20086        }
20087    }
20088
20089    private void assertPackageKnown(String volumeUuid, String packageName)
20090            throws PackageManagerException {
20091        synchronized (mPackages) {
20092            final PackageSetting ps = mSettings.mPackages.get(packageName);
20093            if (ps == null) {
20094                throw new PackageManagerException("Package " + packageName + " is unknown");
20095            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20096                throw new PackageManagerException(
20097                        "Package " + packageName + " found on unknown volume " + volumeUuid
20098                                + "; expected volume " + ps.volumeUuid);
20099            }
20100        }
20101    }
20102
20103    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20104            throws PackageManagerException {
20105        synchronized (mPackages) {
20106            final PackageSetting ps = mSettings.mPackages.get(packageName);
20107            if (ps == null) {
20108                throw new PackageManagerException("Package " + packageName + " is unknown");
20109            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20110                throw new PackageManagerException(
20111                        "Package " + packageName + " found on unknown volume " + volumeUuid
20112                                + "; expected volume " + ps.volumeUuid);
20113            } else if (!ps.getInstalled(userId)) {
20114                throw new PackageManagerException(
20115                        "Package " + packageName + " not installed for user " + userId);
20116            }
20117        }
20118    }
20119
20120    /**
20121     * Examine all apps present on given mounted volume, and destroy apps that
20122     * aren't expected, either due to uninstallation or reinstallation on
20123     * another volume.
20124     */
20125    private void reconcileApps(String volumeUuid) {
20126        final File[] files = FileUtils
20127                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20128        for (File file : files) {
20129            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20130                    && !PackageInstallerService.isStageName(file.getName());
20131            if (!isPackage) {
20132                // Ignore entries which are not packages
20133                continue;
20134            }
20135
20136            try {
20137                final PackageLite pkg = PackageParser.parsePackageLite(file,
20138                        PackageParser.PARSE_MUST_BE_APK);
20139                assertPackageKnown(volumeUuid, pkg.packageName);
20140
20141            } catch (PackageParserException | PackageManagerException e) {
20142                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20143                synchronized (mInstallLock) {
20144                    removeCodePathLI(file);
20145                }
20146            }
20147        }
20148    }
20149
20150    /**
20151     * Reconcile all app data for the given user.
20152     * <p>
20153     * Verifies that directories exist and that ownership and labeling is
20154     * correct for all installed apps on all mounted volumes.
20155     */
20156    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20157        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20158        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20159            final String volumeUuid = vol.getFsUuid();
20160            synchronized (mInstallLock) {
20161                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20162            }
20163        }
20164    }
20165
20166    /**
20167     * Reconcile all app data on given mounted volume.
20168     * <p>
20169     * Destroys app data that isn't expected, either due to uninstallation or
20170     * reinstallation on another volume.
20171     * <p>
20172     * Verifies that directories exist and that ownership and labeling is
20173     * correct for all installed apps.
20174     */
20175    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20176            boolean migrateAppData) {
20177        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20178                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20179
20180        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20181        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20182
20183        // First look for stale data that doesn't belong, and check if things
20184        // have changed since we did our last restorecon
20185        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20186            if (StorageManager.isFileEncryptedNativeOrEmulated()
20187                    && !StorageManager.isUserKeyUnlocked(userId)) {
20188                throw new RuntimeException(
20189                        "Yikes, someone asked us to reconcile CE storage while " + userId
20190                                + " was still locked; this would have caused massive data loss!");
20191            }
20192
20193            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20194            for (File file : files) {
20195                final String packageName = file.getName();
20196                try {
20197                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20198                } catch (PackageManagerException e) {
20199                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20200                    try {
20201                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20202                                StorageManager.FLAG_STORAGE_CE, 0);
20203                    } catch (InstallerException e2) {
20204                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20205                    }
20206                }
20207            }
20208        }
20209        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20210            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20211            for (File file : files) {
20212                final String packageName = file.getName();
20213                try {
20214                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20215                } catch (PackageManagerException e) {
20216                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20217                    try {
20218                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20219                                StorageManager.FLAG_STORAGE_DE, 0);
20220                    } catch (InstallerException e2) {
20221                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20222                    }
20223                }
20224            }
20225        }
20226
20227        // Ensure that data directories are ready to roll for all packages
20228        // installed for this volume and user
20229        final List<PackageSetting> packages;
20230        synchronized (mPackages) {
20231            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20232        }
20233        int preparedCount = 0;
20234        for (PackageSetting ps : packages) {
20235            final String packageName = ps.name;
20236            if (ps.pkg == null) {
20237                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20238                // TODO: might be due to legacy ASEC apps; we should circle back
20239                // and reconcile again once they're scanned
20240                continue;
20241            }
20242
20243            if (ps.getInstalled(userId)) {
20244                prepareAppDataLIF(ps.pkg, userId, flags);
20245
20246                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20247                    // We may have just shuffled around app data directories, so
20248                    // prepare them one more time
20249                    prepareAppDataLIF(ps.pkg, userId, flags);
20250                }
20251
20252                preparedCount++;
20253            }
20254        }
20255
20256        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20257    }
20258
20259    /**
20260     * Prepare app data for the given app just after it was installed or
20261     * upgraded. This method carefully only touches users that it's installed
20262     * for, and it forces a restorecon to handle any seinfo changes.
20263     * <p>
20264     * Verifies that directories exist and that ownership and labeling is
20265     * correct for all installed apps. If there is an ownership mismatch, it
20266     * will try recovering system apps by wiping data; third-party app data is
20267     * left intact.
20268     * <p>
20269     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20270     */
20271    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20272        final PackageSetting ps;
20273        synchronized (mPackages) {
20274            ps = mSettings.mPackages.get(pkg.packageName);
20275            mSettings.writeKernelMappingLPr(ps);
20276        }
20277
20278        final UserManager um = mContext.getSystemService(UserManager.class);
20279        UserManagerInternal umInternal = getUserManagerInternal();
20280        for (UserInfo user : um.getUsers()) {
20281            final int flags;
20282            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20283                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20284            } else if (umInternal.isUserRunning(user.id)) {
20285                flags = StorageManager.FLAG_STORAGE_DE;
20286            } else {
20287                continue;
20288            }
20289
20290            if (ps.getInstalled(user.id)) {
20291                // TODO: when user data is locked, mark that we're still dirty
20292                prepareAppDataLIF(pkg, user.id, flags);
20293            }
20294        }
20295    }
20296
20297    /**
20298     * Prepare app data for the given app.
20299     * <p>
20300     * Verifies that directories exist and that ownership and labeling is
20301     * correct for all installed apps. If there is an ownership mismatch, this
20302     * will try recovering system apps by wiping data; third-party app data is
20303     * left intact.
20304     */
20305    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20306        if (pkg == null) {
20307            Slog.wtf(TAG, "Package was null!", new Throwable());
20308            return;
20309        }
20310        prepareAppDataLeafLIF(pkg, userId, flags);
20311        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20312        for (int i = 0; i < childCount; i++) {
20313            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20314        }
20315    }
20316
20317    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20318        if (DEBUG_APP_DATA) {
20319            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20320                    + Integer.toHexString(flags));
20321        }
20322
20323        final String volumeUuid = pkg.volumeUuid;
20324        final String packageName = pkg.packageName;
20325        final ApplicationInfo app = pkg.applicationInfo;
20326        final int appId = UserHandle.getAppId(app.uid);
20327
20328        Preconditions.checkNotNull(app.seinfo);
20329
20330        try {
20331            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20332                    appId, app.seinfo, app.targetSdkVersion);
20333        } catch (InstallerException e) {
20334            if (app.isSystemApp()) {
20335                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20336                        + ", but trying to recover: " + e);
20337                destroyAppDataLeafLIF(pkg, userId, flags);
20338                try {
20339                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20340                            appId, app.seinfo, app.targetSdkVersion);
20341                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20342                } catch (InstallerException e2) {
20343                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20344                }
20345            } else {
20346                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20347            }
20348        }
20349
20350        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20351            try {
20352                // CE storage is unlocked right now, so read out the inode and
20353                // remember for use later when it's locked
20354                // TODO: mark this structure as dirty so we persist it!
20355                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20356                        StorageManager.FLAG_STORAGE_CE);
20357                synchronized (mPackages) {
20358                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20359                    if (ps != null) {
20360                        ps.setCeDataInode(ceDataInode, userId);
20361                    }
20362                }
20363            } catch (InstallerException e) {
20364                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20365            }
20366        }
20367
20368        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20369    }
20370
20371    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20372        if (pkg == null) {
20373            Slog.wtf(TAG, "Package was null!", new Throwable());
20374            return;
20375        }
20376        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20377        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20378        for (int i = 0; i < childCount; i++) {
20379            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20380        }
20381    }
20382
20383    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20384        final String volumeUuid = pkg.volumeUuid;
20385        final String packageName = pkg.packageName;
20386        final ApplicationInfo app = pkg.applicationInfo;
20387
20388        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20389            // Create a native library symlink only if we have native libraries
20390            // and if the native libraries are 32 bit libraries. We do not provide
20391            // this symlink for 64 bit libraries.
20392            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20393                final String nativeLibPath = app.nativeLibraryDir;
20394                try {
20395                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20396                            nativeLibPath, userId);
20397                } catch (InstallerException e) {
20398                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20399                }
20400            }
20401        }
20402    }
20403
20404    /**
20405     * For system apps on non-FBE devices, this method migrates any existing
20406     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20407     * requested by the app.
20408     */
20409    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20410        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20411                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20412            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20413                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20414            try {
20415                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20416                        storageTarget);
20417            } catch (InstallerException e) {
20418                logCriticalInfo(Log.WARN,
20419                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20420            }
20421            return true;
20422        } else {
20423            return false;
20424        }
20425    }
20426
20427    public PackageFreezer freezePackage(String packageName, String killReason) {
20428        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20429    }
20430
20431    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20432        return new PackageFreezer(packageName, userId, killReason);
20433    }
20434
20435    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20436            String killReason) {
20437        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20438    }
20439
20440    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20441            String killReason) {
20442        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20443            return new PackageFreezer();
20444        } else {
20445            return freezePackage(packageName, userId, killReason);
20446        }
20447    }
20448
20449    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20450            String killReason) {
20451        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20452    }
20453
20454    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20455            String killReason) {
20456        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20457            return new PackageFreezer();
20458        } else {
20459            return freezePackage(packageName, userId, killReason);
20460        }
20461    }
20462
20463    /**
20464     * Class that freezes and kills the given package upon creation, and
20465     * unfreezes it upon closing. This is typically used when doing surgery on
20466     * app code/data to prevent the app from running while you're working.
20467     */
20468    private class PackageFreezer implements AutoCloseable {
20469        private final String mPackageName;
20470        private final PackageFreezer[] mChildren;
20471
20472        private final boolean mWeFroze;
20473
20474        private final AtomicBoolean mClosed = new AtomicBoolean();
20475        private final CloseGuard mCloseGuard = CloseGuard.get();
20476
20477        /**
20478         * Create and return a stub freezer that doesn't actually do anything,
20479         * typically used when someone requested
20480         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20481         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20482         */
20483        public PackageFreezer() {
20484            mPackageName = null;
20485            mChildren = null;
20486            mWeFroze = false;
20487            mCloseGuard.open("close");
20488        }
20489
20490        public PackageFreezer(String packageName, int userId, String killReason) {
20491            synchronized (mPackages) {
20492                mPackageName = packageName;
20493                mWeFroze = mFrozenPackages.add(mPackageName);
20494
20495                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20496                if (ps != null) {
20497                    killApplication(ps.name, ps.appId, userId, killReason);
20498                }
20499
20500                final PackageParser.Package p = mPackages.get(packageName);
20501                if (p != null && p.childPackages != null) {
20502                    final int N = p.childPackages.size();
20503                    mChildren = new PackageFreezer[N];
20504                    for (int i = 0; i < N; i++) {
20505                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20506                                userId, killReason);
20507                    }
20508                } else {
20509                    mChildren = null;
20510                }
20511            }
20512            mCloseGuard.open("close");
20513        }
20514
20515        @Override
20516        protected void finalize() throws Throwable {
20517            try {
20518                mCloseGuard.warnIfOpen();
20519                close();
20520            } finally {
20521                super.finalize();
20522            }
20523        }
20524
20525        @Override
20526        public void close() {
20527            mCloseGuard.close();
20528            if (mClosed.compareAndSet(false, true)) {
20529                synchronized (mPackages) {
20530                    if (mWeFroze) {
20531                        mFrozenPackages.remove(mPackageName);
20532                    }
20533
20534                    if (mChildren != null) {
20535                        for (PackageFreezer freezer : mChildren) {
20536                            freezer.close();
20537                        }
20538                    }
20539                }
20540            }
20541        }
20542    }
20543
20544    /**
20545     * Verify that given package is currently frozen.
20546     */
20547    private void checkPackageFrozen(String packageName) {
20548        synchronized (mPackages) {
20549            if (!mFrozenPackages.contains(packageName)) {
20550                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20551            }
20552        }
20553    }
20554
20555    @Override
20556    public int movePackage(final String packageName, final String volumeUuid) {
20557        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20558
20559        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20560        final int moveId = mNextMoveId.getAndIncrement();
20561        mHandler.post(new Runnable() {
20562            @Override
20563            public void run() {
20564                try {
20565                    movePackageInternal(packageName, volumeUuid, moveId, user);
20566                } catch (PackageManagerException e) {
20567                    Slog.w(TAG, "Failed to move " + packageName, e);
20568                    mMoveCallbacks.notifyStatusChanged(moveId,
20569                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20570                }
20571            }
20572        });
20573        return moveId;
20574    }
20575
20576    private void movePackageInternal(final String packageName, final String volumeUuid,
20577            final int moveId, UserHandle user) throws PackageManagerException {
20578        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20579        final PackageManager pm = mContext.getPackageManager();
20580
20581        final boolean currentAsec;
20582        final String currentVolumeUuid;
20583        final File codeFile;
20584        final String installerPackageName;
20585        final String packageAbiOverride;
20586        final int appId;
20587        final String seinfo;
20588        final String label;
20589        final int targetSdkVersion;
20590        final PackageFreezer freezer;
20591        final int[] installedUserIds;
20592
20593        // reader
20594        synchronized (mPackages) {
20595            final PackageParser.Package pkg = mPackages.get(packageName);
20596            final PackageSetting ps = mSettings.mPackages.get(packageName);
20597            if (pkg == null || ps == null) {
20598                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20599            }
20600
20601            if (pkg.applicationInfo.isSystemApp()) {
20602                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20603                        "Cannot move system application");
20604            }
20605
20606            if (pkg.applicationInfo.isExternalAsec()) {
20607                currentAsec = true;
20608                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20609            } else if (pkg.applicationInfo.isForwardLocked()) {
20610                currentAsec = true;
20611                currentVolumeUuid = "forward_locked";
20612            } else {
20613                currentAsec = false;
20614                currentVolumeUuid = ps.volumeUuid;
20615
20616                final File probe = new File(pkg.codePath);
20617                final File probeOat = new File(probe, "oat");
20618                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20619                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20620                            "Move only supported for modern cluster style installs");
20621                }
20622            }
20623
20624            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20625                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20626                        "Package already moved to " + volumeUuid);
20627            }
20628            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20629                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20630                        "Device admin cannot be moved");
20631            }
20632
20633            if (mFrozenPackages.contains(packageName)) {
20634                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20635                        "Failed to move already frozen package");
20636            }
20637
20638            codeFile = new File(pkg.codePath);
20639            installerPackageName = ps.installerPackageName;
20640            packageAbiOverride = ps.cpuAbiOverrideString;
20641            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20642            seinfo = pkg.applicationInfo.seinfo;
20643            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20644            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20645            freezer = freezePackage(packageName, "movePackageInternal");
20646            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20647        }
20648
20649        final Bundle extras = new Bundle();
20650        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20651        extras.putString(Intent.EXTRA_TITLE, label);
20652        mMoveCallbacks.notifyCreated(moveId, extras);
20653
20654        int installFlags;
20655        final boolean moveCompleteApp;
20656        final File measurePath;
20657
20658        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20659            installFlags = INSTALL_INTERNAL;
20660            moveCompleteApp = !currentAsec;
20661            measurePath = Environment.getDataAppDirectory(volumeUuid);
20662        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20663            installFlags = INSTALL_EXTERNAL;
20664            moveCompleteApp = false;
20665            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20666        } else {
20667            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20668            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20669                    || !volume.isMountedWritable()) {
20670                freezer.close();
20671                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20672                        "Move location not mounted private volume");
20673            }
20674
20675            Preconditions.checkState(!currentAsec);
20676
20677            installFlags = INSTALL_INTERNAL;
20678            moveCompleteApp = true;
20679            measurePath = Environment.getDataAppDirectory(volumeUuid);
20680        }
20681
20682        final PackageStats stats = new PackageStats(null, -1);
20683        synchronized (mInstaller) {
20684            for (int userId : installedUserIds) {
20685                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20686                    freezer.close();
20687                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20688                            "Failed to measure package size");
20689                }
20690            }
20691        }
20692
20693        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20694                + stats.dataSize);
20695
20696        final long startFreeBytes = measurePath.getFreeSpace();
20697        final long sizeBytes;
20698        if (moveCompleteApp) {
20699            sizeBytes = stats.codeSize + stats.dataSize;
20700        } else {
20701            sizeBytes = stats.codeSize;
20702        }
20703
20704        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20705            freezer.close();
20706            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20707                    "Not enough free space to move");
20708        }
20709
20710        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20711
20712        final CountDownLatch installedLatch = new CountDownLatch(1);
20713        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20714            @Override
20715            public void onUserActionRequired(Intent intent) throws RemoteException {
20716                throw new IllegalStateException();
20717            }
20718
20719            @Override
20720            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20721                    Bundle extras) throws RemoteException {
20722                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20723                        + PackageManager.installStatusToString(returnCode, msg));
20724
20725                installedLatch.countDown();
20726                freezer.close();
20727
20728                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20729                switch (status) {
20730                    case PackageInstaller.STATUS_SUCCESS:
20731                        mMoveCallbacks.notifyStatusChanged(moveId,
20732                                PackageManager.MOVE_SUCCEEDED);
20733                        break;
20734                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20735                        mMoveCallbacks.notifyStatusChanged(moveId,
20736                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20737                        break;
20738                    default:
20739                        mMoveCallbacks.notifyStatusChanged(moveId,
20740                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20741                        break;
20742                }
20743            }
20744        };
20745
20746        final MoveInfo move;
20747        if (moveCompleteApp) {
20748            // Kick off a thread to report progress estimates
20749            new Thread() {
20750                @Override
20751                public void run() {
20752                    while (true) {
20753                        try {
20754                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20755                                break;
20756                            }
20757                        } catch (InterruptedException ignored) {
20758                        }
20759
20760                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20761                        final int progress = 10 + (int) MathUtils.constrain(
20762                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20763                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20764                    }
20765                }
20766            }.start();
20767
20768            final String dataAppName = codeFile.getName();
20769            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20770                    dataAppName, appId, seinfo, targetSdkVersion);
20771        } else {
20772            move = null;
20773        }
20774
20775        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20776
20777        final Message msg = mHandler.obtainMessage(INIT_COPY);
20778        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20779        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20780                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20781                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20782        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20783        msg.obj = params;
20784
20785        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20786                System.identityHashCode(msg.obj));
20787        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20788                System.identityHashCode(msg.obj));
20789
20790        mHandler.sendMessage(msg);
20791    }
20792
20793    @Override
20794    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20795        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20796
20797        final int realMoveId = mNextMoveId.getAndIncrement();
20798        final Bundle extras = new Bundle();
20799        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20800        mMoveCallbacks.notifyCreated(realMoveId, extras);
20801
20802        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20803            @Override
20804            public void onCreated(int moveId, Bundle extras) {
20805                // Ignored
20806            }
20807
20808            @Override
20809            public void onStatusChanged(int moveId, int status, long estMillis) {
20810                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20811            }
20812        };
20813
20814        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20815        storage.setPrimaryStorageUuid(volumeUuid, callback);
20816        return realMoveId;
20817    }
20818
20819    @Override
20820    public int getMoveStatus(int moveId) {
20821        mContext.enforceCallingOrSelfPermission(
20822                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20823        return mMoveCallbacks.mLastStatus.get(moveId);
20824    }
20825
20826    @Override
20827    public void registerMoveCallback(IPackageMoveObserver callback) {
20828        mContext.enforceCallingOrSelfPermission(
20829                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20830        mMoveCallbacks.register(callback);
20831    }
20832
20833    @Override
20834    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20835        mContext.enforceCallingOrSelfPermission(
20836                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20837        mMoveCallbacks.unregister(callback);
20838    }
20839
20840    @Override
20841    public boolean setInstallLocation(int loc) {
20842        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20843                null);
20844        if (getInstallLocation() == loc) {
20845            return true;
20846        }
20847        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20848                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20849            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20850                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20851            return true;
20852        }
20853        return false;
20854   }
20855
20856    @Override
20857    public int getInstallLocation() {
20858        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20859                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20860                PackageHelper.APP_INSTALL_AUTO);
20861    }
20862
20863    /** Called by UserManagerService */
20864    void cleanUpUser(UserManagerService userManager, int userHandle) {
20865        synchronized (mPackages) {
20866            mDirtyUsers.remove(userHandle);
20867            mUserNeedsBadging.delete(userHandle);
20868            mSettings.removeUserLPw(userHandle);
20869            mPendingBroadcasts.remove(userHandle);
20870            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20871            removeUnusedPackagesLPw(userManager, userHandle);
20872        }
20873    }
20874
20875    /**
20876     * We're removing userHandle and would like to remove any downloaded packages
20877     * that are no longer in use by any other user.
20878     * @param userHandle the user being removed
20879     */
20880    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20881        final boolean DEBUG_CLEAN_APKS = false;
20882        int [] users = userManager.getUserIds();
20883        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20884        while (psit.hasNext()) {
20885            PackageSetting ps = psit.next();
20886            if (ps.pkg == null) {
20887                continue;
20888            }
20889            final String packageName = ps.pkg.packageName;
20890            // Skip over if system app
20891            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20892                continue;
20893            }
20894            if (DEBUG_CLEAN_APKS) {
20895                Slog.i(TAG, "Checking package " + packageName);
20896            }
20897            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20898            if (keep) {
20899                if (DEBUG_CLEAN_APKS) {
20900                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20901                }
20902            } else {
20903                for (int i = 0; i < users.length; i++) {
20904                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20905                        keep = true;
20906                        if (DEBUG_CLEAN_APKS) {
20907                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20908                                    + users[i]);
20909                        }
20910                        break;
20911                    }
20912                }
20913            }
20914            if (!keep) {
20915                if (DEBUG_CLEAN_APKS) {
20916                    Slog.i(TAG, "  Removing package " + packageName);
20917                }
20918                mHandler.post(new Runnable() {
20919                    public void run() {
20920                        deletePackageX(packageName, userHandle, 0);
20921                    } //end run
20922                });
20923            }
20924        }
20925    }
20926
20927    /** Called by UserManagerService */
20928    void createNewUser(int userId, String[] disallowedPackages) {
20929        synchronized (mInstallLock) {
20930            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
20931        }
20932        synchronized (mPackages) {
20933            scheduleWritePackageRestrictionsLocked(userId);
20934            scheduleWritePackageListLocked(userId);
20935            applyFactoryDefaultBrowserLPw(userId);
20936            primeDomainVerificationsLPw(userId);
20937        }
20938    }
20939
20940    void onNewUserCreated(final int userId) {
20941        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20942        // If permission review for legacy apps is required, we represent
20943        // dagerous permissions for such apps as always granted runtime
20944        // permissions to keep per user flag state whether review is needed.
20945        // Hence, if a new user is added we have to propagate dangerous
20946        // permission grants for these legacy apps.
20947        if (mPermissionReviewRequired) {
20948            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20949                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20950        }
20951    }
20952
20953    @Override
20954    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20955        mContext.enforceCallingOrSelfPermission(
20956                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20957                "Only package verification agents can read the verifier device identity");
20958
20959        synchronized (mPackages) {
20960            return mSettings.getVerifierDeviceIdentityLPw();
20961        }
20962    }
20963
20964    @Override
20965    public void setPermissionEnforced(String permission, boolean enforced) {
20966        // TODO: Now that we no longer change GID for storage, this should to away.
20967        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20968                "setPermissionEnforced");
20969        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20970            synchronized (mPackages) {
20971                if (mSettings.mReadExternalStorageEnforced == null
20972                        || mSettings.mReadExternalStorageEnforced != enforced) {
20973                    mSettings.mReadExternalStorageEnforced = enforced;
20974                    mSettings.writeLPr();
20975                }
20976            }
20977            // kill any non-foreground processes so we restart them and
20978            // grant/revoke the GID.
20979            final IActivityManager am = ActivityManager.getService();
20980            if (am != null) {
20981                final long token = Binder.clearCallingIdentity();
20982                try {
20983                    am.killProcessesBelowForeground("setPermissionEnforcement");
20984                } catch (RemoteException e) {
20985                } finally {
20986                    Binder.restoreCallingIdentity(token);
20987                }
20988            }
20989        } else {
20990            throw new IllegalArgumentException("No selective enforcement for " + permission);
20991        }
20992    }
20993
20994    @Override
20995    @Deprecated
20996    public boolean isPermissionEnforced(String permission) {
20997        return true;
20998    }
20999
21000    @Override
21001    public boolean isStorageLow() {
21002        final long token = Binder.clearCallingIdentity();
21003        try {
21004            final DeviceStorageMonitorInternal
21005                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21006            if (dsm != null) {
21007                return dsm.isMemoryLow();
21008            } else {
21009                return false;
21010            }
21011        } finally {
21012            Binder.restoreCallingIdentity(token);
21013        }
21014    }
21015
21016    @Override
21017    public IPackageInstaller getPackageInstaller() {
21018        return mInstallerService;
21019    }
21020
21021    private boolean userNeedsBadging(int userId) {
21022        int index = mUserNeedsBadging.indexOfKey(userId);
21023        if (index < 0) {
21024            final UserInfo userInfo;
21025            final long token = Binder.clearCallingIdentity();
21026            try {
21027                userInfo = sUserManager.getUserInfo(userId);
21028            } finally {
21029                Binder.restoreCallingIdentity(token);
21030            }
21031            final boolean b;
21032            if (userInfo != null && userInfo.isManagedProfile()) {
21033                b = true;
21034            } else {
21035                b = false;
21036            }
21037            mUserNeedsBadging.put(userId, b);
21038            return b;
21039        }
21040        return mUserNeedsBadging.valueAt(index);
21041    }
21042
21043    @Override
21044    public KeySet getKeySetByAlias(String packageName, String alias) {
21045        if (packageName == null || alias == null) {
21046            return null;
21047        }
21048        synchronized(mPackages) {
21049            final PackageParser.Package pkg = mPackages.get(packageName);
21050            if (pkg == null) {
21051                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21052                throw new IllegalArgumentException("Unknown package: " + packageName);
21053            }
21054            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21055            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21056        }
21057    }
21058
21059    @Override
21060    public KeySet getSigningKeySet(String packageName) {
21061        if (packageName == null) {
21062            return null;
21063        }
21064        synchronized(mPackages) {
21065            final PackageParser.Package pkg = mPackages.get(packageName);
21066            if (pkg == null) {
21067                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21068                throw new IllegalArgumentException("Unknown package: " + packageName);
21069            }
21070            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21071                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21072                throw new SecurityException("May not access signing KeySet of other apps.");
21073            }
21074            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21075            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21076        }
21077    }
21078
21079    @Override
21080    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21081        if (packageName == null || ks == null) {
21082            return false;
21083        }
21084        synchronized(mPackages) {
21085            final PackageParser.Package pkg = mPackages.get(packageName);
21086            if (pkg == null) {
21087                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21088                throw new IllegalArgumentException("Unknown package: " + packageName);
21089            }
21090            IBinder ksh = ks.getToken();
21091            if (ksh instanceof KeySetHandle) {
21092                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21093                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21094            }
21095            return false;
21096        }
21097    }
21098
21099    @Override
21100    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21101        if (packageName == null || ks == null) {
21102            return false;
21103        }
21104        synchronized(mPackages) {
21105            final PackageParser.Package pkg = mPackages.get(packageName);
21106            if (pkg == null) {
21107                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21108                throw new IllegalArgumentException("Unknown package: " + packageName);
21109            }
21110            IBinder ksh = ks.getToken();
21111            if (ksh instanceof KeySetHandle) {
21112                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21113                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21114            }
21115            return false;
21116        }
21117    }
21118
21119    private void deletePackageIfUnusedLPr(final String packageName) {
21120        PackageSetting ps = mSettings.mPackages.get(packageName);
21121        if (ps == null) {
21122            return;
21123        }
21124        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21125            // TODO Implement atomic delete if package is unused
21126            // It is currently possible that the package will be deleted even if it is installed
21127            // after this method returns.
21128            mHandler.post(new Runnable() {
21129                public void run() {
21130                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21131                }
21132            });
21133        }
21134    }
21135
21136    /**
21137     * Check and throw if the given before/after packages would be considered a
21138     * downgrade.
21139     */
21140    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21141            throws PackageManagerException {
21142        if (after.versionCode < before.mVersionCode) {
21143            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21144                    "Update version code " + after.versionCode + " is older than current "
21145                    + before.mVersionCode);
21146        } else if (after.versionCode == before.mVersionCode) {
21147            if (after.baseRevisionCode < before.baseRevisionCode) {
21148                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21149                        "Update base revision code " + after.baseRevisionCode
21150                        + " is older than current " + before.baseRevisionCode);
21151            }
21152
21153            if (!ArrayUtils.isEmpty(after.splitNames)) {
21154                for (int i = 0; i < after.splitNames.length; i++) {
21155                    final String splitName = after.splitNames[i];
21156                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21157                    if (j != -1) {
21158                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21159                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21160                                    "Update split " + splitName + " revision code "
21161                                    + after.splitRevisionCodes[i] + " is older than current "
21162                                    + before.splitRevisionCodes[j]);
21163                        }
21164                    }
21165                }
21166            }
21167        }
21168    }
21169
21170    private static class MoveCallbacks extends Handler {
21171        private static final int MSG_CREATED = 1;
21172        private static final int MSG_STATUS_CHANGED = 2;
21173
21174        private final RemoteCallbackList<IPackageMoveObserver>
21175                mCallbacks = new RemoteCallbackList<>();
21176
21177        private final SparseIntArray mLastStatus = new SparseIntArray();
21178
21179        public MoveCallbacks(Looper looper) {
21180            super(looper);
21181        }
21182
21183        public void register(IPackageMoveObserver callback) {
21184            mCallbacks.register(callback);
21185        }
21186
21187        public void unregister(IPackageMoveObserver callback) {
21188            mCallbacks.unregister(callback);
21189        }
21190
21191        @Override
21192        public void handleMessage(Message msg) {
21193            final SomeArgs args = (SomeArgs) msg.obj;
21194            final int n = mCallbacks.beginBroadcast();
21195            for (int i = 0; i < n; i++) {
21196                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21197                try {
21198                    invokeCallback(callback, msg.what, args);
21199                } catch (RemoteException ignored) {
21200                }
21201            }
21202            mCallbacks.finishBroadcast();
21203            args.recycle();
21204        }
21205
21206        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21207                throws RemoteException {
21208            switch (what) {
21209                case MSG_CREATED: {
21210                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21211                    break;
21212                }
21213                case MSG_STATUS_CHANGED: {
21214                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21215                    break;
21216                }
21217            }
21218        }
21219
21220        private void notifyCreated(int moveId, Bundle extras) {
21221            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21222
21223            final SomeArgs args = SomeArgs.obtain();
21224            args.argi1 = moveId;
21225            args.arg2 = extras;
21226            obtainMessage(MSG_CREATED, args).sendToTarget();
21227        }
21228
21229        private void notifyStatusChanged(int moveId, int status) {
21230            notifyStatusChanged(moveId, status, -1);
21231        }
21232
21233        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21234            Slog.v(TAG, "Move " + moveId + " status " + status);
21235
21236            final SomeArgs args = SomeArgs.obtain();
21237            args.argi1 = moveId;
21238            args.argi2 = status;
21239            args.arg3 = estMillis;
21240            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21241
21242            synchronized (mLastStatus) {
21243                mLastStatus.put(moveId, status);
21244            }
21245        }
21246    }
21247
21248    private final static class OnPermissionChangeListeners extends Handler {
21249        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21250
21251        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21252                new RemoteCallbackList<>();
21253
21254        public OnPermissionChangeListeners(Looper looper) {
21255            super(looper);
21256        }
21257
21258        @Override
21259        public void handleMessage(Message msg) {
21260            switch (msg.what) {
21261                case MSG_ON_PERMISSIONS_CHANGED: {
21262                    final int uid = msg.arg1;
21263                    handleOnPermissionsChanged(uid);
21264                } break;
21265            }
21266        }
21267
21268        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21269            mPermissionListeners.register(listener);
21270
21271        }
21272
21273        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21274            mPermissionListeners.unregister(listener);
21275        }
21276
21277        public void onPermissionsChanged(int uid) {
21278            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21279                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21280            }
21281        }
21282
21283        private void handleOnPermissionsChanged(int uid) {
21284            final int count = mPermissionListeners.beginBroadcast();
21285            try {
21286                for (int i = 0; i < count; i++) {
21287                    IOnPermissionsChangeListener callback = mPermissionListeners
21288                            .getBroadcastItem(i);
21289                    try {
21290                        callback.onPermissionsChanged(uid);
21291                    } catch (RemoteException e) {
21292                        Log.e(TAG, "Permission listener is dead", e);
21293                    }
21294                }
21295            } finally {
21296                mPermissionListeners.finishBroadcast();
21297            }
21298        }
21299    }
21300
21301    private class PackageManagerInternalImpl extends PackageManagerInternal {
21302        @Override
21303        public void setLocationPackagesProvider(PackagesProvider provider) {
21304            synchronized (mPackages) {
21305                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21306            }
21307        }
21308
21309        @Override
21310        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21311            synchronized (mPackages) {
21312                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21313            }
21314        }
21315
21316        @Override
21317        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21318            synchronized (mPackages) {
21319                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21320            }
21321        }
21322
21323        @Override
21324        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21325            synchronized (mPackages) {
21326                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21327            }
21328        }
21329
21330        @Override
21331        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21332            synchronized (mPackages) {
21333                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21334            }
21335        }
21336
21337        @Override
21338        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21339            synchronized (mPackages) {
21340                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21341            }
21342        }
21343
21344        @Override
21345        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21346            synchronized (mPackages) {
21347                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21348                        packageName, userId);
21349            }
21350        }
21351
21352        @Override
21353        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21354            synchronized (mPackages) {
21355                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21356                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21357                        packageName, userId);
21358            }
21359        }
21360
21361        @Override
21362        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21363            synchronized (mPackages) {
21364                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21365                        packageName, userId);
21366            }
21367        }
21368
21369        @Override
21370        public void setKeepUninstalledPackages(final List<String> packageList) {
21371            Preconditions.checkNotNull(packageList);
21372            List<String> removedFromList = null;
21373            synchronized (mPackages) {
21374                if (mKeepUninstalledPackages != null) {
21375                    final int packagesCount = mKeepUninstalledPackages.size();
21376                    for (int i = 0; i < packagesCount; i++) {
21377                        String oldPackage = mKeepUninstalledPackages.get(i);
21378                        if (packageList != null && packageList.contains(oldPackage)) {
21379                            continue;
21380                        }
21381                        if (removedFromList == null) {
21382                            removedFromList = new ArrayList<>();
21383                        }
21384                        removedFromList.add(oldPackage);
21385                    }
21386                }
21387                mKeepUninstalledPackages = new ArrayList<>(packageList);
21388                if (removedFromList != null) {
21389                    final int removedCount = removedFromList.size();
21390                    for (int i = 0; i < removedCount; i++) {
21391                        deletePackageIfUnusedLPr(removedFromList.get(i));
21392                    }
21393                }
21394            }
21395        }
21396
21397        @Override
21398        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21399            synchronized (mPackages) {
21400                // If we do not support permission review, done.
21401                if (!mPermissionReviewRequired) {
21402                    return false;
21403                }
21404
21405                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21406                if (packageSetting == null) {
21407                    return false;
21408                }
21409
21410                // Permission review applies only to apps not supporting the new permission model.
21411                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21412                    return false;
21413                }
21414
21415                // Legacy apps have the permission and get user consent on launch.
21416                PermissionsState permissionsState = packageSetting.getPermissionsState();
21417                return permissionsState.isPermissionReviewRequired(userId);
21418            }
21419        }
21420
21421        @Override
21422        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21423            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21424        }
21425
21426        @Override
21427        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21428                int userId) {
21429            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21430        }
21431
21432        @Override
21433        public void setDeviceAndProfileOwnerPackages(
21434                int deviceOwnerUserId, String deviceOwnerPackage,
21435                SparseArray<String> profileOwnerPackages) {
21436            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21437                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21438        }
21439
21440        @Override
21441        public boolean isPackageDataProtected(int userId, String packageName) {
21442            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21443        }
21444
21445        @Override
21446        public boolean isPackageEphemeral(int userId, String packageName) {
21447            synchronized (mPackages) {
21448                PackageParser.Package p = mPackages.get(packageName);
21449                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21450            }
21451        }
21452
21453        @Override
21454        public boolean wasPackageEverLaunched(String packageName, int userId) {
21455            synchronized (mPackages) {
21456                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21457            }
21458        }
21459
21460        @Override
21461        public void grantRuntimePermission(String packageName, String name, int userId,
21462                boolean overridePolicy) {
21463            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21464                    overridePolicy);
21465        }
21466
21467        @Override
21468        public void revokeRuntimePermission(String packageName, String name, int userId,
21469                boolean overridePolicy) {
21470            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21471                    overridePolicy);
21472        }
21473
21474        @Override
21475        public String getNameForUid(int uid) {
21476            return PackageManagerService.this.getNameForUid(uid);
21477        }
21478
21479        @Override
21480        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21481                Intent origIntent, String resolvedType, Intent launchIntent,
21482                String callingPackage, int userId) {
21483            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21484                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21485        }
21486    }
21487
21488    @Override
21489    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21490        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21491        synchronized (mPackages) {
21492            final long identity = Binder.clearCallingIdentity();
21493            try {
21494                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21495                        packageNames, userId);
21496            } finally {
21497                Binder.restoreCallingIdentity(identity);
21498            }
21499        }
21500    }
21501
21502    private static void enforceSystemOrPhoneCaller(String tag) {
21503        int callingUid = Binder.getCallingUid();
21504        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21505            throw new SecurityException(
21506                    "Cannot call " + tag + " from UID " + callingUid);
21507        }
21508    }
21509
21510    boolean isHistoricalPackageUsageAvailable() {
21511        return mPackageUsage.isHistoricalPackageUsageAvailable();
21512    }
21513
21514    /**
21515     * Return a <b>copy</b> of the collection of packages known to the package manager.
21516     * @return A copy of the values of mPackages.
21517     */
21518    Collection<PackageParser.Package> getPackages() {
21519        synchronized (mPackages) {
21520            return new ArrayList<>(mPackages.values());
21521        }
21522    }
21523
21524    /**
21525     * Logs process start information (including base APK hash) to the security log.
21526     * @hide
21527     */
21528    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21529            String apkFile, int pid) {
21530        if (!SecurityLog.isLoggingEnabled()) {
21531            return;
21532        }
21533        Bundle data = new Bundle();
21534        data.putLong("startTimestamp", System.currentTimeMillis());
21535        data.putString("processName", processName);
21536        data.putInt("uid", uid);
21537        data.putString("seinfo", seinfo);
21538        data.putString("apkFile", apkFile);
21539        data.putInt("pid", pid);
21540        Message msg = mProcessLoggingHandler.obtainMessage(
21541                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21542        msg.setData(data);
21543        mProcessLoggingHandler.sendMessage(msg);
21544    }
21545
21546    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21547        return mCompilerStats.getPackageStats(pkgName);
21548    }
21549
21550    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21551        return getOrCreateCompilerPackageStats(pkg.packageName);
21552    }
21553
21554    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21555        return mCompilerStats.getOrCreatePackageStats(pkgName);
21556    }
21557
21558    public void deleteCompilerPackageStats(String pkgName) {
21559        mCompilerStats.deletePackageStats(pkgName);
21560    }
21561}
21562