PackageManagerService.java revision d2a7a674fb52753a791766428de32e0760e0f832
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.RoSystemProperties;
241import com.android.internal.os.SomeArgs;
242import com.android.internal.os.Zygote;
243import com.android.internal.telephony.CarrierAppUtils;
244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
246import com.android.internal.util.FastXmlSerializer;
247import com.android.internal.util.IndentingPrintWriter;
248import com.android.internal.util.Preconditions;
249import com.android.internal.util.XmlUtils;
250import com.android.server.AttributeCache;
251import com.android.server.EventLogTags;
252import com.android.server.FgThread;
253import com.android.server.IntentResolver;
254import com.android.server.LocalServices;
255import com.android.server.ServiceThread;
256import com.android.server.SystemConfig;
257import com.android.server.Watchdog;
258import com.android.server.net.NetworkPolicyManagerInternal;
259import com.android.server.pm.Installer.InstallerException;
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            Manifest.permission.READ_PHONE_NUMBER);
563
564    final ServiceThread mHandlerThread;
565
566    final PackageHandler mHandler;
567
568    private final ProcessLoggingHandler mProcessLoggingHandler;
569
570    /**
571     * Messages for {@link #mHandler} that need to wait for system ready before
572     * being dispatched.
573     */
574    private ArrayList<Message> mPostSystemReadyMessages;
575
576    final int mSdkVersion = Build.VERSION.SDK_INT;
577
578    final Context mContext;
579    final boolean mFactoryTest;
580    final boolean mOnlyCore;
581    final DisplayMetrics mMetrics;
582    final int mDefParseFlags;
583    final String[] mSeparateProcesses;
584    final boolean mIsUpgrade;
585    final boolean mIsPreNUpgrade;
586    final boolean mIsPreNMR1Upgrade;
587
588    @GuardedBy("mPackages")
589    private boolean mDexOptDialogShown;
590
591    /** The location for ASEC container files on internal storage. */
592    final String mAsecInternalPath;
593
594    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
595    // LOCK HELD.  Can be called with mInstallLock held.
596    @GuardedBy("mInstallLock")
597    final Installer mInstaller;
598
599    /** Directory where installed third-party apps stored */
600    final File mAppInstallDir;
601    final File mEphemeralInstallDir;
602
603    /**
604     * Directory to which applications installed internally have their
605     * 32 bit native libraries copied.
606     */
607    private File mAppLib32InstallDir;
608
609    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
610    // apps.
611    final File mDrmAppPrivateInstallDir;
612
613    // ----------------------------------------------------------------
614
615    // Lock for state used when installing and doing other long running
616    // operations.  Methods that must be called with this lock held have
617    // the suffix "LI".
618    final Object mInstallLock = new Object();
619
620    // ----------------------------------------------------------------
621
622    // Keys are String (package name), values are Package.  This also serves
623    // as the lock for the global state.  Methods that must be called with
624    // this lock held have the prefix "LP".
625    @GuardedBy("mPackages")
626    final ArrayMap<String, PackageParser.Package> mPackages =
627            new ArrayMap<String, PackageParser.Package>();
628
629    final ArrayMap<String, Set<String>> mKnownCodebase =
630            new ArrayMap<String, Set<String>>();
631
632    // Tracks available target package names -> overlay package paths.
633    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
634        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
635
636    /**
637     * Tracks new system packages [received in an OTA] that we expect to
638     * find updated user-installed versions. Keys are package name, values
639     * are package location.
640     */
641    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
642    /**
643     * Tracks high priority intent filters for protected actions. During boot, certain
644     * filter actions are protected and should never be allowed to have a high priority
645     * intent filter for them. However, there is one, and only one exception -- the
646     * setup wizard. It must be able to define a high priority intent filter for these
647     * actions to ensure there are no escapes from the wizard. We need to delay processing
648     * of these during boot as we need to look at all of the system packages in order
649     * to know which component is the setup wizard.
650     */
651    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
652    /**
653     * Whether or not processing protected filters should be deferred.
654     */
655    private boolean mDeferProtectedFilters = true;
656
657    /**
658     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
659     */
660    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
661    /**
662     * Whether or not system app permissions should be promoted from install to runtime.
663     */
664    boolean mPromoteSystemApps;
665
666    @GuardedBy("mPackages")
667    final Settings mSettings;
668
669    /**
670     * Set of package names that are currently "frozen", which means active
671     * surgery is being done on the code/data for that package. The platform
672     * will refuse to launch frozen packages to avoid race conditions.
673     *
674     * @see PackageFreezer
675     */
676    @GuardedBy("mPackages")
677    final ArraySet<String> mFrozenPackages = new ArraySet<>();
678
679    final ProtectedPackages mProtectedPackages;
680
681    boolean mFirstBoot;
682
683    // System configuration read by SystemConfig.
684    final int[] mGlobalGids;
685    final SparseArray<ArraySet<String>> mSystemPermissions;
686    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
687
688    // If mac_permissions.xml was found for seinfo labeling.
689    boolean mFoundPolicyFile;
690
691    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
692
693    public static final class SharedLibraryEntry {
694        public final String path;
695        public final String apk;
696
697        SharedLibraryEntry(String _path, String _apk) {
698            path = _path;
699            apk = _apk;
700        }
701    }
702
703    // Currently known shared libraries.
704    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
705            new ArrayMap<String, SharedLibraryEntry>();
706
707    // All available activities, for your resolving pleasure.
708    final ActivityIntentResolver mActivities =
709            new ActivityIntentResolver();
710
711    // All available receivers, for your resolving pleasure.
712    final ActivityIntentResolver mReceivers =
713            new ActivityIntentResolver();
714
715    // All available services, for your resolving pleasure.
716    final ServiceIntentResolver mServices = new ServiceIntentResolver();
717
718    // All available providers, for your resolving pleasure.
719    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
720
721    // Mapping from provider base names (first directory in content URI codePath)
722    // to the provider information.
723    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
724            new ArrayMap<String, PackageParser.Provider>();
725
726    // Mapping from instrumentation class names to info about them.
727    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
728            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
729
730    // Mapping from permission names to info about them.
731    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
732            new ArrayMap<String, PackageParser.PermissionGroup>();
733
734    // Packages whose data we have transfered into another package, thus
735    // should no longer exist.
736    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
737
738    // Broadcast actions that are only available to the system.
739    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
740
741    /** List of packages waiting for verification. */
742    final SparseArray<PackageVerificationState> mPendingVerification
743            = new SparseArray<PackageVerificationState>();
744
745    /** Set of packages associated with each app op permission. */
746    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
747
748    final PackageInstallerService mInstallerService;
749
750    private final PackageDexOptimizer mPackageDexOptimizer;
751
752    private AtomicInteger mNextMoveId = new AtomicInteger();
753    private final MoveCallbacks mMoveCallbacks;
754
755    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
756
757    // Cache of users who need badging.
758    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
759
760    /** Token for keys in mPendingVerification. */
761    private int mPendingVerificationToken = 0;
762
763    volatile boolean mSystemReady;
764    volatile boolean mSafeMode;
765    volatile boolean mHasSystemUidErrors;
766
767    ApplicationInfo mAndroidApplication;
768    final ActivityInfo mResolveActivity = new ActivityInfo();
769    final ResolveInfo mResolveInfo = new ResolveInfo();
770    ComponentName mResolveComponentName;
771    PackageParser.Package mPlatformPackage;
772    ComponentName mCustomResolverComponentName;
773
774    boolean mResolverReplaced = false;
775
776    private final @Nullable ComponentName mIntentFilterVerifierComponent;
777    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
778
779    private int mIntentFilterVerificationToken = 0;
780
781    /** The service connection to the ephemeral resolver */
782    final EphemeralResolverConnection mEphemeralResolverConnection;
783
784    /** Component used to install ephemeral applications */
785    ComponentName mEphemeralInstallerComponent;
786    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
787    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
788
789    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
790            = new SparseArray<IntentFilterVerificationState>();
791
792    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
793
794    // List of packages names to keep cached, even if they are uninstalled for all users
795    private List<String> mKeepUninstalledPackages;
796
797    private UserManagerInternal mUserManagerInternal;
798
799    private static class IFVerificationParams {
800        PackageParser.Package pkg;
801        boolean replacing;
802        int userId;
803        int verifierUid;
804
805        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
806                int _userId, int _verifierUid) {
807            pkg = _pkg;
808            replacing = _replacing;
809            userId = _userId;
810            replacing = _replacing;
811            verifierUid = _verifierUid;
812        }
813    }
814
815    private interface IntentFilterVerifier<T extends IntentFilter> {
816        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
817                                               T filter, String packageName);
818        void startVerifications(int userId);
819        void receiveVerificationResponse(int verificationId);
820    }
821
822    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
823        private Context mContext;
824        private ComponentName mIntentFilterVerifierComponent;
825        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
826
827        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
828            mContext = context;
829            mIntentFilterVerifierComponent = verifierComponent;
830        }
831
832        private String getDefaultScheme() {
833            return IntentFilter.SCHEME_HTTPS;
834        }
835
836        @Override
837        public void startVerifications(int userId) {
838            // Launch verifications requests
839            int count = mCurrentIntentFilterVerifications.size();
840            for (int n=0; n<count; n++) {
841                int verificationId = mCurrentIntentFilterVerifications.get(n);
842                final IntentFilterVerificationState ivs =
843                        mIntentFilterVerificationStates.get(verificationId);
844
845                String packageName = ivs.getPackageName();
846
847                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
848                final int filterCount = filters.size();
849                ArraySet<String> domainsSet = new ArraySet<>();
850                for (int m=0; m<filterCount; m++) {
851                    PackageParser.ActivityIntentInfo filter = filters.get(m);
852                    domainsSet.addAll(filter.getHostsList());
853                }
854                synchronized (mPackages) {
855                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
856                            packageName, domainsSet) != null) {
857                        scheduleWriteSettingsLocked();
858                    }
859                }
860                sendVerificationRequest(userId, verificationId, ivs);
861            }
862            mCurrentIntentFilterVerifications.clear();
863        }
864
865        private void sendVerificationRequest(int userId, int verificationId,
866                IntentFilterVerificationState ivs) {
867
868            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
869            verificationIntent.putExtra(
870                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
871                    verificationId);
872            verificationIntent.putExtra(
873                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
874                    getDefaultScheme());
875            verificationIntent.putExtra(
876                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
877                    ivs.getHostsString());
878            verificationIntent.putExtra(
879                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
880                    ivs.getPackageName());
881            verificationIntent.setComponent(mIntentFilterVerifierComponent);
882            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
883
884            UserHandle user = new UserHandle(userId);
885            mContext.sendBroadcastAsUser(verificationIntent, user);
886            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
887                    "Sending IntentFilter verification broadcast");
888        }
889
890        public void receiveVerificationResponse(int verificationId) {
891            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
892
893            final boolean verified = ivs.isVerified();
894
895            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
896            final int count = filters.size();
897            if (DEBUG_DOMAIN_VERIFICATION) {
898                Slog.i(TAG, "Received verification response " + verificationId
899                        + " for " + count + " filters, verified=" + verified);
900            }
901            for (int n=0; n<count; n++) {
902                PackageParser.ActivityIntentInfo filter = filters.get(n);
903                filter.setVerified(verified);
904
905                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
906                        + " verified with result:" + verified + " and hosts:"
907                        + ivs.getHostsString());
908            }
909
910            mIntentFilterVerificationStates.remove(verificationId);
911
912            final String packageName = ivs.getPackageName();
913            IntentFilterVerificationInfo ivi = null;
914
915            synchronized (mPackages) {
916                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
917            }
918            if (ivi == null) {
919                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
920                        + verificationId + " packageName:" + packageName);
921                return;
922            }
923            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
924                    "Updating IntentFilterVerificationInfo for package " + packageName
925                            +" verificationId:" + verificationId);
926
927            synchronized (mPackages) {
928                if (verified) {
929                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
930                } else {
931                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
932                }
933                scheduleWriteSettingsLocked();
934
935                final int userId = ivs.getUserId();
936                if (userId != UserHandle.USER_ALL) {
937                    final int userStatus =
938                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
939
940                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
941                    boolean needUpdate = false;
942
943                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
944                    // already been set by the User thru the Disambiguation dialog
945                    switch (userStatus) {
946                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
947                            if (verified) {
948                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
949                            } else {
950                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
951                            }
952                            needUpdate = true;
953                            break;
954
955                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
956                            if (verified) {
957                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
958                                needUpdate = true;
959                            }
960                            break;
961
962                        default:
963                            // Nothing to do
964                    }
965
966                    if (needUpdate) {
967                        mSettings.updateIntentFilterVerificationStatusLPw(
968                                packageName, updatedStatus, userId);
969                        scheduleWritePackageRestrictionsLocked(userId);
970                    }
971                }
972            }
973        }
974
975        @Override
976        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
977                    ActivityIntentInfo filter, String packageName) {
978            if (!hasValidDomains(filter)) {
979                return false;
980            }
981            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
982            if (ivs == null) {
983                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
984                        packageName);
985            }
986            if (DEBUG_DOMAIN_VERIFICATION) {
987                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
988            }
989            ivs.addFilter(filter);
990            return true;
991        }
992
993        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
994                int userId, int verificationId, String packageName) {
995            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
996                    verifierUid, userId, packageName);
997            ivs.setPendingState();
998            synchronized (mPackages) {
999                mIntentFilterVerificationStates.append(verificationId, ivs);
1000                mCurrentIntentFilterVerifications.add(verificationId);
1001            }
1002            return ivs;
1003        }
1004    }
1005
1006    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1007        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1008                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1009                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1010    }
1011
1012    // Set of pending broadcasts for aggregating enable/disable of components.
1013    static class PendingPackageBroadcasts {
1014        // for each user id, a map of <package name -> components within that package>
1015        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1016
1017        public PendingPackageBroadcasts() {
1018            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1019        }
1020
1021        public ArrayList<String> get(int userId, String packageName) {
1022            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1023            return packages.get(packageName);
1024        }
1025
1026        public void put(int userId, String packageName, ArrayList<String> components) {
1027            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1028            packages.put(packageName, components);
1029        }
1030
1031        public void remove(int userId, String packageName) {
1032            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1033            if (packages != null) {
1034                packages.remove(packageName);
1035            }
1036        }
1037
1038        public void remove(int userId) {
1039            mUidMap.remove(userId);
1040        }
1041
1042        public int userIdCount() {
1043            return mUidMap.size();
1044        }
1045
1046        public int userIdAt(int n) {
1047            return mUidMap.keyAt(n);
1048        }
1049
1050        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1051            return mUidMap.get(userId);
1052        }
1053
1054        public int size() {
1055            // total number of pending broadcast entries across all userIds
1056            int num = 0;
1057            for (int i = 0; i< mUidMap.size(); i++) {
1058                num += mUidMap.valueAt(i).size();
1059            }
1060            return num;
1061        }
1062
1063        public void clear() {
1064            mUidMap.clear();
1065        }
1066
1067        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1068            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1069            if (map == null) {
1070                map = new ArrayMap<String, ArrayList<String>>();
1071                mUidMap.put(userId, map);
1072            }
1073            return map;
1074        }
1075    }
1076    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1077
1078    // Service Connection to remote media container service to copy
1079    // package uri's from external media onto secure containers
1080    // or internal storage.
1081    private IMediaContainerService mContainerService = null;
1082
1083    static final int SEND_PENDING_BROADCAST = 1;
1084    static final int MCS_BOUND = 3;
1085    static final int END_COPY = 4;
1086    static final int INIT_COPY = 5;
1087    static final int MCS_UNBIND = 6;
1088    static final int START_CLEANING_PACKAGE = 7;
1089    static final int FIND_INSTALL_LOC = 8;
1090    static final int POST_INSTALL = 9;
1091    static final int MCS_RECONNECT = 10;
1092    static final int MCS_GIVE_UP = 11;
1093    static final int UPDATED_MEDIA_STATUS = 12;
1094    static final int WRITE_SETTINGS = 13;
1095    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1096    static final int PACKAGE_VERIFIED = 15;
1097    static final int CHECK_PENDING_VERIFICATION = 16;
1098    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1099    static final int INTENT_FILTER_VERIFIED = 18;
1100    static final int WRITE_PACKAGE_LIST = 19;
1101    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1102
1103    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1104
1105    // Delay time in millisecs
1106    static final int BROADCAST_DELAY = 10 * 1000;
1107
1108    static UserManagerService sUserManager;
1109
1110    // Stores a list of users whose package restrictions file needs to be updated
1111    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1112
1113    final private DefaultContainerConnection mDefContainerConn =
1114            new DefaultContainerConnection();
1115    class DefaultContainerConnection implements ServiceConnection {
1116        public void onServiceConnected(ComponentName name, IBinder service) {
1117            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1118            final IMediaContainerService imcs = IMediaContainerService.Stub
1119                    .asInterface(Binder.allowBlocking(service));
1120            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1121        }
1122
1123        public void onServiceDisconnected(ComponentName name) {
1124            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1125        }
1126    }
1127
1128    // Recordkeeping of restore-after-install operations that are currently in flight
1129    // between the Package Manager and the Backup Manager
1130    static class PostInstallData {
1131        public InstallArgs args;
1132        public PackageInstalledInfo res;
1133
1134        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1135            args = _a;
1136            res = _r;
1137        }
1138    }
1139
1140    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1141    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1142
1143    // XML tags for backup/restore of various bits of state
1144    private static final String TAG_PREFERRED_BACKUP = "pa";
1145    private static final String TAG_DEFAULT_APPS = "da";
1146    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1147
1148    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1149    private static final String TAG_ALL_GRANTS = "rt-grants";
1150    private static final String TAG_GRANT = "grant";
1151    private static final String ATTR_PACKAGE_NAME = "pkg";
1152
1153    private static final String TAG_PERMISSION = "perm";
1154    private static final String ATTR_PERMISSION_NAME = "name";
1155    private static final String ATTR_IS_GRANTED = "g";
1156    private static final String ATTR_USER_SET = "set";
1157    private static final String ATTR_USER_FIXED = "fixed";
1158    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1159
1160    // System/policy permission grants are not backed up
1161    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1162            FLAG_PERMISSION_POLICY_FIXED
1163            | FLAG_PERMISSION_SYSTEM_FIXED
1164            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1165
1166    // And we back up these user-adjusted states
1167    private static final int USER_RUNTIME_GRANT_MASK =
1168            FLAG_PERMISSION_USER_SET
1169            | FLAG_PERMISSION_USER_FIXED
1170            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1171
1172    final @Nullable String mRequiredVerifierPackage;
1173    final @NonNull String mRequiredInstallerPackage;
1174    final @NonNull String mRequiredUninstallerPackage;
1175    final @Nullable String mSetupWizardPackage;
1176    final @Nullable String mStorageManagerPackage;
1177    final @NonNull String mServicesSystemSharedLibraryPackageName;
1178    final @NonNull String mSharedSystemSharedLibraryPackageName;
1179
1180    final boolean mPermissionReviewRequired;
1181
1182    private final PackageUsage mPackageUsage = new PackageUsage();
1183    private final CompilerStats mCompilerStats = new CompilerStats();
1184
1185    class PackageHandler extends Handler {
1186        private boolean mBound = false;
1187        final ArrayList<HandlerParams> mPendingInstalls =
1188            new ArrayList<HandlerParams>();
1189
1190        private boolean connectToService() {
1191            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1192                    " DefaultContainerService");
1193            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1194            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1195            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1196                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1197                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1198                mBound = true;
1199                return true;
1200            }
1201            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1202            return false;
1203        }
1204
1205        private void disconnectService() {
1206            mContainerService = null;
1207            mBound = false;
1208            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1209            mContext.unbindService(mDefContainerConn);
1210            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1211        }
1212
1213        PackageHandler(Looper looper) {
1214            super(looper);
1215        }
1216
1217        public void handleMessage(Message msg) {
1218            try {
1219                doHandleMessage(msg);
1220            } finally {
1221                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1222            }
1223        }
1224
1225        void doHandleMessage(Message msg) {
1226            switch (msg.what) {
1227                case INIT_COPY: {
1228                    HandlerParams params = (HandlerParams) msg.obj;
1229                    int idx = mPendingInstalls.size();
1230                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1231                    // If a bind was already initiated we dont really
1232                    // need to do anything. The pending install
1233                    // will be processed later on.
1234                    if (!mBound) {
1235                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1236                                System.identityHashCode(mHandler));
1237                        // If this is the only one pending we might
1238                        // have to bind to the service again.
1239                        if (!connectToService()) {
1240                            Slog.e(TAG, "Failed to bind to media container service");
1241                            params.serviceError();
1242                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1243                                    System.identityHashCode(mHandler));
1244                            if (params.traceMethod != null) {
1245                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1246                                        params.traceCookie);
1247                            }
1248                            return;
1249                        } else {
1250                            // Once we bind to the service, the first
1251                            // pending request will be processed.
1252                            mPendingInstalls.add(idx, params);
1253                        }
1254                    } else {
1255                        mPendingInstalls.add(idx, params);
1256                        // Already bound to the service. Just make
1257                        // sure we trigger off processing the first request.
1258                        if (idx == 0) {
1259                            mHandler.sendEmptyMessage(MCS_BOUND);
1260                        }
1261                    }
1262                    break;
1263                }
1264                case MCS_BOUND: {
1265                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1266                    if (msg.obj != null) {
1267                        mContainerService = (IMediaContainerService) msg.obj;
1268                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1269                                System.identityHashCode(mHandler));
1270                    }
1271                    if (mContainerService == null) {
1272                        if (!mBound) {
1273                            // Something seriously wrong since we are not bound and we are not
1274                            // waiting for connection. Bail out.
1275                            Slog.e(TAG, "Cannot bind to media container service");
1276                            for (HandlerParams params : mPendingInstalls) {
1277                                // Indicate service bind error
1278                                params.serviceError();
1279                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1280                                        System.identityHashCode(params));
1281                                if (params.traceMethod != null) {
1282                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1283                                            params.traceMethod, params.traceCookie);
1284                                }
1285                                return;
1286                            }
1287                            mPendingInstalls.clear();
1288                        } else {
1289                            Slog.w(TAG, "Waiting to connect to media container service");
1290                        }
1291                    } else if (mPendingInstalls.size() > 0) {
1292                        HandlerParams params = mPendingInstalls.get(0);
1293                        if (params != null) {
1294                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1295                                    System.identityHashCode(params));
1296                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1297                            if (params.startCopy()) {
1298                                // We are done...  look for more work or to
1299                                // go idle.
1300                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1301                                        "Checking for more work or unbind...");
1302                                // Delete pending install
1303                                if (mPendingInstalls.size() > 0) {
1304                                    mPendingInstalls.remove(0);
1305                                }
1306                                if (mPendingInstalls.size() == 0) {
1307                                    if (mBound) {
1308                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1309                                                "Posting delayed MCS_UNBIND");
1310                                        removeMessages(MCS_UNBIND);
1311                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1312                                        // Unbind after a little delay, to avoid
1313                                        // continual thrashing.
1314                                        sendMessageDelayed(ubmsg, 10000);
1315                                    }
1316                                } else {
1317                                    // There are more pending requests in queue.
1318                                    // Just post MCS_BOUND message to trigger processing
1319                                    // of next pending install.
1320                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1321                                            "Posting MCS_BOUND for next work");
1322                                    mHandler.sendEmptyMessage(MCS_BOUND);
1323                                }
1324                            }
1325                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1326                        }
1327                    } else {
1328                        // Should never happen ideally.
1329                        Slog.w(TAG, "Empty queue");
1330                    }
1331                    break;
1332                }
1333                case MCS_RECONNECT: {
1334                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1335                    if (mPendingInstalls.size() > 0) {
1336                        if (mBound) {
1337                            disconnectService();
1338                        }
1339                        if (!connectToService()) {
1340                            Slog.e(TAG, "Failed to bind to media container service");
1341                            for (HandlerParams params : mPendingInstalls) {
1342                                // Indicate service bind error
1343                                params.serviceError();
1344                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1345                                        System.identityHashCode(params));
1346                            }
1347                            mPendingInstalls.clear();
1348                        }
1349                    }
1350                    break;
1351                }
1352                case MCS_UNBIND: {
1353                    // If there is no actual work left, then time to unbind.
1354                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1355
1356                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1357                        if (mBound) {
1358                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1359
1360                            disconnectService();
1361                        }
1362                    } else if (mPendingInstalls.size() > 0) {
1363                        // There are more pending requests in queue.
1364                        // Just post MCS_BOUND message to trigger processing
1365                        // of next pending install.
1366                        mHandler.sendEmptyMessage(MCS_BOUND);
1367                    }
1368
1369                    break;
1370                }
1371                case MCS_GIVE_UP: {
1372                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1373                    HandlerParams params = mPendingInstalls.remove(0);
1374                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1375                            System.identityHashCode(params));
1376                    break;
1377                }
1378                case SEND_PENDING_BROADCAST: {
1379                    String packages[];
1380                    ArrayList<String> components[];
1381                    int size = 0;
1382                    int uids[];
1383                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1384                    synchronized (mPackages) {
1385                        if (mPendingBroadcasts == null) {
1386                            return;
1387                        }
1388                        size = mPendingBroadcasts.size();
1389                        if (size <= 0) {
1390                            // Nothing to be done. Just return
1391                            return;
1392                        }
1393                        packages = new String[size];
1394                        components = new ArrayList[size];
1395                        uids = new int[size];
1396                        int i = 0;  // filling out the above arrays
1397
1398                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1399                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1400                            Iterator<Map.Entry<String, ArrayList<String>>> it
1401                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1402                                            .entrySet().iterator();
1403                            while (it.hasNext() && i < size) {
1404                                Map.Entry<String, ArrayList<String>> ent = it.next();
1405                                packages[i] = ent.getKey();
1406                                components[i] = ent.getValue();
1407                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1408                                uids[i] = (ps != null)
1409                                        ? UserHandle.getUid(packageUserId, ps.appId)
1410                                        : -1;
1411                                i++;
1412                            }
1413                        }
1414                        size = i;
1415                        mPendingBroadcasts.clear();
1416                    }
1417                    // Send broadcasts
1418                    for (int i = 0; i < size; i++) {
1419                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1420                    }
1421                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422                    break;
1423                }
1424                case START_CLEANING_PACKAGE: {
1425                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1426                    final String packageName = (String)msg.obj;
1427                    final int userId = msg.arg1;
1428                    final boolean andCode = msg.arg2 != 0;
1429                    synchronized (mPackages) {
1430                        if (userId == UserHandle.USER_ALL) {
1431                            int[] users = sUserManager.getUserIds();
1432                            for (int user : users) {
1433                                mSettings.addPackageToCleanLPw(
1434                                        new PackageCleanItem(user, packageName, andCode));
1435                            }
1436                        } else {
1437                            mSettings.addPackageToCleanLPw(
1438                                    new PackageCleanItem(userId, packageName, andCode));
1439                        }
1440                    }
1441                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1442                    startCleaningPackages();
1443                } break;
1444                case POST_INSTALL: {
1445                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1446
1447                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1448                    final boolean didRestore = (msg.arg2 != 0);
1449                    mRunningInstalls.delete(msg.arg1);
1450
1451                    if (data != null) {
1452                        InstallArgs args = data.args;
1453                        PackageInstalledInfo parentRes = data.res;
1454
1455                        final boolean grantPermissions = (args.installFlags
1456                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1457                        final boolean killApp = (args.installFlags
1458                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1459                        final String[] grantedPermissions = args.installGrantPermissions;
1460
1461                        // Handle the parent package
1462                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1463                                grantedPermissions, didRestore, args.installerPackageName,
1464                                args.observer);
1465
1466                        // Handle the child packages
1467                        final int childCount = (parentRes.addedChildPackages != null)
1468                                ? parentRes.addedChildPackages.size() : 0;
1469                        for (int i = 0; i < childCount; i++) {
1470                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1471                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1472                                    grantedPermissions, false, args.installerPackageName,
1473                                    args.observer);
1474                        }
1475
1476                        // Log tracing if needed
1477                        if (args.traceMethod != null) {
1478                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1479                                    args.traceCookie);
1480                        }
1481                    } else {
1482                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1483                    }
1484
1485                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1486                } break;
1487                case UPDATED_MEDIA_STATUS: {
1488                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1489                    boolean reportStatus = msg.arg1 == 1;
1490                    boolean doGc = msg.arg2 == 1;
1491                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1492                    if (doGc) {
1493                        // Force a gc to clear up stale containers.
1494                        Runtime.getRuntime().gc();
1495                    }
1496                    if (msg.obj != null) {
1497                        @SuppressWarnings("unchecked")
1498                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1499                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1500                        // Unload containers
1501                        unloadAllContainers(args);
1502                    }
1503                    if (reportStatus) {
1504                        try {
1505                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1506                                    "Invoking StorageManagerService call back");
1507                            PackageHelper.getStorageManager().finishMediaUpdate();
1508                        } catch (RemoteException e) {
1509                            Log.e(TAG, "StorageManagerService not running?");
1510                        }
1511                    }
1512                } break;
1513                case WRITE_SETTINGS: {
1514                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1515                    synchronized (mPackages) {
1516                        removeMessages(WRITE_SETTINGS);
1517                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1518                        mSettings.writeLPr();
1519                        mDirtyUsers.clear();
1520                    }
1521                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1522                } break;
1523                case WRITE_PACKAGE_RESTRICTIONS: {
1524                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1525                    synchronized (mPackages) {
1526                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1527                        for (int userId : mDirtyUsers) {
1528                            mSettings.writePackageRestrictionsLPr(userId);
1529                        }
1530                        mDirtyUsers.clear();
1531                    }
1532                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1533                } break;
1534                case WRITE_PACKAGE_LIST: {
1535                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1536                    synchronized (mPackages) {
1537                        removeMessages(WRITE_PACKAGE_LIST);
1538                        mSettings.writePackageListLPr(msg.arg1);
1539                    }
1540                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1541                } break;
1542                case CHECK_PENDING_VERIFICATION: {
1543                    final int verificationId = msg.arg1;
1544                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1545
1546                    if ((state != null) && !state.timeoutExtended()) {
1547                        final InstallArgs args = state.getInstallArgs();
1548                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1549
1550                        Slog.i(TAG, "Verification timed out for " + originUri);
1551                        mPendingVerification.remove(verificationId);
1552
1553                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1554
1555                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1556                            Slog.i(TAG, "Continuing with installation of " + originUri);
1557                            state.setVerifierResponse(Binder.getCallingUid(),
1558                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1559                            broadcastPackageVerified(verificationId, originUri,
1560                                    PackageManager.VERIFICATION_ALLOW,
1561                                    state.getInstallArgs().getUser());
1562                            try {
1563                                ret = args.copyApk(mContainerService, true);
1564                            } catch (RemoteException e) {
1565                                Slog.e(TAG, "Could not contact the ContainerService");
1566                            }
1567                        } else {
1568                            broadcastPackageVerified(verificationId, originUri,
1569                                    PackageManager.VERIFICATION_REJECT,
1570                                    state.getInstallArgs().getUser());
1571                        }
1572
1573                        Trace.asyncTraceEnd(
1574                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1575
1576                        processPendingInstall(args, ret);
1577                        mHandler.sendEmptyMessage(MCS_UNBIND);
1578                    }
1579                    break;
1580                }
1581                case PACKAGE_VERIFIED: {
1582                    final int verificationId = msg.arg1;
1583
1584                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1585                    if (state == null) {
1586                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1587                        break;
1588                    }
1589
1590                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1591
1592                    state.setVerifierResponse(response.callerUid, response.code);
1593
1594                    if (state.isVerificationComplete()) {
1595                        mPendingVerification.remove(verificationId);
1596
1597                        final InstallArgs args = state.getInstallArgs();
1598                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1599
1600                        int ret;
1601                        if (state.isInstallAllowed()) {
1602                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1603                            broadcastPackageVerified(verificationId, originUri,
1604                                    response.code, state.getInstallArgs().getUser());
1605                            try {
1606                                ret = args.copyApk(mContainerService, true);
1607                            } catch (RemoteException e) {
1608                                Slog.e(TAG, "Could not contact the ContainerService");
1609                            }
1610                        } else {
1611                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1612                        }
1613
1614                        Trace.asyncTraceEnd(
1615                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1616
1617                        processPendingInstall(args, ret);
1618                        mHandler.sendEmptyMessage(MCS_UNBIND);
1619                    }
1620
1621                    break;
1622                }
1623                case START_INTENT_FILTER_VERIFICATIONS: {
1624                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1625                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1626                            params.replacing, params.pkg);
1627                    break;
1628                }
1629                case INTENT_FILTER_VERIFIED: {
1630                    final int verificationId = msg.arg1;
1631
1632                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1633                            verificationId);
1634                    if (state == null) {
1635                        Slog.w(TAG, "Invalid IntentFilter verification token "
1636                                + verificationId + " received");
1637                        break;
1638                    }
1639
1640                    final int userId = state.getUserId();
1641
1642                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1643                            "Processing IntentFilter verification with token:"
1644                            + verificationId + " and userId:" + userId);
1645
1646                    final IntentFilterVerificationResponse response =
1647                            (IntentFilterVerificationResponse) msg.obj;
1648
1649                    state.setVerifierResponse(response.callerUid, response.code);
1650
1651                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1652                            "IntentFilter verification with token:" + verificationId
1653                            + " and userId:" + userId
1654                            + " is settings verifier response with response code:"
1655                            + response.code);
1656
1657                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1658                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1659                                + response.getFailedDomainsString());
1660                    }
1661
1662                    if (state.isVerificationComplete()) {
1663                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1664                    } else {
1665                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1666                                "IntentFilter verification with token:" + verificationId
1667                                + " was not said to be complete");
1668                    }
1669
1670                    break;
1671                }
1672                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1673                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1674                            mEphemeralResolverConnection,
1675                            (EphemeralRequest) msg.obj,
1676                            mEphemeralInstallerActivity,
1677                            mHandler);
1678                }
1679            }
1680        }
1681    }
1682
1683    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1684            boolean killApp, String[] grantedPermissions,
1685            boolean launchedForRestore, String installerPackage,
1686            IPackageInstallObserver2 installObserver) {
1687        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1688            // Send the removed broadcasts
1689            if (res.removedInfo != null) {
1690                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1691            }
1692
1693            // Now that we successfully installed the package, grant runtime
1694            // permissions if requested before broadcasting the install.
1695            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1696                    >= Build.VERSION_CODES.M) {
1697                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1698            }
1699
1700            final boolean update = res.removedInfo != null
1701                    && res.removedInfo.removedPackage != null;
1702
1703            // If this is the first time we have child packages for a disabled privileged
1704            // app that had no children, we grant requested runtime permissions to the new
1705            // children if the parent on the system image had them already granted.
1706            if (res.pkg.parentPackage != null) {
1707                synchronized (mPackages) {
1708                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1709                }
1710            }
1711
1712            synchronized (mPackages) {
1713                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1714            }
1715
1716            final String packageName = res.pkg.applicationInfo.packageName;
1717
1718            // Determine the set of users who are adding this package for
1719            // the first time vs. those who are seeing an update.
1720            int[] firstUsers = EMPTY_INT_ARRAY;
1721            int[] updateUsers = EMPTY_INT_ARRAY;
1722            if (res.origUsers == null || res.origUsers.length == 0) {
1723                firstUsers = res.newUsers;
1724            } else {
1725                for (int newUser : res.newUsers) {
1726                    boolean isNew = true;
1727                    for (int origUser : res.origUsers) {
1728                        if (origUser == newUser) {
1729                            isNew = false;
1730                            break;
1731                        }
1732                    }
1733                    if (isNew) {
1734                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1735                    } else {
1736                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1737                    }
1738                }
1739            }
1740
1741            // Send installed broadcasts if the install/update is not ephemeral
1742            if (!isEphemeral(res.pkg)) {
1743                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1744
1745                // Send added for users that see the package for the first time
1746                // sendPackageAddedForNewUsers also deals with system apps
1747                int appId = UserHandle.getAppId(res.uid);
1748                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1749                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1750
1751                // Send added for users that don't see the package for the first time
1752                Bundle extras = new Bundle(1);
1753                extras.putInt(Intent.EXTRA_UID, res.uid);
1754                if (update) {
1755                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1756                }
1757                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1758                        extras, 0 /*flags*/, null /*targetPackage*/,
1759                        null /*finishedReceiver*/, updateUsers);
1760
1761                // Send replaced for users that don't see the package for the first time
1762                if (update) {
1763                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1764                            packageName, extras, 0 /*flags*/,
1765                            null /*targetPackage*/, null /*finishedReceiver*/,
1766                            updateUsers);
1767                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1768                            null /*package*/, null /*extras*/, 0 /*flags*/,
1769                            packageName /*targetPackage*/,
1770                            null /*finishedReceiver*/, updateUsers);
1771                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1772                    // First-install and we did a restore, so we're responsible for the
1773                    // first-launch broadcast.
1774                    if (DEBUG_BACKUP) {
1775                        Slog.i(TAG, "Post-restore of " + packageName
1776                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1777                    }
1778                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1779                }
1780
1781                // Send broadcast package appeared if forward locked/external for all users
1782                // treat asec-hosted packages like removable media on upgrade
1783                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1784                    if (DEBUG_INSTALL) {
1785                        Slog.i(TAG, "upgrading pkg " + res.pkg
1786                                + " is ASEC-hosted -> AVAILABLE");
1787                    }
1788                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1789                    ArrayList<String> pkgList = new ArrayList<>(1);
1790                    pkgList.add(packageName);
1791                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1792                }
1793            }
1794
1795            // Work that needs to happen on first install within each user
1796            if (firstUsers != null && firstUsers.length > 0) {
1797                synchronized (mPackages) {
1798                    for (int userId : firstUsers) {
1799                        // If this app is a browser and it's newly-installed for some
1800                        // users, clear any default-browser state in those users. The
1801                        // app's nature doesn't depend on the user, so we can just check
1802                        // its browser nature in any user and generalize.
1803                        if (packageIsBrowser(packageName, userId)) {
1804                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1805                        }
1806
1807                        // We may also need to apply pending (restored) runtime
1808                        // permission grants within these users.
1809                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1810                    }
1811                }
1812            }
1813
1814            // Log current value of "unknown sources" setting
1815            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1816                    getUnknownSourcesSettings());
1817
1818            // Force a gc to clear up things
1819            Runtime.getRuntime().gc();
1820
1821            // Remove the replaced package's older resources safely now
1822            // We delete after a gc for applications  on sdcard.
1823            if (res.removedInfo != null && res.removedInfo.args != null) {
1824                synchronized (mInstallLock) {
1825                    res.removedInfo.args.doPostDeleteLI(true);
1826                }
1827            }
1828        }
1829
1830        // If someone is watching installs - notify them
1831        if (installObserver != null) {
1832            try {
1833                Bundle extras = extrasForInstallResult(res);
1834                installObserver.onPackageInstalled(res.name, res.returnCode,
1835                        res.returnMsg, extras);
1836            } catch (RemoteException e) {
1837                Slog.i(TAG, "Observer no longer exists.");
1838            }
1839        }
1840    }
1841
1842    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1843            PackageParser.Package pkg) {
1844        if (pkg.parentPackage == null) {
1845            return;
1846        }
1847        if (pkg.requestedPermissions == null) {
1848            return;
1849        }
1850        final PackageSetting disabledSysParentPs = mSettings
1851                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1852        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1853                || !disabledSysParentPs.isPrivileged()
1854                || (disabledSysParentPs.childPackageNames != null
1855                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1856            return;
1857        }
1858        final int[] allUserIds = sUserManager.getUserIds();
1859        final int permCount = pkg.requestedPermissions.size();
1860        for (int i = 0; i < permCount; i++) {
1861            String permission = pkg.requestedPermissions.get(i);
1862            BasePermission bp = mSettings.mPermissions.get(permission);
1863            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1864                continue;
1865            }
1866            for (int userId : allUserIds) {
1867                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1868                        permission, userId)) {
1869                    grantRuntimePermission(pkg.packageName, permission, userId);
1870                }
1871            }
1872        }
1873    }
1874
1875    private StorageEventListener mStorageListener = new StorageEventListener() {
1876        @Override
1877        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1878            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1879                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1880                    final String volumeUuid = vol.getFsUuid();
1881
1882                    // Clean up any users or apps that were removed or recreated
1883                    // while this volume was missing
1884                    reconcileUsers(volumeUuid);
1885                    reconcileApps(volumeUuid);
1886
1887                    // Clean up any install sessions that expired or were
1888                    // cancelled while this volume was missing
1889                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1890
1891                    loadPrivatePackages(vol);
1892
1893                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1894                    unloadPrivatePackages(vol);
1895                }
1896            }
1897
1898            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1899                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1900                    updateExternalMediaStatus(true, false);
1901                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1902                    updateExternalMediaStatus(false, false);
1903                }
1904            }
1905        }
1906
1907        @Override
1908        public void onVolumeForgotten(String fsUuid) {
1909            if (TextUtils.isEmpty(fsUuid)) {
1910                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1911                return;
1912            }
1913
1914            // Remove any apps installed on the forgotten volume
1915            synchronized (mPackages) {
1916                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1917                for (PackageSetting ps : packages) {
1918                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1919                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1920                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1921
1922                    // Try very hard to release any references to this package
1923                    // so we don't risk the system server being killed due to
1924                    // open FDs
1925                    AttributeCache.instance().removePackage(ps.name);
1926                }
1927
1928                mSettings.onVolumeForgotten(fsUuid);
1929                mSettings.writeLPr();
1930            }
1931        }
1932    };
1933
1934    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1935            String[] grantedPermissions) {
1936        for (int userId : userIds) {
1937            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1938        }
1939
1940        // We could have touched GID membership, so flush out packages.list
1941        synchronized (mPackages) {
1942            mSettings.writePackageListLPr();
1943        }
1944    }
1945
1946    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1947            String[] grantedPermissions) {
1948        SettingBase sb = (SettingBase) pkg.mExtras;
1949        if (sb == null) {
1950            return;
1951        }
1952
1953        PermissionsState permissionsState = sb.getPermissionsState();
1954
1955        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1956                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1957
1958        for (String permission : pkg.requestedPermissions) {
1959            final BasePermission bp;
1960            synchronized (mPackages) {
1961                bp = mSettings.mPermissions.get(permission);
1962            }
1963            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1964                    && (grantedPermissions == null
1965                           || ArrayUtils.contains(grantedPermissions, permission))) {
1966                final int flags = permissionsState.getPermissionFlags(permission, userId);
1967                // Installer cannot change immutable permissions.
1968                if ((flags & immutableFlags) == 0) {
1969                    grantRuntimePermission(pkg.packageName, permission, userId);
1970                }
1971            }
1972        }
1973    }
1974
1975    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1976        Bundle extras = null;
1977        switch (res.returnCode) {
1978            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1979                extras = new Bundle();
1980                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1981                        res.origPermission);
1982                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1983                        res.origPackage);
1984                break;
1985            }
1986            case PackageManager.INSTALL_SUCCEEDED: {
1987                extras = new Bundle();
1988                extras.putBoolean(Intent.EXTRA_REPLACING,
1989                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1990                break;
1991            }
1992        }
1993        return extras;
1994    }
1995
1996    void scheduleWriteSettingsLocked() {
1997        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1998            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1999        }
2000    }
2001
2002    void scheduleWritePackageListLocked(int userId) {
2003        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2004            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2005            msg.arg1 = userId;
2006            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2007        }
2008    }
2009
2010    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2011        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2012        scheduleWritePackageRestrictionsLocked(userId);
2013    }
2014
2015    void scheduleWritePackageRestrictionsLocked(int userId) {
2016        final int[] userIds = (userId == UserHandle.USER_ALL)
2017                ? sUserManager.getUserIds() : new int[]{userId};
2018        for (int nextUserId : userIds) {
2019            if (!sUserManager.exists(nextUserId)) return;
2020            mDirtyUsers.add(nextUserId);
2021            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2022                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2023            }
2024        }
2025    }
2026
2027    public static PackageManagerService main(Context context, Installer installer,
2028            boolean factoryTest, boolean onlyCore) {
2029        // Self-check for initial settings.
2030        PackageManagerServiceCompilerMapping.checkProperties();
2031
2032        PackageManagerService m = new PackageManagerService(context, installer,
2033                factoryTest, onlyCore);
2034        m.enableSystemUserPackages();
2035        ServiceManager.addService("package", m);
2036        return m;
2037    }
2038
2039    private void enableSystemUserPackages() {
2040        if (!UserManager.isSplitSystemUser()) {
2041            return;
2042        }
2043        // For system user, enable apps based on the following conditions:
2044        // - app is whitelisted or belong to one of these groups:
2045        //   -- system app which has no launcher icons
2046        //   -- system app which has INTERACT_ACROSS_USERS permission
2047        //   -- system IME app
2048        // - app is not in the blacklist
2049        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2050        Set<String> enableApps = new ArraySet<>();
2051        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2052                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2053                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2054        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2055        enableApps.addAll(wlApps);
2056        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2057                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2058        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2059        enableApps.removeAll(blApps);
2060        Log.i(TAG, "Applications installed for system user: " + enableApps);
2061        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2062                UserHandle.SYSTEM);
2063        final int allAppsSize = allAps.size();
2064        synchronized (mPackages) {
2065            for (int i = 0; i < allAppsSize; i++) {
2066                String pName = allAps.get(i);
2067                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2068                // Should not happen, but we shouldn't be failing if it does
2069                if (pkgSetting == null) {
2070                    continue;
2071                }
2072                boolean install = enableApps.contains(pName);
2073                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2074                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2075                            + " for system user");
2076                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2077                }
2078            }
2079        }
2080    }
2081
2082    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2083        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2084                Context.DISPLAY_SERVICE);
2085        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2086    }
2087
2088    /**
2089     * Requests that files preopted on a secondary system partition be copied to the data partition
2090     * if possible.  Note that the actual copying of the files is accomplished by init for security
2091     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2092     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2093     */
2094    private static void requestCopyPreoptedFiles() {
2095        final int WAIT_TIME_MS = 100;
2096        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2097        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2098            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2099            // We will wait for up to 100 seconds.
2100            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2101            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2102                try {
2103                    Thread.sleep(WAIT_TIME_MS);
2104                } catch (InterruptedException e) {
2105                    // Do nothing
2106                }
2107                if (SystemClock.uptimeMillis() > timeEnd) {
2108                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2109                    Slog.wtf(TAG, "cppreopt did not finish!");
2110                    break;
2111                }
2112            }
2113        }
2114    }
2115
2116    public PackageManagerService(Context context, Installer installer,
2117            boolean factoryTest, boolean onlyCore) {
2118        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2119        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2120                SystemClock.uptimeMillis());
2121
2122        if (mSdkVersion <= 0) {
2123            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2124        }
2125
2126        mContext = context;
2127
2128        mPermissionReviewRequired = context.getResources().getBoolean(
2129                R.bool.config_permissionReviewRequired);
2130
2131        mFactoryTest = factoryTest;
2132        mOnlyCore = onlyCore;
2133        mMetrics = new DisplayMetrics();
2134        mSettings = new Settings(mPackages);
2135        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2136                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2137        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2138                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2139        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2140                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2141        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2142                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2143        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2144                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2145        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2146                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2147
2148        String separateProcesses = SystemProperties.get("debug.separate_processes");
2149        if (separateProcesses != null && separateProcesses.length() > 0) {
2150            if ("*".equals(separateProcesses)) {
2151                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2152                mSeparateProcesses = null;
2153                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2154            } else {
2155                mDefParseFlags = 0;
2156                mSeparateProcesses = separateProcesses.split(",");
2157                Slog.w(TAG, "Running with debug.separate_processes: "
2158                        + separateProcesses);
2159            }
2160        } else {
2161            mDefParseFlags = 0;
2162            mSeparateProcesses = null;
2163        }
2164
2165        mInstaller = installer;
2166        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2167                "*dexopt*");
2168        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2169
2170        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2171                FgThread.get().getLooper());
2172
2173        getDefaultDisplayMetrics(context, mMetrics);
2174
2175        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2176        SystemConfig systemConfig = SystemConfig.getInstance();
2177        mGlobalGids = systemConfig.getGlobalGids();
2178        mSystemPermissions = systemConfig.getSystemPermissions();
2179        mAvailableFeatures = systemConfig.getAvailableFeatures();
2180        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2181
2182        mProtectedPackages = new ProtectedPackages(mContext);
2183
2184        synchronized (mInstallLock) {
2185        // writer
2186        synchronized (mPackages) {
2187            mHandlerThread = new ServiceThread(TAG,
2188                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2189            mHandlerThread.start();
2190            mHandler = new PackageHandler(mHandlerThread.getLooper());
2191            mProcessLoggingHandler = new ProcessLoggingHandler();
2192            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2193
2194            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2195
2196            File dataDir = Environment.getDataDirectory();
2197            mAppInstallDir = new File(dataDir, "app");
2198            mAppLib32InstallDir = new File(dataDir, "app-lib");
2199            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2200            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2201            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2202
2203            sUserManager = new UserManagerService(context, this, mPackages);
2204
2205            // Propagate permission configuration in to package manager.
2206            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2207                    = systemConfig.getPermissions();
2208            for (int i=0; i<permConfig.size(); i++) {
2209                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2210                BasePermission bp = mSettings.mPermissions.get(perm.name);
2211                if (bp == null) {
2212                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2213                    mSettings.mPermissions.put(perm.name, bp);
2214                }
2215                if (perm.gids != null) {
2216                    bp.setGids(perm.gids, perm.perUser);
2217                }
2218            }
2219
2220            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2221            for (int i=0; i<libConfig.size(); i++) {
2222                mSharedLibraries.put(libConfig.keyAt(i),
2223                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2224            }
2225
2226            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2227
2228            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2229            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2230            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2231
2232            // Clean up orphaned packages for which the code path doesn't exist
2233            // and they are an update to a system app - caused by bug/32321269
2234            final int packageSettingCount = mSettings.mPackages.size();
2235            for (int i = packageSettingCount - 1; i >= 0; i--) {
2236                PackageSetting ps = mSettings.mPackages.valueAt(i);
2237                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2238                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2239                    mSettings.mPackages.removeAt(i);
2240                    mSettings.enableSystemPackageLPw(ps.name);
2241                }
2242            }
2243
2244            if (mFirstBoot) {
2245                requestCopyPreoptedFiles();
2246            }
2247
2248            String customResolverActivity = Resources.getSystem().getString(
2249                    R.string.config_customResolverActivity);
2250            if (TextUtils.isEmpty(customResolverActivity)) {
2251                customResolverActivity = null;
2252            } else {
2253                mCustomResolverComponentName = ComponentName.unflattenFromString(
2254                        customResolverActivity);
2255            }
2256
2257            long startTime = SystemClock.uptimeMillis();
2258
2259            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2260                    startTime);
2261
2262            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2263            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2264
2265            if (bootClassPath == null) {
2266                Slog.w(TAG, "No BOOTCLASSPATH found!");
2267            }
2268
2269            if (systemServerClassPath == null) {
2270                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2271            }
2272
2273            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2274            final String[] dexCodeInstructionSets =
2275                    getDexCodeInstructionSets(
2276                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2277
2278            /**
2279             * Ensure all external libraries have had dexopt run on them.
2280             */
2281            if (mSharedLibraries.size() > 0) {
2282                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2283                // NOTE: For now, we're compiling these system "shared libraries"
2284                // (and framework jars) into all available architectures. It's possible
2285                // to compile them only when we come across an app that uses them (there's
2286                // already logic for that in scanPackageLI) but that adds some complexity.
2287                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2288                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2289                        final String lib = libEntry.path;
2290                        if (lib == null) {
2291                            continue;
2292                        }
2293
2294                        try {
2295                            // Shared libraries do not have profiles so we perform a full
2296                            // AOT compilation (if needed).
2297                            int dexoptNeeded = DexFile.getDexOptNeeded(
2298                                    lib, dexCodeInstructionSet,
2299                                    getCompilerFilterForReason(REASON_SHARED_APK),
2300                                    false /* newProfile */);
2301                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2302                                mInstaller.dexopt(lib, Process.SYSTEM_UID, "*",
2303                                        dexCodeInstructionSet, dexoptNeeded, null,
2304                                        DEXOPT_PUBLIC,
2305                                        getCompilerFilterForReason(REASON_SHARED_APK),
2306                                        StorageManager.UUID_PRIVATE_INTERNAL,
2307                                        SKIP_SHARED_LIBRARY_CHECK);
2308                            }
2309                        } catch (FileNotFoundException e) {
2310                            Slog.w(TAG, "Library not found: " + lib);
2311                        } catch (IOException | InstallerException e) {
2312                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2313                                    + e.getMessage());
2314                        }
2315                    }
2316                }
2317                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2318            }
2319
2320            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2321
2322            final VersionInfo ver = mSettings.getInternalVersion();
2323            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2324
2325            // when upgrading from pre-M, promote system app permissions from install to runtime
2326            mPromoteSystemApps =
2327                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2328
2329            // When upgrading from pre-N, we need to handle package extraction like first boot,
2330            // as there is no profiling data available.
2331            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2332
2333            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2334
2335            // save off the names of pre-existing system packages prior to scanning; we don't
2336            // want to automatically grant runtime permissions for new system apps
2337            if (mPromoteSystemApps) {
2338                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2339                while (pkgSettingIter.hasNext()) {
2340                    PackageSetting ps = pkgSettingIter.next();
2341                    if (isSystemApp(ps)) {
2342                        mExistingSystemPackages.add(ps.name);
2343                    }
2344                }
2345            }
2346
2347            // Set flag to monitor and not change apk file paths when
2348            // scanning install directories.
2349            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2350
2351            if (mIsUpgrade || mFirstBoot) {
2352                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2353            }
2354
2355            // Collect vendor overlay packages. (Do this before scanning any apps.)
2356            // For security and version matching reason, only consider
2357            // overlay packages if they reside in the right directory.
2358            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2359            if (overlayThemeDir.isEmpty()) {
2360                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2361            }
2362            if (!overlayThemeDir.isEmpty()) {
2363                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2364                        | PackageParser.PARSE_IS_SYSTEM
2365                        | PackageParser.PARSE_IS_SYSTEM_DIR
2366                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2367            }
2368            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2369                    | PackageParser.PARSE_IS_SYSTEM
2370                    | PackageParser.PARSE_IS_SYSTEM_DIR
2371                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2372
2373            // Find base frameworks (resource packages without code).
2374            scanDirTracedLI(frameworkDir, mDefParseFlags
2375                    | PackageParser.PARSE_IS_SYSTEM
2376                    | PackageParser.PARSE_IS_SYSTEM_DIR
2377                    | PackageParser.PARSE_IS_PRIVILEGED,
2378                    scanFlags | SCAN_NO_DEX, 0);
2379
2380            // Collected privileged system packages.
2381            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2382            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2383                    | PackageParser.PARSE_IS_SYSTEM
2384                    | PackageParser.PARSE_IS_SYSTEM_DIR
2385                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2386
2387            // Collect ordinary system packages.
2388            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2389            scanDirTracedLI(systemAppDir, mDefParseFlags
2390                    | PackageParser.PARSE_IS_SYSTEM
2391                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2392
2393            // Collect all vendor packages.
2394            File vendorAppDir = new File("/vendor/app");
2395            try {
2396                vendorAppDir = vendorAppDir.getCanonicalFile();
2397            } catch (IOException e) {
2398                // failed to look up canonical path, continue with original one
2399            }
2400            scanDirTracedLI(vendorAppDir, mDefParseFlags
2401                    | PackageParser.PARSE_IS_SYSTEM
2402                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2403
2404            // Collect all OEM packages.
2405            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2406            scanDirTracedLI(oemAppDir, mDefParseFlags
2407                    | PackageParser.PARSE_IS_SYSTEM
2408                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2409
2410            // Prune any system packages that no longer exist.
2411            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2412            if (!mOnlyCore) {
2413                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2414                while (psit.hasNext()) {
2415                    PackageSetting ps = psit.next();
2416
2417                    /*
2418                     * If this is not a system app, it can't be a
2419                     * disable system app.
2420                     */
2421                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2422                        continue;
2423                    }
2424
2425                    /*
2426                     * If the package is scanned, it's not erased.
2427                     */
2428                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2429                    if (scannedPkg != null) {
2430                        /*
2431                         * If the system app is both scanned and in the
2432                         * disabled packages list, then it must have been
2433                         * added via OTA. Remove it from the currently
2434                         * scanned package so the previously user-installed
2435                         * application can be scanned.
2436                         */
2437                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2438                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2439                                    + ps.name + "; removing system app.  Last known codePath="
2440                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2441                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2442                                    + scannedPkg.mVersionCode);
2443                            removePackageLI(scannedPkg, true);
2444                            mExpectingBetter.put(ps.name, ps.codePath);
2445                        }
2446
2447                        continue;
2448                    }
2449
2450                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2451                        psit.remove();
2452                        logCriticalInfo(Log.WARN, "System package " + ps.name
2453                                + " no longer exists; it's data will be wiped");
2454                        // Actual deletion of code and data will be handled by later
2455                        // reconciliation step
2456                    } else {
2457                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2458                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2459                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2460                        }
2461                    }
2462                }
2463            }
2464
2465            //look for any incomplete package installations
2466            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2467            for (int i = 0; i < deletePkgsList.size(); i++) {
2468                // Actual deletion of code and data will be handled by later
2469                // reconciliation step
2470                final String packageName = deletePkgsList.get(i).name;
2471                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2472                synchronized (mPackages) {
2473                    mSettings.removePackageLPw(packageName);
2474                }
2475            }
2476
2477            //delete tmp files
2478            deleteTempPackageFiles();
2479
2480            // Remove any shared userIDs that have no associated packages
2481            mSettings.pruneSharedUsersLPw();
2482
2483            if (!mOnlyCore) {
2484                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2485                        SystemClock.uptimeMillis());
2486                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2487
2488                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2489                        | PackageParser.PARSE_FORWARD_LOCK,
2490                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2491
2492                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2493                        | PackageParser.PARSE_IS_EPHEMERAL,
2494                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2495
2496                /**
2497                 * Remove disable package settings for any updated system
2498                 * apps that were removed via an OTA. If they're not a
2499                 * previously-updated app, remove them completely.
2500                 * Otherwise, just revoke their system-level permissions.
2501                 */
2502                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2503                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2504                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2505
2506                    String msg;
2507                    if (deletedPkg == null) {
2508                        msg = "Updated system package " + deletedAppName
2509                                + " no longer exists; it's data will be wiped";
2510                        // Actual deletion of code and data will be handled by later
2511                        // reconciliation step
2512                    } else {
2513                        msg = "Updated system app + " + deletedAppName
2514                                + " no longer present; removing system privileges for "
2515                                + deletedAppName;
2516
2517                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2518
2519                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2520                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2521                    }
2522                    logCriticalInfo(Log.WARN, msg);
2523                }
2524
2525                /**
2526                 * Make sure all system apps that we expected to appear on
2527                 * the userdata partition actually showed up. If they never
2528                 * appeared, crawl back and revive the system version.
2529                 */
2530                for (int i = 0; i < mExpectingBetter.size(); i++) {
2531                    final String packageName = mExpectingBetter.keyAt(i);
2532                    if (!mPackages.containsKey(packageName)) {
2533                        final File scanFile = mExpectingBetter.valueAt(i);
2534
2535                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2536                                + " but never showed up; reverting to system");
2537
2538                        int reparseFlags = mDefParseFlags;
2539                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2540                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2541                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2542                                    | PackageParser.PARSE_IS_PRIVILEGED;
2543                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2544                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2545                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2546                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2547                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2548                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2549                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2550                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2551                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2552                        } else {
2553                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2554                            continue;
2555                        }
2556
2557                        mSettings.enableSystemPackageLPw(packageName);
2558
2559                        try {
2560                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2561                        } catch (PackageManagerException e) {
2562                            Slog.e(TAG, "Failed to parse original system package: "
2563                                    + e.getMessage());
2564                        }
2565                    }
2566                }
2567            }
2568            mExpectingBetter.clear();
2569
2570            // Resolve the storage manager.
2571            mStorageManagerPackage = getStorageManagerPackageName();
2572
2573            // Resolve protected action filters. Only the setup wizard is allowed to
2574            // have a high priority filter for these actions.
2575            mSetupWizardPackage = getSetupWizardPackageName();
2576            if (mProtectedFilters.size() > 0) {
2577                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2578                    Slog.i(TAG, "No setup wizard;"
2579                        + " All protected intents capped to priority 0");
2580                }
2581                for (ActivityIntentInfo filter : mProtectedFilters) {
2582                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2583                        if (DEBUG_FILTERS) {
2584                            Slog.i(TAG, "Found setup wizard;"
2585                                + " allow priority " + filter.getPriority() + ";"
2586                                + " package: " + filter.activity.info.packageName
2587                                + " activity: " + filter.activity.className
2588                                + " priority: " + filter.getPriority());
2589                        }
2590                        // skip setup wizard; allow it to keep the high priority filter
2591                        continue;
2592                    }
2593                    Slog.w(TAG, "Protected action; cap priority to 0;"
2594                            + " package: " + filter.activity.info.packageName
2595                            + " activity: " + filter.activity.className
2596                            + " origPrio: " + filter.getPriority());
2597                    filter.setPriority(0);
2598                }
2599            }
2600            mDeferProtectedFilters = false;
2601            mProtectedFilters.clear();
2602
2603            // Now that we know all of the shared libraries, update all clients to have
2604            // the correct library paths.
2605            updateAllSharedLibrariesLPw();
2606
2607            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2608                // NOTE: We ignore potential failures here during a system scan (like
2609                // the rest of the commands above) because there's precious little we
2610                // can do about it. A settings error is reported, though.
2611                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2612            }
2613
2614            // Now that we know all the packages we are keeping,
2615            // read and update their last usage times.
2616            mPackageUsage.read(mPackages);
2617            mCompilerStats.read();
2618
2619            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2620                    SystemClock.uptimeMillis());
2621            Slog.i(TAG, "Time to scan packages: "
2622                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2623                    + " seconds");
2624
2625            // If the platform SDK has changed since the last time we booted,
2626            // we need to re-grant app permission to catch any new ones that
2627            // appear.  This is really a hack, and means that apps can in some
2628            // cases get permissions that the user didn't initially explicitly
2629            // allow...  it would be nice to have some better way to handle
2630            // this situation.
2631            int updateFlags = UPDATE_PERMISSIONS_ALL;
2632            if (ver.sdkVersion != mSdkVersion) {
2633                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2634                        + mSdkVersion + "; regranting permissions for internal storage");
2635                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2636            }
2637            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2638            ver.sdkVersion = mSdkVersion;
2639
2640            // If this is the first boot or an update from pre-M, and it is a normal
2641            // boot, then we need to initialize the default preferred apps across
2642            // all defined users.
2643            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2644                for (UserInfo user : sUserManager.getUsers(true)) {
2645                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2646                    applyFactoryDefaultBrowserLPw(user.id);
2647                    primeDomainVerificationsLPw(user.id);
2648                }
2649            }
2650
2651            // Prepare storage for system user really early during boot,
2652            // since core system apps like SettingsProvider and SystemUI
2653            // can't wait for user to start
2654            final int storageFlags;
2655            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2656                storageFlags = StorageManager.FLAG_STORAGE_DE;
2657            } else {
2658                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2659            }
2660            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2661                    storageFlags, true /* migrateAppData */);
2662
2663            // If this is first boot after an OTA, and a normal boot, then
2664            // we need to clear code cache directories.
2665            // Note that we do *not* clear the application profiles. These remain valid
2666            // across OTAs and are used to drive profile verification (post OTA) and
2667            // profile compilation (without waiting to collect a fresh set of profiles).
2668            if (mIsUpgrade && !onlyCore) {
2669                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2670                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2671                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2672                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2673                        // No apps are running this early, so no need to freeze
2674                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2675                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2676                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2677                    }
2678                }
2679                ver.fingerprint = Build.FINGERPRINT;
2680            }
2681
2682            checkDefaultBrowser();
2683
2684            // clear only after permissions and other defaults have been updated
2685            mExistingSystemPackages.clear();
2686            mPromoteSystemApps = false;
2687
2688            // All the changes are done during package scanning.
2689            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2690
2691            // can downgrade to reader
2692            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2693            mSettings.writeLPr();
2694            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2695
2696            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2697            // early on (before the package manager declares itself as early) because other
2698            // components in the system server might ask for package contexts for these apps.
2699            //
2700            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2701            // (i.e, that the data partition is unavailable).
2702            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2703                long start = System.nanoTime();
2704                List<PackageParser.Package> coreApps = new ArrayList<>();
2705                for (PackageParser.Package pkg : mPackages.values()) {
2706                    if (pkg.coreApp) {
2707                        coreApps.add(pkg);
2708                    }
2709                }
2710
2711                int[] stats = performDexOptUpgrade(coreApps, false,
2712                        getCompilerFilterForReason(REASON_CORE_APP));
2713
2714                final int elapsedTimeSeconds =
2715                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2716                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2717
2718                if (DEBUG_DEXOPT) {
2719                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2720                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2721                }
2722
2723
2724                // TODO: Should we log these stats to tron too ?
2725                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2726                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2727                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2728                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2729            }
2730
2731            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2732                    SystemClock.uptimeMillis());
2733
2734            if (!mOnlyCore) {
2735                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2736                mRequiredInstallerPackage = getRequiredInstallerLPr();
2737                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2738                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2739                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2740                        mIntentFilterVerifierComponent);
2741                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2742                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2743                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2744                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2745            } else {
2746                mRequiredVerifierPackage = null;
2747                mRequiredInstallerPackage = null;
2748                mRequiredUninstallerPackage = null;
2749                mIntentFilterVerifierComponent = null;
2750                mIntentFilterVerifier = null;
2751                mServicesSystemSharedLibraryPackageName = null;
2752                mSharedSystemSharedLibraryPackageName = null;
2753            }
2754
2755            mInstallerService = new PackageInstallerService(context, this);
2756
2757            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2758            if (ephemeralResolverComponent != null) {
2759                if (DEBUG_EPHEMERAL) {
2760                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2761                }
2762                mEphemeralResolverConnection =
2763                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2764            } else {
2765                mEphemeralResolverConnection = null;
2766            }
2767            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2768            if (mEphemeralInstallerComponent != null) {
2769                if (DEBUG_EPHEMERAL) {
2770                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2771                }
2772                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2773            }
2774
2775            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2776        } // synchronized (mPackages)
2777        } // synchronized (mInstallLock)
2778
2779        // Now after opening every single application zip, make sure they
2780        // are all flushed.  Not really needed, but keeps things nice and
2781        // tidy.
2782        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2783        Runtime.getRuntime().gc();
2784        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2785
2786        // The initial scanning above does many calls into installd while
2787        // holding the mPackages lock, but we're mostly interested in yelling
2788        // once we have a booted system.
2789        mInstaller.setWarnIfHeld(mPackages);
2790
2791        // Expose private service for system components to use.
2792        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2793        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2794    }
2795
2796    @Override
2797    public boolean isFirstBoot() {
2798        return mFirstBoot;
2799    }
2800
2801    @Override
2802    public boolean isOnlyCoreApps() {
2803        return mOnlyCore;
2804    }
2805
2806    @Override
2807    public boolean isUpgrade() {
2808        return mIsUpgrade;
2809    }
2810
2811    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2812        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2813
2814        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2815                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2816                UserHandle.USER_SYSTEM);
2817        if (matches.size() == 1) {
2818            return matches.get(0).getComponentInfo().packageName;
2819        } else if (matches.size() == 0) {
2820            Log.e(TAG, "There should probably be a verifier, but, none were found");
2821            return null;
2822        }
2823        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2824    }
2825
2826    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2827        synchronized (mPackages) {
2828            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2829            if (libraryEntry == null) {
2830                throw new IllegalStateException("Missing required shared library:" + libraryName);
2831            }
2832            return libraryEntry.apk;
2833        }
2834    }
2835
2836    private @NonNull String getRequiredInstallerLPr() {
2837        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2838        intent.addCategory(Intent.CATEGORY_DEFAULT);
2839        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2840
2841        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2842                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2843                UserHandle.USER_SYSTEM);
2844        if (matches.size() == 1) {
2845            ResolveInfo resolveInfo = matches.get(0);
2846            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2847                throw new RuntimeException("The installer must be a privileged app");
2848            }
2849            return matches.get(0).getComponentInfo().packageName;
2850        } else {
2851            throw new RuntimeException("There must be exactly one installer; found " + matches);
2852        }
2853    }
2854
2855    private @NonNull String getRequiredUninstallerLPr() {
2856        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2857        intent.addCategory(Intent.CATEGORY_DEFAULT);
2858        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2859
2860        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2861                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2862                UserHandle.USER_SYSTEM);
2863        if (resolveInfo == null ||
2864                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2865            throw new RuntimeException("There must be exactly one uninstaller; found "
2866                    + resolveInfo);
2867        }
2868        return resolveInfo.getComponentInfo().packageName;
2869    }
2870
2871    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2872        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2873
2874        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2875                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2876                UserHandle.USER_SYSTEM);
2877        ResolveInfo best = null;
2878        final int N = matches.size();
2879        for (int i = 0; i < N; i++) {
2880            final ResolveInfo cur = matches.get(i);
2881            final String packageName = cur.getComponentInfo().packageName;
2882            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2883                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2884                continue;
2885            }
2886
2887            if (best == null || cur.priority > best.priority) {
2888                best = cur;
2889            }
2890        }
2891
2892        if (best != null) {
2893            return best.getComponentInfo().getComponentName();
2894        } else {
2895            throw new RuntimeException("There must be at least one intent filter verifier");
2896        }
2897    }
2898
2899    private @Nullable ComponentName getEphemeralResolverLPr() {
2900        final String[] packageArray =
2901                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2902        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2903            if (DEBUG_EPHEMERAL) {
2904                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2905            }
2906            return null;
2907        }
2908
2909        final int resolveFlags =
2910                MATCH_DIRECT_BOOT_AWARE
2911                | MATCH_DIRECT_BOOT_UNAWARE
2912                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2913        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2914        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2915                resolveFlags, UserHandle.USER_SYSTEM);
2916
2917        final int N = resolvers.size();
2918        if (N == 0) {
2919            if (DEBUG_EPHEMERAL) {
2920                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2921            }
2922            return null;
2923        }
2924
2925        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2926        for (int i = 0; i < N; i++) {
2927            final ResolveInfo info = resolvers.get(i);
2928
2929            if (info.serviceInfo == null) {
2930                continue;
2931            }
2932
2933            final String packageName = info.serviceInfo.packageName;
2934            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2935                if (DEBUG_EPHEMERAL) {
2936                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2937                            + " pkg: " + packageName + ", info:" + info);
2938                }
2939                continue;
2940            }
2941
2942            if (DEBUG_EPHEMERAL) {
2943                Slog.v(TAG, "Ephemeral resolver found;"
2944                        + " pkg: " + packageName + ", info:" + info);
2945            }
2946            return new ComponentName(packageName, info.serviceInfo.name);
2947        }
2948        if (DEBUG_EPHEMERAL) {
2949            Slog.v(TAG, "Ephemeral resolver NOT found");
2950        }
2951        return null;
2952    }
2953
2954    private @Nullable ComponentName getEphemeralInstallerLPr() {
2955        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2956        intent.addCategory(Intent.CATEGORY_DEFAULT);
2957        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2958
2959        final int resolveFlags =
2960                MATCH_DIRECT_BOOT_AWARE
2961                | MATCH_DIRECT_BOOT_UNAWARE
2962                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2963        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2964                resolveFlags, UserHandle.USER_SYSTEM);
2965        Iterator<ResolveInfo> iter = matches.iterator();
2966        while (iter.hasNext()) {
2967            final ResolveInfo rInfo = iter.next();
2968            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
2969            if (ps != null) {
2970                final PermissionsState permissionsState = ps.getPermissionsState();
2971                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
2972                    continue;
2973                }
2974            }
2975            iter.remove();
2976        }
2977        if (matches.size() == 0) {
2978            return null;
2979        } else if (matches.size() == 1) {
2980            return matches.get(0).getComponentInfo().getComponentName();
2981        } else {
2982            throw new RuntimeException(
2983                    "There must be at most one ephemeral installer; found " + matches);
2984        }
2985    }
2986
2987    private void primeDomainVerificationsLPw(int userId) {
2988        if (DEBUG_DOMAIN_VERIFICATION) {
2989            Slog.d(TAG, "Priming domain verifications in user " + userId);
2990        }
2991
2992        SystemConfig systemConfig = SystemConfig.getInstance();
2993        ArraySet<String> packages = systemConfig.getLinkedApps();
2994
2995        for (String packageName : packages) {
2996            PackageParser.Package pkg = mPackages.get(packageName);
2997            if (pkg != null) {
2998                if (!pkg.isSystemApp()) {
2999                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3000                    continue;
3001                }
3002
3003                ArraySet<String> domains = null;
3004                for (PackageParser.Activity a : pkg.activities) {
3005                    for (ActivityIntentInfo filter : a.intents) {
3006                        if (hasValidDomains(filter)) {
3007                            if (domains == null) {
3008                                domains = new ArraySet<String>();
3009                            }
3010                            domains.addAll(filter.getHostsList());
3011                        }
3012                    }
3013                }
3014
3015                if (domains != null && domains.size() > 0) {
3016                    if (DEBUG_DOMAIN_VERIFICATION) {
3017                        Slog.v(TAG, "      + " + packageName);
3018                    }
3019                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3020                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3021                    // and then 'always' in the per-user state actually used for intent resolution.
3022                    final IntentFilterVerificationInfo ivi;
3023                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3024                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3025                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3026                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3027                } else {
3028                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3029                            + "' does not handle web links");
3030                }
3031            } else {
3032                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3033            }
3034        }
3035
3036        scheduleWritePackageRestrictionsLocked(userId);
3037        scheduleWriteSettingsLocked();
3038    }
3039
3040    private void applyFactoryDefaultBrowserLPw(int userId) {
3041        // The default browser app's package name is stored in a string resource,
3042        // with a product-specific overlay used for vendor customization.
3043        String browserPkg = mContext.getResources().getString(
3044                com.android.internal.R.string.default_browser);
3045        if (!TextUtils.isEmpty(browserPkg)) {
3046            // non-empty string => required to be a known package
3047            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3048            if (ps == null) {
3049                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3050                browserPkg = null;
3051            } else {
3052                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3053            }
3054        }
3055
3056        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3057        // default.  If there's more than one, just leave everything alone.
3058        if (browserPkg == null) {
3059            calculateDefaultBrowserLPw(userId);
3060        }
3061    }
3062
3063    private void calculateDefaultBrowserLPw(int userId) {
3064        List<String> allBrowsers = resolveAllBrowserApps(userId);
3065        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3066        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3067    }
3068
3069    private List<String> resolveAllBrowserApps(int userId) {
3070        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3071        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3072                PackageManager.MATCH_ALL, userId);
3073
3074        final int count = list.size();
3075        List<String> result = new ArrayList<String>(count);
3076        for (int i=0; i<count; i++) {
3077            ResolveInfo info = list.get(i);
3078            if (info.activityInfo == null
3079                    || !info.handleAllWebDataURI
3080                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3081                    || result.contains(info.activityInfo.packageName)) {
3082                continue;
3083            }
3084            result.add(info.activityInfo.packageName);
3085        }
3086
3087        return result;
3088    }
3089
3090    private boolean packageIsBrowser(String packageName, int userId) {
3091        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3092                PackageManager.MATCH_ALL, userId);
3093        final int N = list.size();
3094        for (int i = 0; i < N; i++) {
3095            ResolveInfo info = list.get(i);
3096            if (packageName.equals(info.activityInfo.packageName)) {
3097                return true;
3098            }
3099        }
3100        return false;
3101    }
3102
3103    private void checkDefaultBrowser() {
3104        final int myUserId = UserHandle.myUserId();
3105        final String packageName = getDefaultBrowserPackageName(myUserId);
3106        if (packageName != null) {
3107            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3108            if (info == null) {
3109                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3110                synchronized (mPackages) {
3111                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3112                }
3113            }
3114        }
3115    }
3116
3117    @Override
3118    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3119            throws RemoteException {
3120        try {
3121            return super.onTransact(code, data, reply, flags);
3122        } catch (RuntimeException e) {
3123            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3124                Slog.wtf(TAG, "Package Manager Crash", e);
3125            }
3126            throw e;
3127        }
3128    }
3129
3130    static int[] appendInts(int[] cur, int[] add) {
3131        if (add == null) return cur;
3132        if (cur == null) return add;
3133        final int N = add.length;
3134        for (int i=0; i<N; i++) {
3135            cur = appendInt(cur, add[i]);
3136        }
3137        return cur;
3138    }
3139
3140    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3141        if (!sUserManager.exists(userId)) return null;
3142        if (ps == null) {
3143            return null;
3144        }
3145        final PackageParser.Package p = ps.pkg;
3146        if (p == null) {
3147            return null;
3148        }
3149
3150        final PermissionsState permissionsState = ps.getPermissionsState();
3151
3152        // Compute GIDs only if requested
3153        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3154                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3155        // Compute granted permissions only if package has requested permissions
3156        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3157                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3158        final PackageUserState state = ps.readUserState(userId);
3159
3160        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3161                && ps.isSystem()) {
3162            flags |= MATCH_ANY_USER;
3163        }
3164
3165        return PackageParser.generatePackageInfo(p, gids, flags,
3166                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3167    }
3168
3169    @Override
3170    public void checkPackageStartable(String packageName, int userId) {
3171        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3172
3173        synchronized (mPackages) {
3174            final PackageSetting ps = mSettings.mPackages.get(packageName);
3175            if (ps == null) {
3176                throw new SecurityException("Package " + packageName + " was not found!");
3177            }
3178
3179            if (!ps.getInstalled(userId)) {
3180                throw new SecurityException(
3181                        "Package " + packageName + " was not installed for user " + userId + "!");
3182            }
3183
3184            if (mSafeMode && !ps.isSystem()) {
3185                throw new SecurityException("Package " + packageName + " not a system app!");
3186            }
3187
3188            if (mFrozenPackages.contains(packageName)) {
3189                throw new SecurityException("Package " + packageName + " is currently frozen!");
3190            }
3191
3192            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3193                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3194                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3195            }
3196        }
3197    }
3198
3199    @Override
3200    public boolean isPackageAvailable(String packageName, int userId) {
3201        if (!sUserManager.exists(userId)) return false;
3202        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3203                false /* requireFullPermission */, false /* checkShell */, "is package available");
3204        synchronized (mPackages) {
3205            PackageParser.Package p = mPackages.get(packageName);
3206            if (p != null) {
3207                final PackageSetting ps = (PackageSetting) p.mExtras;
3208                if (ps != null) {
3209                    final PackageUserState state = ps.readUserState(userId);
3210                    if (state != null) {
3211                        return PackageParser.isAvailable(state);
3212                    }
3213                }
3214            }
3215        }
3216        return false;
3217    }
3218
3219    @Override
3220    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3221        if (!sUserManager.exists(userId)) return null;
3222        flags = updateFlagsForPackage(flags, userId, packageName);
3223        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3224                false /* requireFullPermission */, false /* checkShell */, "get package info");
3225
3226        // reader
3227        synchronized (mPackages) {
3228            // Normalize package name to hanlde renamed packages
3229            packageName = normalizePackageNameLPr(packageName);
3230
3231            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3232            PackageParser.Package p = null;
3233            if (matchFactoryOnly) {
3234                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3235                if (ps != null) {
3236                    return generatePackageInfo(ps, flags, userId);
3237                }
3238            }
3239            if (p == null) {
3240                p = mPackages.get(packageName);
3241                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3242                    return null;
3243                }
3244            }
3245            if (DEBUG_PACKAGE_INFO)
3246                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3247            if (p != null) {
3248                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3249            }
3250            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3251                final PackageSetting ps = mSettings.mPackages.get(packageName);
3252                return generatePackageInfo(ps, flags, userId);
3253            }
3254        }
3255        return null;
3256    }
3257
3258    @Override
3259    public String[] currentToCanonicalPackageNames(String[] names) {
3260        String[] out = new String[names.length];
3261        // reader
3262        synchronized (mPackages) {
3263            for (int i=names.length-1; i>=0; i--) {
3264                PackageSetting ps = mSettings.mPackages.get(names[i]);
3265                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3266            }
3267        }
3268        return out;
3269    }
3270
3271    @Override
3272    public String[] canonicalToCurrentPackageNames(String[] names) {
3273        String[] out = new String[names.length];
3274        // reader
3275        synchronized (mPackages) {
3276            for (int i=names.length-1; i>=0; i--) {
3277                String cur = mSettings.getRenamedPackageLPr(names[i]);
3278                out[i] = cur != null ? cur : names[i];
3279            }
3280        }
3281        return out;
3282    }
3283
3284    @Override
3285    public int getPackageUid(String packageName, int flags, int userId) {
3286        if (!sUserManager.exists(userId)) return -1;
3287        flags = updateFlagsForPackage(flags, userId, packageName);
3288        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3289                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3290
3291        // reader
3292        synchronized (mPackages) {
3293            final PackageParser.Package p = mPackages.get(packageName);
3294            if (p != null && p.isMatch(flags)) {
3295                return UserHandle.getUid(userId, p.applicationInfo.uid);
3296            }
3297            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3298                final PackageSetting ps = mSettings.mPackages.get(packageName);
3299                if (ps != null && ps.isMatch(flags)) {
3300                    return UserHandle.getUid(userId, ps.appId);
3301                }
3302            }
3303        }
3304
3305        return -1;
3306    }
3307
3308    @Override
3309    public int[] getPackageGids(String packageName, int flags, int userId) {
3310        if (!sUserManager.exists(userId)) return null;
3311        flags = updateFlagsForPackage(flags, userId, packageName);
3312        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3313                false /* requireFullPermission */, false /* checkShell */,
3314                "getPackageGids");
3315
3316        // reader
3317        synchronized (mPackages) {
3318            final PackageParser.Package p = mPackages.get(packageName);
3319            if (p != null && p.isMatch(flags)) {
3320                PackageSetting ps = (PackageSetting) p.mExtras;
3321                // TODO: Shouldn't this be checking for package installed state for userId and
3322                // return null?
3323                return ps.getPermissionsState().computeGids(userId);
3324            }
3325            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3326                final PackageSetting ps = mSettings.mPackages.get(packageName);
3327                if (ps != null && ps.isMatch(flags)) {
3328                    return ps.getPermissionsState().computeGids(userId);
3329                }
3330            }
3331        }
3332
3333        return null;
3334    }
3335
3336    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3337        if (bp.perm != null) {
3338            return PackageParser.generatePermissionInfo(bp.perm, flags);
3339        }
3340        PermissionInfo pi = new PermissionInfo();
3341        pi.name = bp.name;
3342        pi.packageName = bp.sourcePackage;
3343        pi.nonLocalizedLabel = bp.name;
3344        pi.protectionLevel = bp.protectionLevel;
3345        return pi;
3346    }
3347
3348    @Override
3349    public PermissionInfo getPermissionInfo(String name, int flags) {
3350        // reader
3351        synchronized (mPackages) {
3352            final BasePermission p = mSettings.mPermissions.get(name);
3353            if (p != null) {
3354                return generatePermissionInfo(p, flags);
3355            }
3356            return null;
3357        }
3358    }
3359
3360    @Override
3361    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3362            int flags) {
3363        // reader
3364        synchronized (mPackages) {
3365            if (group != null && !mPermissionGroups.containsKey(group)) {
3366                // This is thrown as NameNotFoundException
3367                return null;
3368            }
3369
3370            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3371            for (BasePermission p : mSettings.mPermissions.values()) {
3372                if (group == null) {
3373                    if (p.perm == null || p.perm.info.group == null) {
3374                        out.add(generatePermissionInfo(p, flags));
3375                    }
3376                } else {
3377                    if (p.perm != null && group.equals(p.perm.info.group)) {
3378                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3379                    }
3380                }
3381            }
3382            return new ParceledListSlice<>(out);
3383        }
3384    }
3385
3386    @Override
3387    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3388        // reader
3389        synchronized (mPackages) {
3390            return PackageParser.generatePermissionGroupInfo(
3391                    mPermissionGroups.get(name), flags);
3392        }
3393    }
3394
3395    @Override
3396    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3397        // reader
3398        synchronized (mPackages) {
3399            final int N = mPermissionGroups.size();
3400            ArrayList<PermissionGroupInfo> out
3401                    = new ArrayList<PermissionGroupInfo>(N);
3402            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3403                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3404            }
3405            return new ParceledListSlice<>(out);
3406        }
3407    }
3408
3409    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3410            int userId) {
3411        if (!sUserManager.exists(userId)) return null;
3412        PackageSetting ps = mSettings.mPackages.get(packageName);
3413        if (ps != null) {
3414            if (ps.pkg == null) {
3415                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3416                if (pInfo != null) {
3417                    return pInfo.applicationInfo;
3418                }
3419                return null;
3420            }
3421            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3422                    ps.readUserState(userId), userId);
3423        }
3424        return null;
3425    }
3426
3427    @Override
3428    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3429        if (!sUserManager.exists(userId)) return null;
3430        flags = updateFlagsForApplication(flags, userId, packageName);
3431        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3432                false /* requireFullPermission */, false /* checkShell */, "get application info");
3433
3434        // writer
3435        synchronized (mPackages) {
3436            // Normalize package name to hanlde renamed packages
3437            packageName = normalizePackageNameLPr(packageName);
3438
3439            PackageParser.Package p = mPackages.get(packageName);
3440            if (DEBUG_PACKAGE_INFO) Log.v(
3441                    TAG, "getApplicationInfo " + packageName
3442                    + ": " + p);
3443            if (p != null) {
3444                PackageSetting ps = mSettings.mPackages.get(packageName);
3445                if (ps == null) return null;
3446                // Note: isEnabledLP() does not apply here - always return info
3447                return PackageParser.generateApplicationInfo(
3448                        p, flags, ps.readUserState(userId), userId);
3449            }
3450            if ("android".equals(packageName)||"system".equals(packageName)) {
3451                return mAndroidApplication;
3452            }
3453            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3454                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3455            }
3456        }
3457        return null;
3458    }
3459
3460    private String normalizePackageNameLPr(String packageName) {
3461        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3462        return normalizedPackageName != null ? normalizedPackageName : packageName;
3463    }
3464
3465    @Override
3466    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3467            final IPackageDataObserver observer) {
3468        mContext.enforceCallingOrSelfPermission(
3469                android.Manifest.permission.CLEAR_APP_CACHE, null);
3470        // Queue up an async operation since clearing cache may take a little while.
3471        mHandler.post(new Runnable() {
3472            public void run() {
3473                mHandler.removeCallbacks(this);
3474                boolean success = true;
3475                synchronized (mInstallLock) {
3476                    try {
3477                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3478                    } catch (InstallerException e) {
3479                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3480                        success = false;
3481                    }
3482                }
3483                if (observer != null) {
3484                    try {
3485                        observer.onRemoveCompleted(null, success);
3486                    } catch (RemoteException e) {
3487                        Slog.w(TAG, "RemoveException when invoking call back");
3488                    }
3489                }
3490            }
3491        });
3492    }
3493
3494    @Override
3495    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3496            final IntentSender pi) {
3497        mContext.enforceCallingOrSelfPermission(
3498                android.Manifest.permission.CLEAR_APP_CACHE, null);
3499        // Queue up an async operation since clearing cache may take a little while.
3500        mHandler.post(new Runnable() {
3501            public void run() {
3502                mHandler.removeCallbacks(this);
3503                boolean success = true;
3504                synchronized (mInstallLock) {
3505                    try {
3506                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3507                    } catch (InstallerException e) {
3508                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3509                        success = false;
3510                    }
3511                }
3512                if(pi != null) {
3513                    try {
3514                        // Callback via pending intent
3515                        int code = success ? 1 : 0;
3516                        pi.sendIntent(null, code, null,
3517                                null, null);
3518                    } catch (SendIntentException e1) {
3519                        Slog.i(TAG, "Failed to send pending intent");
3520                    }
3521                }
3522            }
3523        });
3524    }
3525
3526    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3527        synchronized (mInstallLock) {
3528            try {
3529                mInstaller.freeCache(volumeUuid, freeStorageSize);
3530            } catch (InstallerException e) {
3531                throw new IOException("Failed to free enough space", e);
3532            }
3533        }
3534    }
3535
3536    /**
3537     * Update given flags based on encryption status of current user.
3538     */
3539    private int updateFlags(int flags, int userId) {
3540        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3541                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3542            // Caller expressed an explicit opinion about what encryption
3543            // aware/unaware components they want to see, so fall through and
3544            // give them what they want
3545        } else {
3546            // Caller expressed no opinion, so match based on user state
3547            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3548                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3549            } else {
3550                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3551            }
3552        }
3553        return flags;
3554    }
3555
3556    private UserManagerInternal getUserManagerInternal() {
3557        if (mUserManagerInternal == null) {
3558            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3559        }
3560        return mUserManagerInternal;
3561    }
3562
3563    /**
3564     * Update given flags when being used to request {@link PackageInfo}.
3565     */
3566    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3567        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3568        boolean triaged = true;
3569        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3570                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3571            // Caller is asking for component details, so they'd better be
3572            // asking for specific encryption matching behavior, or be triaged
3573            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3574                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3575                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3576                triaged = false;
3577            }
3578        }
3579        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3580                | PackageManager.MATCH_SYSTEM_ONLY
3581                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3582            triaged = false;
3583        }
3584        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3585            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3586                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3587                    + Debug.getCallers(5));
3588        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3589                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3590            // If the caller wants all packages and has a restricted profile associated with it,
3591            // then match all users. This is to make sure that launchers that need to access work
3592            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3593            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3594            flags |= PackageManager.MATCH_ANY_USER;
3595        }
3596        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3597            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3598                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3599        }
3600        return updateFlags(flags, userId);
3601    }
3602
3603    /**
3604     * Update given flags when being used to request {@link ApplicationInfo}.
3605     */
3606    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3607        return updateFlagsForPackage(flags, userId, cookie);
3608    }
3609
3610    /**
3611     * Update given flags when being used to request {@link ComponentInfo}.
3612     */
3613    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3614        if (cookie instanceof Intent) {
3615            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3616                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3617            }
3618        }
3619
3620        boolean triaged = true;
3621        // Caller is asking for component details, so they'd better be
3622        // asking for specific encryption matching behavior, or be triaged
3623        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3624                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3625                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3626            triaged = false;
3627        }
3628        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3629            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3630                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3631        }
3632
3633        return updateFlags(flags, userId);
3634    }
3635
3636    /**
3637     * Update given flags when being used to request {@link ResolveInfo}.
3638     */
3639    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3640        // Safe mode means we shouldn't match any third-party components
3641        if (mSafeMode) {
3642            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3643        }
3644        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
3645        if (ephemeralPkgName != null) {
3646            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3647            flags |= PackageManager.MATCH_EPHEMERAL;
3648        }
3649
3650        return updateFlagsForComponent(flags, userId, cookie);
3651    }
3652
3653    @Override
3654    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3655        if (!sUserManager.exists(userId)) return null;
3656        flags = updateFlagsForComponent(flags, userId, component);
3657        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3658                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3659        synchronized (mPackages) {
3660            PackageParser.Activity a = mActivities.mActivities.get(component);
3661
3662            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3663            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3664                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3665                if (ps == null) return null;
3666                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3667                        userId);
3668            }
3669            if (mResolveComponentName.equals(component)) {
3670                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3671                        new PackageUserState(), userId);
3672            }
3673        }
3674        return null;
3675    }
3676
3677    @Override
3678    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3679            String resolvedType) {
3680        synchronized (mPackages) {
3681            if (component.equals(mResolveComponentName)) {
3682                // The resolver supports EVERYTHING!
3683                return true;
3684            }
3685            PackageParser.Activity a = mActivities.mActivities.get(component);
3686            if (a == null) {
3687                return false;
3688            }
3689            for (int i=0; i<a.intents.size(); i++) {
3690                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3691                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3692                    return true;
3693                }
3694            }
3695            return false;
3696        }
3697    }
3698
3699    @Override
3700    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3701        if (!sUserManager.exists(userId)) return null;
3702        flags = updateFlagsForComponent(flags, userId, component);
3703        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3704                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3705        synchronized (mPackages) {
3706            PackageParser.Activity a = mReceivers.mActivities.get(component);
3707            if (DEBUG_PACKAGE_INFO) Log.v(
3708                TAG, "getReceiverInfo " + component + ": " + a);
3709            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3710                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3711                if (ps == null) return null;
3712                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3713                        userId);
3714            }
3715        }
3716        return null;
3717    }
3718
3719    @Override
3720    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3721        if (!sUserManager.exists(userId)) return null;
3722        flags = updateFlagsForComponent(flags, userId, component);
3723        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3724                false /* requireFullPermission */, false /* checkShell */, "get service info");
3725        synchronized (mPackages) {
3726            PackageParser.Service s = mServices.mServices.get(component);
3727            if (DEBUG_PACKAGE_INFO) Log.v(
3728                TAG, "getServiceInfo " + component + ": " + s);
3729            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3730                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3731                if (ps == null) return null;
3732                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3733                        userId);
3734            }
3735        }
3736        return null;
3737    }
3738
3739    @Override
3740    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3741        if (!sUserManager.exists(userId)) return null;
3742        flags = updateFlagsForComponent(flags, userId, component);
3743        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3744                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3745        synchronized (mPackages) {
3746            PackageParser.Provider p = mProviders.mProviders.get(component);
3747            if (DEBUG_PACKAGE_INFO) Log.v(
3748                TAG, "getProviderInfo " + component + ": " + p);
3749            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3750                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3751                if (ps == null) return null;
3752                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3753                        userId);
3754            }
3755        }
3756        return null;
3757    }
3758
3759    @Override
3760    public String[] getSystemSharedLibraryNames() {
3761        Set<String> libSet;
3762        synchronized (mPackages) {
3763            libSet = mSharedLibraries.keySet();
3764            int size = libSet.size();
3765            if (size > 0) {
3766                String[] libs = new String[size];
3767                libSet.toArray(libs);
3768                return libs;
3769            }
3770        }
3771        return null;
3772    }
3773
3774    @Override
3775    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3776        synchronized (mPackages) {
3777            return mServicesSystemSharedLibraryPackageName;
3778        }
3779    }
3780
3781    @Override
3782    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3783        synchronized (mPackages) {
3784            return mSharedSystemSharedLibraryPackageName;
3785        }
3786    }
3787
3788    @Override
3789    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3790        synchronized (mPackages) {
3791            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3792
3793            final FeatureInfo fi = new FeatureInfo();
3794            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3795                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3796            res.add(fi);
3797
3798            return new ParceledListSlice<>(res);
3799        }
3800    }
3801
3802    @Override
3803    public boolean hasSystemFeature(String name, int version) {
3804        synchronized (mPackages) {
3805            final FeatureInfo feat = mAvailableFeatures.get(name);
3806            if (feat == null) {
3807                return false;
3808            } else {
3809                return feat.version >= version;
3810            }
3811        }
3812    }
3813
3814    @Override
3815    public int checkPermission(String permName, String pkgName, int userId) {
3816        if (!sUserManager.exists(userId)) {
3817            return PackageManager.PERMISSION_DENIED;
3818        }
3819
3820        synchronized (mPackages) {
3821            final PackageParser.Package p = mPackages.get(pkgName);
3822            if (p != null && p.mExtras != null) {
3823                final PackageSetting ps = (PackageSetting) p.mExtras;
3824                final PermissionsState permissionsState = ps.getPermissionsState();
3825                if (permissionsState.hasPermission(permName, userId)) {
3826                    return PackageManager.PERMISSION_GRANTED;
3827                }
3828                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3829                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3830                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3831                    return PackageManager.PERMISSION_GRANTED;
3832                }
3833            }
3834        }
3835
3836        return PackageManager.PERMISSION_DENIED;
3837    }
3838
3839    @Override
3840    public int checkUidPermission(String permName, int uid) {
3841        final int userId = UserHandle.getUserId(uid);
3842
3843        if (!sUserManager.exists(userId)) {
3844            return PackageManager.PERMISSION_DENIED;
3845        }
3846
3847        synchronized (mPackages) {
3848            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3849            if (obj != null) {
3850                final SettingBase ps = (SettingBase) obj;
3851                final PermissionsState permissionsState = ps.getPermissionsState();
3852                if (permissionsState.hasPermission(permName, userId)) {
3853                    return PackageManager.PERMISSION_GRANTED;
3854                }
3855                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3856                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3857                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3858                    return PackageManager.PERMISSION_GRANTED;
3859                }
3860            } else {
3861                ArraySet<String> perms = mSystemPermissions.get(uid);
3862                if (perms != null) {
3863                    if (perms.contains(permName)) {
3864                        return PackageManager.PERMISSION_GRANTED;
3865                    }
3866                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3867                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3868                        return PackageManager.PERMISSION_GRANTED;
3869                    }
3870                }
3871            }
3872        }
3873
3874        return PackageManager.PERMISSION_DENIED;
3875    }
3876
3877    @Override
3878    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3879        if (UserHandle.getCallingUserId() != userId) {
3880            mContext.enforceCallingPermission(
3881                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3882                    "isPermissionRevokedByPolicy for user " + userId);
3883        }
3884
3885        if (checkPermission(permission, packageName, userId)
3886                == PackageManager.PERMISSION_GRANTED) {
3887            return false;
3888        }
3889
3890        final long identity = Binder.clearCallingIdentity();
3891        try {
3892            final int flags = getPermissionFlags(permission, packageName, userId);
3893            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3894        } finally {
3895            Binder.restoreCallingIdentity(identity);
3896        }
3897    }
3898
3899    @Override
3900    public String getPermissionControllerPackageName() {
3901        synchronized (mPackages) {
3902            return mRequiredInstallerPackage;
3903        }
3904    }
3905
3906    /**
3907     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3908     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3909     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3910     * @param message the message to log on security exception
3911     */
3912    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3913            boolean checkShell, String message) {
3914        if (userId < 0) {
3915            throw new IllegalArgumentException("Invalid userId " + userId);
3916        }
3917        if (checkShell) {
3918            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3919        }
3920        if (userId == UserHandle.getUserId(callingUid)) return;
3921        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3922            if (requireFullPermission) {
3923                mContext.enforceCallingOrSelfPermission(
3924                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3925            } else {
3926                try {
3927                    mContext.enforceCallingOrSelfPermission(
3928                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3929                } catch (SecurityException se) {
3930                    mContext.enforceCallingOrSelfPermission(
3931                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3932                }
3933            }
3934        }
3935    }
3936
3937    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3938        if (callingUid == Process.SHELL_UID) {
3939            if (userHandle >= 0
3940                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3941                throw new SecurityException("Shell does not have permission to access user "
3942                        + userHandle);
3943            } else if (userHandle < 0) {
3944                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3945                        + Debug.getCallers(3));
3946            }
3947        }
3948    }
3949
3950    private BasePermission findPermissionTreeLP(String permName) {
3951        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3952            if (permName.startsWith(bp.name) &&
3953                    permName.length() > bp.name.length() &&
3954                    permName.charAt(bp.name.length()) == '.') {
3955                return bp;
3956            }
3957        }
3958        return null;
3959    }
3960
3961    private BasePermission checkPermissionTreeLP(String permName) {
3962        if (permName != null) {
3963            BasePermission bp = findPermissionTreeLP(permName);
3964            if (bp != null) {
3965                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3966                    return bp;
3967                }
3968                throw new SecurityException("Calling uid "
3969                        + Binder.getCallingUid()
3970                        + " is not allowed to add to permission tree "
3971                        + bp.name + " owned by uid " + bp.uid);
3972            }
3973        }
3974        throw new SecurityException("No permission tree found for " + permName);
3975    }
3976
3977    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3978        if (s1 == null) {
3979            return s2 == null;
3980        }
3981        if (s2 == null) {
3982            return false;
3983        }
3984        if (s1.getClass() != s2.getClass()) {
3985            return false;
3986        }
3987        return s1.equals(s2);
3988    }
3989
3990    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3991        if (pi1.icon != pi2.icon) return false;
3992        if (pi1.logo != pi2.logo) return false;
3993        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3994        if (!compareStrings(pi1.name, pi2.name)) return false;
3995        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3996        // We'll take care of setting this one.
3997        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3998        // These are not currently stored in settings.
3999        //if (!compareStrings(pi1.group, pi2.group)) return false;
4000        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4001        //if (pi1.labelRes != pi2.labelRes) return false;
4002        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4003        return true;
4004    }
4005
4006    int permissionInfoFootprint(PermissionInfo info) {
4007        int size = info.name.length();
4008        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4009        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4010        return size;
4011    }
4012
4013    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4014        int size = 0;
4015        for (BasePermission perm : mSettings.mPermissions.values()) {
4016            if (perm.uid == tree.uid) {
4017                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4018            }
4019        }
4020        return size;
4021    }
4022
4023    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4024        // We calculate the max size of permissions defined by this uid and throw
4025        // if that plus the size of 'info' would exceed our stated maximum.
4026        if (tree.uid != Process.SYSTEM_UID) {
4027            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4028            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4029                throw new SecurityException("Permission tree size cap exceeded");
4030            }
4031        }
4032    }
4033
4034    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4035        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4036            throw new SecurityException("Label must be specified in permission");
4037        }
4038        BasePermission tree = checkPermissionTreeLP(info.name);
4039        BasePermission bp = mSettings.mPermissions.get(info.name);
4040        boolean added = bp == null;
4041        boolean changed = true;
4042        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4043        if (added) {
4044            enforcePermissionCapLocked(info, tree);
4045            bp = new BasePermission(info.name, tree.sourcePackage,
4046                    BasePermission.TYPE_DYNAMIC);
4047        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4048            throw new SecurityException(
4049                    "Not allowed to modify non-dynamic permission "
4050                    + info.name);
4051        } else {
4052            if (bp.protectionLevel == fixedLevel
4053                    && bp.perm.owner.equals(tree.perm.owner)
4054                    && bp.uid == tree.uid
4055                    && comparePermissionInfos(bp.perm.info, info)) {
4056                changed = false;
4057            }
4058        }
4059        bp.protectionLevel = fixedLevel;
4060        info = new PermissionInfo(info);
4061        info.protectionLevel = fixedLevel;
4062        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4063        bp.perm.info.packageName = tree.perm.info.packageName;
4064        bp.uid = tree.uid;
4065        if (added) {
4066            mSettings.mPermissions.put(info.name, bp);
4067        }
4068        if (changed) {
4069            if (!async) {
4070                mSettings.writeLPr();
4071            } else {
4072                scheduleWriteSettingsLocked();
4073            }
4074        }
4075        return added;
4076    }
4077
4078    @Override
4079    public boolean addPermission(PermissionInfo info) {
4080        synchronized (mPackages) {
4081            return addPermissionLocked(info, false);
4082        }
4083    }
4084
4085    @Override
4086    public boolean addPermissionAsync(PermissionInfo info) {
4087        synchronized (mPackages) {
4088            return addPermissionLocked(info, true);
4089        }
4090    }
4091
4092    @Override
4093    public void removePermission(String name) {
4094        synchronized (mPackages) {
4095            checkPermissionTreeLP(name);
4096            BasePermission bp = mSettings.mPermissions.get(name);
4097            if (bp != null) {
4098                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4099                    throw new SecurityException(
4100                            "Not allowed to modify non-dynamic permission "
4101                            + name);
4102                }
4103                mSettings.mPermissions.remove(name);
4104                mSettings.writeLPr();
4105            }
4106        }
4107    }
4108
4109    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4110            BasePermission bp) {
4111        int index = pkg.requestedPermissions.indexOf(bp.name);
4112        if (index == -1) {
4113            throw new SecurityException("Package " + pkg.packageName
4114                    + " has not requested permission " + bp.name);
4115        }
4116        if (!bp.isRuntime() && !bp.isDevelopment()) {
4117            throw new SecurityException("Permission " + bp.name
4118                    + " is not a changeable permission type");
4119        }
4120    }
4121
4122    @Override
4123    public void grantRuntimePermission(String packageName, String name, final int userId) {
4124        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4125    }
4126
4127    private void grantRuntimePermission(String packageName, String name, final int userId,
4128            boolean overridePolicy) {
4129        if (!sUserManager.exists(userId)) {
4130            Log.e(TAG, "No such user:" + userId);
4131            return;
4132        }
4133
4134        mContext.enforceCallingOrSelfPermission(
4135                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4136                "grantRuntimePermission");
4137
4138        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4139                true /* requireFullPermission */, true /* checkShell */,
4140                "grantRuntimePermission");
4141
4142        final int uid;
4143        final SettingBase sb;
4144
4145        synchronized (mPackages) {
4146            final PackageParser.Package pkg = mPackages.get(packageName);
4147            if (pkg == null) {
4148                throw new IllegalArgumentException("Unknown package: " + packageName);
4149            }
4150
4151            final BasePermission bp = mSettings.mPermissions.get(name);
4152            if (bp == null) {
4153                throw new IllegalArgumentException("Unknown permission: " + name);
4154            }
4155
4156            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4157
4158            // If a permission review is required for legacy apps we represent
4159            // their permissions as always granted runtime ones since we need
4160            // to keep the review required permission flag per user while an
4161            // install permission's state is shared across all users.
4162            if (mPermissionReviewRequired
4163                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4164                    && bp.isRuntime()) {
4165                return;
4166            }
4167
4168            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4169            sb = (SettingBase) pkg.mExtras;
4170            if (sb == null) {
4171                throw new IllegalArgumentException("Unknown package: " + packageName);
4172            }
4173
4174            final PermissionsState permissionsState = sb.getPermissionsState();
4175
4176            final int flags = permissionsState.getPermissionFlags(name, userId);
4177            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4178                throw new SecurityException("Cannot grant system fixed permission "
4179                        + name + " for package " + packageName);
4180            }
4181            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4182                throw new SecurityException("Cannot grant policy fixed permission "
4183                        + name + " for package " + packageName);
4184            }
4185
4186            if (bp.isDevelopment()) {
4187                // Development permissions must be handled specially, since they are not
4188                // normal runtime permissions.  For now they apply to all users.
4189                if (permissionsState.grantInstallPermission(bp) !=
4190                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4191                    scheduleWriteSettingsLocked();
4192                }
4193                return;
4194            }
4195
4196            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
4197                throw new SecurityException("Cannot grant non-ephemeral permission"
4198                        + name + " for package " + packageName);
4199            }
4200
4201            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4202                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4203                return;
4204            }
4205
4206            final int result = permissionsState.grantRuntimePermission(bp, userId);
4207            switch (result) {
4208                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4209                    return;
4210                }
4211
4212                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4213                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4214                    mHandler.post(new Runnable() {
4215                        @Override
4216                        public void run() {
4217                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4218                        }
4219                    });
4220                }
4221                break;
4222            }
4223
4224            if (bp.isRuntime()) {
4225                logPermissionGranted(mContext, name, packageName);
4226            }
4227
4228            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4229
4230            // Not critical if that is lost - app has to request again.
4231            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4232        }
4233
4234        // Only need to do this if user is initialized. Otherwise it's a new user
4235        // and there are no processes running as the user yet and there's no need
4236        // to make an expensive call to remount processes for the changed permissions.
4237        if (READ_EXTERNAL_STORAGE.equals(name)
4238                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4239            final long token = Binder.clearCallingIdentity();
4240            try {
4241                if (sUserManager.isInitialized(userId)) {
4242                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4243                            StorageManagerInternal.class);
4244                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4245                }
4246            } finally {
4247                Binder.restoreCallingIdentity(token);
4248            }
4249        }
4250    }
4251
4252    @Override
4253    public void revokeRuntimePermission(String packageName, String name, int userId) {
4254        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4255    }
4256
4257    private void revokeRuntimePermission(String packageName, String name, int userId,
4258            boolean overridePolicy) {
4259        if (!sUserManager.exists(userId)) {
4260            Log.e(TAG, "No such user:" + userId);
4261            return;
4262        }
4263
4264        mContext.enforceCallingOrSelfPermission(
4265                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4266                "revokeRuntimePermission");
4267
4268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4269                true /* requireFullPermission */, true /* checkShell */,
4270                "revokeRuntimePermission");
4271
4272        final int appId;
4273
4274        synchronized (mPackages) {
4275            final PackageParser.Package pkg = mPackages.get(packageName);
4276            if (pkg == null) {
4277                throw new IllegalArgumentException("Unknown package: " + packageName);
4278            }
4279
4280            final BasePermission bp = mSettings.mPermissions.get(name);
4281            if (bp == null) {
4282                throw new IllegalArgumentException("Unknown permission: " + name);
4283            }
4284
4285            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4286
4287            // If a permission review is required for legacy apps we represent
4288            // their permissions as always granted runtime ones since we need
4289            // to keep the review required permission flag per user while an
4290            // install permission's state is shared across all users.
4291            if (mPermissionReviewRequired
4292                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4293                    && bp.isRuntime()) {
4294                return;
4295            }
4296
4297            SettingBase sb = (SettingBase) pkg.mExtras;
4298            if (sb == null) {
4299                throw new IllegalArgumentException("Unknown package: " + packageName);
4300            }
4301
4302            final PermissionsState permissionsState = sb.getPermissionsState();
4303
4304            final int flags = permissionsState.getPermissionFlags(name, userId);
4305            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4306                throw new SecurityException("Cannot revoke system fixed permission "
4307                        + name + " for package " + packageName);
4308            }
4309            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4310                throw new SecurityException("Cannot revoke policy fixed permission "
4311                        + name + " for package " + packageName);
4312            }
4313
4314            if (bp.isDevelopment()) {
4315                // Development permissions must be handled specially, since they are not
4316                // normal runtime permissions.  For now they apply to all users.
4317                if (permissionsState.revokeInstallPermission(bp) !=
4318                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4319                    scheduleWriteSettingsLocked();
4320                }
4321                return;
4322            }
4323
4324            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4325                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4326                return;
4327            }
4328
4329            if (bp.isRuntime()) {
4330                logPermissionRevoked(mContext, name, packageName);
4331            }
4332
4333            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4334
4335            // Critical, after this call app should never have the permission.
4336            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4337
4338            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4339        }
4340
4341        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4342    }
4343
4344    /**
4345     * Get the first event id for the permission.
4346     *
4347     * <p>There are four events for each permission: <ul>
4348     *     <li>Request permission: first id + 0</li>
4349     *     <li>Grant permission: first id + 1</li>
4350     *     <li>Request for permission denied: first id + 2</li>
4351     *     <li>Revoke permission: first id + 3</li>
4352     * </ul></p>
4353     *
4354     * @param name name of the permission
4355     *
4356     * @return The first event id for the permission
4357     */
4358    private static int getBaseEventId(@NonNull String name) {
4359        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4360
4361        if (eventIdIndex == -1) {
4362            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4363                    || "user".equals(Build.TYPE)) {
4364                Log.i(TAG, "Unknown permission " + name);
4365
4366                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4367            } else {
4368                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4369                //
4370                // Also update
4371                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4372                // - metrics_constants.proto
4373                throw new IllegalStateException("Unknown permission " + name);
4374            }
4375        }
4376
4377        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4378    }
4379
4380    /**
4381     * Log that a permission was revoked.
4382     *
4383     * @param context Context of the caller
4384     * @param name name of the permission
4385     * @param packageName package permission if for
4386     */
4387    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4388            @NonNull String packageName) {
4389        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4390    }
4391
4392    /**
4393     * Log that a permission request was granted.
4394     *
4395     * @param context Context of the caller
4396     * @param name name of the permission
4397     * @param packageName package permission if for
4398     */
4399    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4400            @NonNull String packageName) {
4401        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4402    }
4403
4404    @Override
4405    public void resetRuntimePermissions() {
4406        mContext.enforceCallingOrSelfPermission(
4407                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4408                "revokeRuntimePermission");
4409
4410        int callingUid = Binder.getCallingUid();
4411        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4412            mContext.enforceCallingOrSelfPermission(
4413                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4414                    "resetRuntimePermissions");
4415        }
4416
4417        synchronized (mPackages) {
4418            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4419            for (int userId : UserManagerService.getInstance().getUserIds()) {
4420                final int packageCount = mPackages.size();
4421                for (int i = 0; i < packageCount; i++) {
4422                    PackageParser.Package pkg = mPackages.valueAt(i);
4423                    if (!(pkg.mExtras instanceof PackageSetting)) {
4424                        continue;
4425                    }
4426                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4427                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4428                }
4429            }
4430        }
4431    }
4432
4433    @Override
4434    public int getPermissionFlags(String name, String packageName, int userId) {
4435        if (!sUserManager.exists(userId)) {
4436            return 0;
4437        }
4438
4439        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4440
4441        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4442                true /* requireFullPermission */, false /* checkShell */,
4443                "getPermissionFlags");
4444
4445        synchronized (mPackages) {
4446            final PackageParser.Package pkg = mPackages.get(packageName);
4447            if (pkg == null) {
4448                return 0;
4449            }
4450
4451            final BasePermission bp = mSettings.mPermissions.get(name);
4452            if (bp == null) {
4453                return 0;
4454            }
4455
4456            SettingBase sb = (SettingBase) pkg.mExtras;
4457            if (sb == null) {
4458                return 0;
4459            }
4460
4461            PermissionsState permissionsState = sb.getPermissionsState();
4462            return permissionsState.getPermissionFlags(name, userId);
4463        }
4464    }
4465
4466    @Override
4467    public void updatePermissionFlags(String name, String packageName, int flagMask,
4468            int flagValues, int userId) {
4469        if (!sUserManager.exists(userId)) {
4470            return;
4471        }
4472
4473        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4474
4475        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4476                true /* requireFullPermission */, true /* checkShell */,
4477                "updatePermissionFlags");
4478
4479        // Only the system can change these flags and nothing else.
4480        if (getCallingUid() != Process.SYSTEM_UID) {
4481            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4482            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4483            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4484            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4485            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4486        }
4487
4488        synchronized (mPackages) {
4489            final PackageParser.Package pkg = mPackages.get(packageName);
4490            if (pkg == null) {
4491                throw new IllegalArgumentException("Unknown package: " + packageName);
4492            }
4493
4494            final BasePermission bp = mSettings.mPermissions.get(name);
4495            if (bp == null) {
4496                throw new IllegalArgumentException("Unknown permission: " + name);
4497            }
4498
4499            SettingBase sb = (SettingBase) pkg.mExtras;
4500            if (sb == null) {
4501                throw new IllegalArgumentException("Unknown package: " + packageName);
4502            }
4503
4504            PermissionsState permissionsState = sb.getPermissionsState();
4505
4506            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4507
4508            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4509                // Install and runtime permissions are stored in different places,
4510                // so figure out what permission changed and persist the change.
4511                if (permissionsState.getInstallPermissionState(name) != null) {
4512                    scheduleWriteSettingsLocked();
4513                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4514                        || hadState) {
4515                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4516                }
4517            }
4518        }
4519    }
4520
4521    /**
4522     * Update the permission flags for all packages and runtime permissions of a user in order
4523     * to allow device or profile owner to remove POLICY_FIXED.
4524     */
4525    @Override
4526    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4527        if (!sUserManager.exists(userId)) {
4528            return;
4529        }
4530
4531        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4532
4533        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4534                true /* requireFullPermission */, true /* checkShell */,
4535                "updatePermissionFlagsForAllApps");
4536
4537        // Only the system can change system fixed flags.
4538        if (getCallingUid() != Process.SYSTEM_UID) {
4539            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4540            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4541        }
4542
4543        synchronized (mPackages) {
4544            boolean changed = false;
4545            final int packageCount = mPackages.size();
4546            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4547                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4548                SettingBase sb = (SettingBase) pkg.mExtras;
4549                if (sb == null) {
4550                    continue;
4551                }
4552                PermissionsState permissionsState = sb.getPermissionsState();
4553                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4554                        userId, flagMask, flagValues);
4555            }
4556            if (changed) {
4557                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4558            }
4559        }
4560    }
4561
4562    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4563        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4564                != PackageManager.PERMISSION_GRANTED
4565            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4566                != PackageManager.PERMISSION_GRANTED) {
4567            throw new SecurityException(message + " requires "
4568                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4569                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4570        }
4571    }
4572
4573    @Override
4574    public boolean shouldShowRequestPermissionRationale(String permissionName,
4575            String packageName, int userId) {
4576        if (UserHandle.getCallingUserId() != userId) {
4577            mContext.enforceCallingPermission(
4578                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4579                    "canShowRequestPermissionRationale for user " + userId);
4580        }
4581
4582        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4583        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4584            return false;
4585        }
4586
4587        if (checkPermission(permissionName, packageName, userId)
4588                == PackageManager.PERMISSION_GRANTED) {
4589            return false;
4590        }
4591
4592        final int flags;
4593
4594        final long identity = Binder.clearCallingIdentity();
4595        try {
4596            flags = getPermissionFlags(permissionName,
4597                    packageName, userId);
4598        } finally {
4599            Binder.restoreCallingIdentity(identity);
4600        }
4601
4602        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4603                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4604                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4605
4606        if ((flags & fixedFlags) != 0) {
4607            return false;
4608        }
4609
4610        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4611    }
4612
4613    @Override
4614    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4615        mContext.enforceCallingOrSelfPermission(
4616                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4617                "addOnPermissionsChangeListener");
4618
4619        synchronized (mPackages) {
4620            mOnPermissionChangeListeners.addListenerLocked(listener);
4621        }
4622    }
4623
4624    @Override
4625    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4626        synchronized (mPackages) {
4627            mOnPermissionChangeListeners.removeListenerLocked(listener);
4628        }
4629    }
4630
4631    @Override
4632    public boolean isProtectedBroadcast(String actionName) {
4633        synchronized (mPackages) {
4634            if (mProtectedBroadcasts.contains(actionName)) {
4635                return true;
4636            } else if (actionName != null) {
4637                // TODO: remove these terrible hacks
4638                if (actionName.startsWith("android.net.netmon.lingerExpired")
4639                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4640                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4641                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4642                    return true;
4643                }
4644            }
4645        }
4646        return false;
4647    }
4648
4649    @Override
4650    public int checkSignatures(String pkg1, String pkg2) {
4651        synchronized (mPackages) {
4652            final PackageParser.Package p1 = mPackages.get(pkg1);
4653            final PackageParser.Package p2 = mPackages.get(pkg2);
4654            if (p1 == null || p1.mExtras == null
4655                    || p2 == null || p2.mExtras == null) {
4656                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4657            }
4658            return compareSignatures(p1.mSignatures, p2.mSignatures);
4659        }
4660    }
4661
4662    @Override
4663    public int checkUidSignatures(int uid1, int uid2) {
4664        // Map to base uids.
4665        uid1 = UserHandle.getAppId(uid1);
4666        uid2 = UserHandle.getAppId(uid2);
4667        // reader
4668        synchronized (mPackages) {
4669            Signature[] s1;
4670            Signature[] s2;
4671            Object obj = mSettings.getUserIdLPr(uid1);
4672            if (obj != null) {
4673                if (obj instanceof SharedUserSetting) {
4674                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4675                } else if (obj instanceof PackageSetting) {
4676                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4677                } else {
4678                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4679                }
4680            } else {
4681                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4682            }
4683            obj = mSettings.getUserIdLPr(uid2);
4684            if (obj != null) {
4685                if (obj instanceof SharedUserSetting) {
4686                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4687                } else if (obj instanceof PackageSetting) {
4688                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4689                } else {
4690                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4691                }
4692            } else {
4693                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4694            }
4695            return compareSignatures(s1, s2);
4696        }
4697    }
4698
4699    /**
4700     * This method should typically only be used when granting or revoking
4701     * permissions, since the app may immediately restart after this call.
4702     * <p>
4703     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4704     * guard your work against the app being relaunched.
4705     */
4706    private void killUid(int appId, int userId, String reason) {
4707        final long identity = Binder.clearCallingIdentity();
4708        try {
4709            IActivityManager am = ActivityManager.getService();
4710            if (am != null) {
4711                try {
4712                    am.killUid(appId, userId, reason);
4713                } catch (RemoteException e) {
4714                    /* ignore - same process */
4715                }
4716            }
4717        } finally {
4718            Binder.restoreCallingIdentity(identity);
4719        }
4720    }
4721
4722    /**
4723     * Compares two sets of signatures. Returns:
4724     * <br />
4725     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4726     * <br />
4727     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4728     * <br />
4729     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4730     * <br />
4731     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4732     * <br />
4733     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4734     */
4735    static int compareSignatures(Signature[] s1, Signature[] s2) {
4736        if (s1 == null) {
4737            return s2 == null
4738                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4739                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4740        }
4741
4742        if (s2 == null) {
4743            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4744        }
4745
4746        if (s1.length != s2.length) {
4747            return PackageManager.SIGNATURE_NO_MATCH;
4748        }
4749
4750        // Since both signature sets are of size 1, we can compare without HashSets.
4751        if (s1.length == 1) {
4752            return s1[0].equals(s2[0]) ?
4753                    PackageManager.SIGNATURE_MATCH :
4754                    PackageManager.SIGNATURE_NO_MATCH;
4755        }
4756
4757        ArraySet<Signature> set1 = new ArraySet<Signature>();
4758        for (Signature sig : s1) {
4759            set1.add(sig);
4760        }
4761        ArraySet<Signature> set2 = new ArraySet<Signature>();
4762        for (Signature sig : s2) {
4763            set2.add(sig);
4764        }
4765        // Make sure s2 contains all signatures in s1.
4766        if (set1.equals(set2)) {
4767            return PackageManager.SIGNATURE_MATCH;
4768        }
4769        return PackageManager.SIGNATURE_NO_MATCH;
4770    }
4771
4772    /**
4773     * If the database version for this type of package (internal storage or
4774     * external storage) is less than the version where package signatures
4775     * were updated, return true.
4776     */
4777    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4778        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4779        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4780    }
4781
4782    /**
4783     * Used for backward compatibility to make sure any packages with
4784     * certificate chains get upgraded to the new style. {@code existingSigs}
4785     * will be in the old format (since they were stored on disk from before the
4786     * system upgrade) and {@code scannedSigs} will be in the newer format.
4787     */
4788    private int compareSignaturesCompat(PackageSignatures existingSigs,
4789            PackageParser.Package scannedPkg) {
4790        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4791            return PackageManager.SIGNATURE_NO_MATCH;
4792        }
4793
4794        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4795        for (Signature sig : existingSigs.mSignatures) {
4796            existingSet.add(sig);
4797        }
4798        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4799        for (Signature sig : scannedPkg.mSignatures) {
4800            try {
4801                Signature[] chainSignatures = sig.getChainSignatures();
4802                for (Signature chainSig : chainSignatures) {
4803                    scannedCompatSet.add(chainSig);
4804                }
4805            } catch (CertificateEncodingException e) {
4806                scannedCompatSet.add(sig);
4807            }
4808        }
4809        /*
4810         * Make sure the expanded scanned set contains all signatures in the
4811         * existing one.
4812         */
4813        if (scannedCompatSet.equals(existingSet)) {
4814            // Migrate the old signatures to the new scheme.
4815            existingSigs.assignSignatures(scannedPkg.mSignatures);
4816            // The new KeySets will be re-added later in the scanning process.
4817            synchronized (mPackages) {
4818                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4819            }
4820            return PackageManager.SIGNATURE_MATCH;
4821        }
4822        return PackageManager.SIGNATURE_NO_MATCH;
4823    }
4824
4825    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4826        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4827        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4828    }
4829
4830    private int compareSignaturesRecover(PackageSignatures existingSigs,
4831            PackageParser.Package scannedPkg) {
4832        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4833            return PackageManager.SIGNATURE_NO_MATCH;
4834        }
4835
4836        String msg = null;
4837        try {
4838            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4839                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4840                        + scannedPkg.packageName);
4841                return PackageManager.SIGNATURE_MATCH;
4842            }
4843        } catch (CertificateException e) {
4844            msg = e.getMessage();
4845        }
4846
4847        logCriticalInfo(Log.INFO,
4848                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4849        return PackageManager.SIGNATURE_NO_MATCH;
4850    }
4851
4852    @Override
4853    public List<String> getAllPackages() {
4854        synchronized (mPackages) {
4855            return new ArrayList<String>(mPackages.keySet());
4856        }
4857    }
4858
4859    @Override
4860    public String[] getPackagesForUid(int uid) {
4861        final int userId = UserHandle.getUserId(uid);
4862        uid = UserHandle.getAppId(uid);
4863        // reader
4864        synchronized (mPackages) {
4865            Object obj = mSettings.getUserIdLPr(uid);
4866            if (obj instanceof SharedUserSetting) {
4867                final SharedUserSetting sus = (SharedUserSetting) obj;
4868                final int N = sus.packages.size();
4869                String[] res = new String[N];
4870                final Iterator<PackageSetting> it = sus.packages.iterator();
4871                int i = 0;
4872                while (it.hasNext()) {
4873                    PackageSetting ps = it.next();
4874                    if (ps.getInstalled(userId)) {
4875                        res[i++] = ps.name;
4876                    } else {
4877                        res = ArrayUtils.removeElement(String.class, res, res[i]);
4878                    }
4879                }
4880                return res;
4881            } else if (obj instanceof PackageSetting) {
4882                final PackageSetting ps = (PackageSetting) obj;
4883                return new String[] { ps.name };
4884            }
4885        }
4886        return null;
4887    }
4888
4889    @Override
4890    public String getNameForUid(int uid) {
4891        // reader
4892        synchronized (mPackages) {
4893            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4894            if (obj instanceof SharedUserSetting) {
4895                final SharedUserSetting sus = (SharedUserSetting) obj;
4896                return sus.name + ":" + sus.userId;
4897            } else if (obj instanceof PackageSetting) {
4898                final PackageSetting ps = (PackageSetting) obj;
4899                return ps.name;
4900            }
4901        }
4902        return null;
4903    }
4904
4905    @Override
4906    public int getUidForSharedUser(String sharedUserName) {
4907        if(sharedUserName == null) {
4908            return -1;
4909        }
4910        // reader
4911        synchronized (mPackages) {
4912            SharedUserSetting suid;
4913            try {
4914                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4915                if (suid != null) {
4916                    return suid.userId;
4917                }
4918            } catch (PackageManagerException ignore) {
4919                // can't happen, but, still need to catch it
4920            }
4921            return -1;
4922        }
4923    }
4924
4925    @Override
4926    public int getFlagsForUid(int uid) {
4927        synchronized (mPackages) {
4928            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4929            if (obj instanceof SharedUserSetting) {
4930                final SharedUserSetting sus = (SharedUserSetting) obj;
4931                return sus.pkgFlags;
4932            } else if (obj instanceof PackageSetting) {
4933                final PackageSetting ps = (PackageSetting) obj;
4934                return ps.pkgFlags;
4935            }
4936        }
4937        return 0;
4938    }
4939
4940    @Override
4941    public int getPrivateFlagsForUid(int uid) {
4942        synchronized (mPackages) {
4943            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4944            if (obj instanceof SharedUserSetting) {
4945                final SharedUserSetting sus = (SharedUserSetting) obj;
4946                return sus.pkgPrivateFlags;
4947            } else if (obj instanceof PackageSetting) {
4948                final PackageSetting ps = (PackageSetting) obj;
4949                return ps.pkgPrivateFlags;
4950            }
4951        }
4952        return 0;
4953    }
4954
4955    @Override
4956    public boolean isUidPrivileged(int uid) {
4957        uid = UserHandle.getAppId(uid);
4958        // reader
4959        synchronized (mPackages) {
4960            Object obj = mSettings.getUserIdLPr(uid);
4961            if (obj instanceof SharedUserSetting) {
4962                final SharedUserSetting sus = (SharedUserSetting) obj;
4963                final Iterator<PackageSetting> it = sus.packages.iterator();
4964                while (it.hasNext()) {
4965                    if (it.next().isPrivileged()) {
4966                        return true;
4967                    }
4968                }
4969            } else if (obj instanceof PackageSetting) {
4970                final PackageSetting ps = (PackageSetting) obj;
4971                return ps.isPrivileged();
4972            }
4973        }
4974        return false;
4975    }
4976
4977    @Override
4978    public String[] getAppOpPermissionPackages(String permissionName) {
4979        synchronized (mPackages) {
4980            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4981            if (pkgs == null) {
4982                return null;
4983            }
4984            return pkgs.toArray(new String[pkgs.size()]);
4985        }
4986    }
4987
4988    @Override
4989    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4990            int flags, int userId) {
4991        try {
4992            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4993
4994            if (!sUserManager.exists(userId)) return null;
4995            flags = updateFlagsForResolve(flags, userId, intent);
4996            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4997                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4998
4999            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5000            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5001                    flags, userId);
5002            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5003
5004            final ResolveInfo bestChoice =
5005                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5006            return bestChoice;
5007        } finally {
5008            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5009        }
5010    }
5011
5012    @Override
5013    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5014            IntentFilter filter, int match, ComponentName activity) {
5015        final int userId = UserHandle.getCallingUserId();
5016        if (DEBUG_PREFERRED) {
5017            Log.v(TAG, "setLastChosenActivity intent=" + intent
5018                + " resolvedType=" + resolvedType
5019                + " flags=" + flags
5020                + " filter=" + filter
5021                + " match=" + match
5022                + " activity=" + activity);
5023            filter.dump(new PrintStreamPrinter(System.out), "    ");
5024        }
5025        intent.setComponent(null);
5026        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5027                userId);
5028        // Find any earlier preferred or last chosen entries and nuke them
5029        findPreferredActivity(intent, resolvedType,
5030                flags, query, 0, false, true, false, userId);
5031        // Add the new activity as the last chosen for this filter
5032        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5033                "Setting last chosen");
5034    }
5035
5036    @Override
5037    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5038        final int userId = UserHandle.getCallingUserId();
5039        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5040        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5041                userId);
5042        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5043                false, false, false, userId);
5044    }
5045
5046    private boolean isEphemeralDisabled() {
5047        // ephemeral apps have been disabled across the board
5048        if (DISABLE_EPHEMERAL_APPS) {
5049            return true;
5050        }
5051        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5052        if (!mSystemReady) {
5053            return true;
5054        }
5055        // we can't get a content resolver until the system is ready; these checks must happen last
5056        final ContentResolver resolver = mContext.getContentResolver();
5057        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5058            return true;
5059        }
5060        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5061    }
5062
5063    private boolean isEphemeralAllowed(
5064            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5065            boolean skipPackageCheck) {
5066        // Short circuit and return early if possible.
5067        if (isEphemeralDisabled()) {
5068            return false;
5069        }
5070        final int callingUser = UserHandle.getCallingUserId();
5071        if (callingUser != UserHandle.USER_SYSTEM) {
5072            return false;
5073        }
5074        if (mEphemeralResolverConnection == null) {
5075            return false;
5076        }
5077        if (mEphemeralInstallerComponent == null) {
5078            return false;
5079        }
5080        if (intent.getComponent() != null) {
5081            return false;
5082        }
5083        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5084            return false;
5085        }
5086        if (!skipPackageCheck && intent.getPackage() != null) {
5087            return false;
5088        }
5089        final boolean isWebUri = hasWebURI(intent);
5090        if (!isWebUri || intent.getData().getHost() == null) {
5091            return false;
5092        }
5093        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5094        synchronized (mPackages) {
5095            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5096            for (int n = 0; n < count; n++) {
5097                ResolveInfo info = resolvedActivities.get(n);
5098                String packageName = info.activityInfo.packageName;
5099                PackageSetting ps = mSettings.mPackages.get(packageName);
5100                if (ps != null) {
5101                    // Try to get the status from User settings first
5102                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5103                    int status = (int) (packedStatus >> 32);
5104                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5105                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5106                        if (DEBUG_EPHEMERAL) {
5107                            Slog.v(TAG, "DENY ephemeral apps;"
5108                                + " pkg: " + packageName + ", status: " + status);
5109                        }
5110                        return false;
5111                    }
5112                }
5113            }
5114        }
5115        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5116        return true;
5117    }
5118
5119    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5120            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5121            int userId) {
5122        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5123                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5124                        callingPackage, userId));
5125        mHandler.sendMessage(msg);
5126    }
5127
5128    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5129            int flags, List<ResolveInfo> query, int userId) {
5130        if (query != null) {
5131            final int N = query.size();
5132            if (N == 1) {
5133                return query.get(0);
5134            } else if (N > 1) {
5135                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5136                // If there is more than one activity with the same priority,
5137                // then let the user decide between them.
5138                ResolveInfo r0 = query.get(0);
5139                ResolveInfo r1 = query.get(1);
5140                if (DEBUG_INTENT_MATCHING || debug) {
5141                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5142                            + r1.activityInfo.name + "=" + r1.priority);
5143                }
5144                // If the first activity has a higher priority, or a different
5145                // default, then it is always desirable to pick it.
5146                if (r0.priority != r1.priority
5147                        || r0.preferredOrder != r1.preferredOrder
5148                        || r0.isDefault != r1.isDefault) {
5149                    return query.get(0);
5150                }
5151                // If we have saved a preference for a preferred activity for
5152                // this Intent, use that.
5153                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5154                        flags, query, r0.priority, true, false, debug, userId);
5155                if (ri != null) {
5156                    return ri;
5157                }
5158                ri = new ResolveInfo(mResolveInfo);
5159                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5160                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5161                // If all of the options come from the same package, show the application's
5162                // label and icon instead of the generic resolver's.
5163                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5164                // and then throw away the ResolveInfo itself, meaning that the caller loses
5165                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5166                // a fallback for this case; we only set the target package's resources on
5167                // the ResolveInfo, not the ActivityInfo.
5168                final String intentPackage = intent.getPackage();
5169                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5170                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5171                    ri.resolvePackageName = intentPackage;
5172                    if (userNeedsBadging(userId)) {
5173                        ri.noResourceId = true;
5174                    } else {
5175                        ri.icon = appi.icon;
5176                    }
5177                    ri.iconResourceId = appi.icon;
5178                    ri.labelRes = appi.labelRes;
5179                }
5180                ri.activityInfo.applicationInfo = new ApplicationInfo(
5181                        ri.activityInfo.applicationInfo);
5182                if (userId != 0) {
5183                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5184                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5185                }
5186                // Make sure that the resolver is displayable in car mode
5187                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5188                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5189                return ri;
5190            }
5191        }
5192        return null;
5193    }
5194
5195    /**
5196     * Return true if the given list is not empty and all of its contents have
5197     * an activityInfo with the given package name.
5198     */
5199    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5200        if (ArrayUtils.isEmpty(list)) {
5201            return false;
5202        }
5203        for (int i = 0, N = list.size(); i < N; i++) {
5204            final ResolveInfo ri = list.get(i);
5205            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5206            if (ai == null || !packageName.equals(ai.packageName)) {
5207                return false;
5208            }
5209        }
5210        return true;
5211    }
5212
5213    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5214            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5215        final int N = query.size();
5216        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5217                .get(userId);
5218        // Get the list of persistent preferred activities that handle the intent
5219        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5220        List<PersistentPreferredActivity> pprefs = ppir != null
5221                ? ppir.queryIntent(intent, resolvedType,
5222                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5223                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5224                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5225                : null;
5226        if (pprefs != null && pprefs.size() > 0) {
5227            final int M = pprefs.size();
5228            for (int i=0; i<M; i++) {
5229                final PersistentPreferredActivity ppa = pprefs.get(i);
5230                if (DEBUG_PREFERRED || debug) {
5231                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5232                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5233                            + "\n  component=" + ppa.mComponent);
5234                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5235                }
5236                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5237                        flags | MATCH_DISABLED_COMPONENTS, userId);
5238                if (DEBUG_PREFERRED || debug) {
5239                    Slog.v(TAG, "Found persistent preferred activity:");
5240                    if (ai != null) {
5241                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5242                    } else {
5243                        Slog.v(TAG, "  null");
5244                    }
5245                }
5246                if (ai == null) {
5247                    // This previously registered persistent preferred activity
5248                    // component is no longer known. Ignore it and do NOT remove it.
5249                    continue;
5250                }
5251                for (int j=0; j<N; j++) {
5252                    final ResolveInfo ri = query.get(j);
5253                    if (!ri.activityInfo.applicationInfo.packageName
5254                            .equals(ai.applicationInfo.packageName)) {
5255                        continue;
5256                    }
5257                    if (!ri.activityInfo.name.equals(ai.name)) {
5258                        continue;
5259                    }
5260                    //  Found a persistent preference that can handle the intent.
5261                    if (DEBUG_PREFERRED || debug) {
5262                        Slog.v(TAG, "Returning persistent preferred activity: " +
5263                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5264                    }
5265                    return ri;
5266                }
5267            }
5268        }
5269        return null;
5270    }
5271
5272    // TODO: handle preferred activities missing while user has amnesia
5273    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5274            List<ResolveInfo> query, int priority, boolean always,
5275            boolean removeMatches, boolean debug, int userId) {
5276        if (!sUserManager.exists(userId)) return null;
5277        flags = updateFlagsForResolve(flags, userId, intent);
5278        // writer
5279        synchronized (mPackages) {
5280            if (intent.getSelector() != null) {
5281                intent = intent.getSelector();
5282            }
5283            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5284
5285            // Try to find a matching persistent preferred activity.
5286            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5287                    debug, userId);
5288
5289            // If a persistent preferred activity matched, use it.
5290            if (pri != null) {
5291                return pri;
5292            }
5293
5294            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5295            // Get the list of preferred activities that handle the intent
5296            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5297            List<PreferredActivity> prefs = pir != null
5298                    ? pir.queryIntent(intent, resolvedType,
5299                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5300                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5301                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5302                    : null;
5303            if (prefs != null && prefs.size() > 0) {
5304                boolean changed = false;
5305                try {
5306                    // First figure out how good the original match set is.
5307                    // We will only allow preferred activities that came
5308                    // from the same match quality.
5309                    int match = 0;
5310
5311                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5312
5313                    final int N = query.size();
5314                    for (int j=0; j<N; j++) {
5315                        final ResolveInfo ri = query.get(j);
5316                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5317                                + ": 0x" + Integer.toHexString(match));
5318                        if (ri.match > match) {
5319                            match = ri.match;
5320                        }
5321                    }
5322
5323                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5324                            + Integer.toHexString(match));
5325
5326                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5327                    final int M = prefs.size();
5328                    for (int i=0; i<M; i++) {
5329                        final PreferredActivity pa = prefs.get(i);
5330                        if (DEBUG_PREFERRED || debug) {
5331                            Slog.v(TAG, "Checking PreferredActivity ds="
5332                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5333                                    + "\n  component=" + pa.mPref.mComponent);
5334                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5335                        }
5336                        if (pa.mPref.mMatch != match) {
5337                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5338                                    + Integer.toHexString(pa.mPref.mMatch));
5339                            continue;
5340                        }
5341                        // If it's not an "always" type preferred activity and that's what we're
5342                        // looking for, skip it.
5343                        if (always && !pa.mPref.mAlways) {
5344                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5345                            continue;
5346                        }
5347                        final ActivityInfo ai = getActivityInfo(
5348                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5349                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5350                                userId);
5351                        if (DEBUG_PREFERRED || debug) {
5352                            Slog.v(TAG, "Found preferred activity:");
5353                            if (ai != null) {
5354                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5355                            } else {
5356                                Slog.v(TAG, "  null");
5357                            }
5358                        }
5359                        if (ai == null) {
5360                            // This previously registered preferred activity
5361                            // component is no longer known.  Most likely an update
5362                            // to the app was installed and in the new version this
5363                            // component no longer exists.  Clean it up by removing
5364                            // it from the preferred activities list, and skip it.
5365                            Slog.w(TAG, "Removing dangling preferred activity: "
5366                                    + pa.mPref.mComponent);
5367                            pir.removeFilter(pa);
5368                            changed = true;
5369                            continue;
5370                        }
5371                        for (int j=0; j<N; j++) {
5372                            final ResolveInfo ri = query.get(j);
5373                            if (!ri.activityInfo.applicationInfo.packageName
5374                                    .equals(ai.applicationInfo.packageName)) {
5375                                continue;
5376                            }
5377                            if (!ri.activityInfo.name.equals(ai.name)) {
5378                                continue;
5379                            }
5380
5381                            if (removeMatches) {
5382                                pir.removeFilter(pa);
5383                                changed = true;
5384                                if (DEBUG_PREFERRED) {
5385                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5386                                }
5387                                break;
5388                            }
5389
5390                            // Okay we found a previously set preferred or last chosen app.
5391                            // If the result set is different from when this
5392                            // was created, we need to clear it and re-ask the
5393                            // user their preference, if we're looking for an "always" type entry.
5394                            if (always && !pa.mPref.sameSet(query)) {
5395                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5396                                        + intent + " type " + resolvedType);
5397                                if (DEBUG_PREFERRED) {
5398                                    Slog.v(TAG, "Removing preferred activity since set changed "
5399                                            + pa.mPref.mComponent);
5400                                }
5401                                pir.removeFilter(pa);
5402                                // Re-add the filter as a "last chosen" entry (!always)
5403                                PreferredActivity lastChosen = new PreferredActivity(
5404                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5405                                pir.addFilter(lastChosen);
5406                                changed = true;
5407                                return null;
5408                            }
5409
5410                            // Yay! Either the set matched or we're looking for the last chosen
5411                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5412                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5413                            return ri;
5414                        }
5415                    }
5416                } finally {
5417                    if (changed) {
5418                        if (DEBUG_PREFERRED) {
5419                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5420                        }
5421                        scheduleWritePackageRestrictionsLocked(userId);
5422                    }
5423                }
5424            }
5425        }
5426        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5427        return null;
5428    }
5429
5430    /*
5431     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5432     */
5433    @Override
5434    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5435            int targetUserId) {
5436        mContext.enforceCallingOrSelfPermission(
5437                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5438        List<CrossProfileIntentFilter> matches =
5439                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5440        if (matches != null) {
5441            int size = matches.size();
5442            for (int i = 0; i < size; i++) {
5443                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5444            }
5445        }
5446        if (hasWebURI(intent)) {
5447            // cross-profile app linking works only towards the parent.
5448            final UserInfo parent = getProfileParent(sourceUserId);
5449            synchronized(mPackages) {
5450                int flags = updateFlagsForResolve(0, parent.id, intent);
5451                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5452                        intent, resolvedType, flags, sourceUserId, parent.id);
5453                return xpDomainInfo != null;
5454            }
5455        }
5456        return false;
5457    }
5458
5459    private UserInfo getProfileParent(int userId) {
5460        final long identity = Binder.clearCallingIdentity();
5461        try {
5462            return sUserManager.getProfileParent(userId);
5463        } finally {
5464            Binder.restoreCallingIdentity(identity);
5465        }
5466    }
5467
5468    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5469            String resolvedType, int userId) {
5470        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5471        if (resolver != null) {
5472            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5473                    false /*visibleToEphemeral*/, false /*isEphemeral*/, userId);
5474        }
5475        return null;
5476    }
5477
5478    @Override
5479    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5480            String resolvedType, int flags, int userId) {
5481        try {
5482            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5483
5484            return new ParceledListSlice<>(
5485                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5486        } finally {
5487            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5488        }
5489    }
5490
5491    /**
5492     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5493     * ephemeral, returns {@code null}.
5494     */
5495    private String getEphemeralPackageName(int callingUid) {
5496        final int appId = UserHandle.getAppId(callingUid);
5497        synchronized (mPackages) {
5498            final Object obj = mSettings.getUserIdLPr(appId);
5499            if (obj instanceof PackageSetting) {
5500                final PackageSetting ps = (PackageSetting) obj;
5501                return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null;
5502            }
5503        }
5504        return null;
5505    }
5506
5507    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5508            String resolvedType, int flags, int userId) {
5509        if (!sUserManager.exists(userId)) return Collections.emptyList();
5510        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5511        flags = updateFlagsForResolve(flags, userId, intent);
5512        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5513                false /* requireFullPermission */, false /* checkShell */,
5514                "query intent activities");
5515        ComponentName comp = intent.getComponent();
5516        if (comp == null) {
5517            if (intent.getSelector() != null) {
5518                intent = intent.getSelector();
5519                comp = intent.getComponent();
5520            }
5521        }
5522
5523        if (comp != null) {
5524            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5525            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5526            if (ai != null) {
5527                final ResolveInfo ri = new ResolveInfo();
5528                ri.activityInfo = ai;
5529                list.add(ri);
5530            }
5531            return list;
5532        }
5533
5534        // reader
5535        boolean sortResult = false;
5536        boolean addEphemeral = false;
5537        List<ResolveInfo> result;
5538        final String pkgName = intent.getPackage();
5539        synchronized (mPackages) {
5540            if (pkgName == null) {
5541                List<CrossProfileIntentFilter> matchingFilters =
5542                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5543                // Check for results that need to skip the current profile.
5544                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5545                        resolvedType, flags, userId);
5546                if (xpResolveInfo != null) {
5547                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5548                    xpResult.add(xpResolveInfo);
5549                    return filterForEphemeral(
5550                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5551                }
5552
5553                // Check for results in the current profile.
5554                result = filterIfNotSystemUser(mActivities.queryIntent(
5555                        intent, resolvedType, flags, userId), userId);
5556                addEphemeral =
5557                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5558
5559                // Check for cross profile results.
5560                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5561                xpResolveInfo = queryCrossProfileIntents(
5562                        matchingFilters, intent, resolvedType, flags, userId,
5563                        hasNonNegativePriorityResult);
5564                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5565                    boolean isVisibleToUser = filterIfNotSystemUser(
5566                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5567                    if (isVisibleToUser) {
5568                        result.add(xpResolveInfo);
5569                        sortResult = true;
5570                    }
5571                }
5572                if (hasWebURI(intent)) {
5573                    CrossProfileDomainInfo xpDomainInfo = null;
5574                    final UserInfo parent = getProfileParent(userId);
5575                    if (parent != null) {
5576                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5577                                flags, userId, parent.id);
5578                    }
5579                    if (xpDomainInfo != null) {
5580                        if (xpResolveInfo != null) {
5581                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5582                            // in the result.
5583                            result.remove(xpResolveInfo);
5584                        }
5585                        if (result.size() == 0 && !addEphemeral) {
5586                            // No result in current profile, but found candidate in parent user.
5587                            // And we are not going to add emphemeral app, so we can return the
5588                            // result straight away.
5589                            result.add(xpDomainInfo.resolveInfo);
5590                            return filterForEphemeral(result, ephemeralPkgName);
5591                        }
5592                    } else if (result.size() <= 1 && !addEphemeral) {
5593                        // No result in parent user and <= 1 result in current profile, and we
5594                        // are not going to add emphemeral app, so we can return the result without
5595                        // further processing.
5596                        return filterForEphemeral(result, ephemeralPkgName);
5597                    }
5598                    // We have more than one candidate (combining results from current and parent
5599                    // profile), so we need filtering and sorting.
5600                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5601                            intent, flags, result, xpDomainInfo, userId);
5602                    sortResult = true;
5603                }
5604            } else {
5605                final PackageParser.Package pkg = mPackages.get(pkgName);
5606                if (pkg != null) {
5607                    result = filterIfNotSystemUser(
5608                            mActivities.queryIntentForPackage(
5609                                    intent, resolvedType, flags, pkg.activities, userId),
5610                            userId);
5611                } else {
5612                    // the caller wants to resolve for a particular package; however, there
5613                    // were no installed results, so, try to find an ephemeral result
5614                    addEphemeral = isEphemeralAllowed(
5615                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5616                    result = new ArrayList<ResolveInfo>();
5617                }
5618            }
5619        }
5620        if (addEphemeral) {
5621            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5622            final EphemeralRequest requestObject = new EphemeralRequest(
5623                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5624                    null /*launchIntent*/, null /*callingPackage*/, userId);
5625            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5626                    mContext, mEphemeralResolverConnection, requestObject);
5627            if (intentInfo != null) {
5628                if (DEBUG_EPHEMERAL) {
5629                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5630                }
5631                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5632                ephemeralInstaller.ephemeralResponse = intentInfo;
5633                // make sure this resolver is the default
5634                ephemeralInstaller.isDefault = true;
5635                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5636                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5637                // add a non-generic filter
5638                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5639                ephemeralInstaller.filter.addDataPath(
5640                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5641                result.add(ephemeralInstaller);
5642            }
5643            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5644        }
5645        if (sortResult) {
5646            Collections.sort(result, mResolvePrioritySorter);
5647        }
5648        return filterForEphemeral(result, ephemeralPkgName);
5649    }
5650
5651    private static class CrossProfileDomainInfo {
5652        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5653        ResolveInfo resolveInfo;
5654        /* Best domain verification status of the activities found in the other profile */
5655        int bestDomainVerificationStatus;
5656    }
5657
5658    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5659            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5660        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5661                sourceUserId)) {
5662            return null;
5663        }
5664        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5665                resolvedType, flags, parentUserId);
5666
5667        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5668            return null;
5669        }
5670        CrossProfileDomainInfo result = null;
5671        int size = resultTargetUser.size();
5672        for (int i = 0; i < size; i++) {
5673            ResolveInfo riTargetUser = resultTargetUser.get(i);
5674            // Intent filter verification is only for filters that specify a host. So don't return
5675            // those that handle all web uris.
5676            if (riTargetUser.handleAllWebDataURI) {
5677                continue;
5678            }
5679            String packageName = riTargetUser.activityInfo.packageName;
5680            PackageSetting ps = mSettings.mPackages.get(packageName);
5681            if (ps == null) {
5682                continue;
5683            }
5684            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5685            int status = (int)(verificationState >> 32);
5686            if (result == null) {
5687                result = new CrossProfileDomainInfo();
5688                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5689                        sourceUserId, parentUserId);
5690                result.bestDomainVerificationStatus = status;
5691            } else {
5692                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5693                        result.bestDomainVerificationStatus);
5694            }
5695        }
5696        // Don't consider matches with status NEVER across profiles.
5697        if (result != null && result.bestDomainVerificationStatus
5698                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5699            return null;
5700        }
5701        return result;
5702    }
5703
5704    /**
5705     * Verification statuses are ordered from the worse to the best, except for
5706     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5707     */
5708    private int bestDomainVerificationStatus(int status1, int status2) {
5709        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5710            return status2;
5711        }
5712        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5713            return status1;
5714        }
5715        return (int) MathUtils.max(status1, status2);
5716    }
5717
5718    private boolean isUserEnabled(int userId) {
5719        long callingId = Binder.clearCallingIdentity();
5720        try {
5721            UserInfo userInfo = sUserManager.getUserInfo(userId);
5722            return userInfo != null && userInfo.isEnabled();
5723        } finally {
5724            Binder.restoreCallingIdentity(callingId);
5725        }
5726    }
5727
5728    /**
5729     * Filter out activities with systemUserOnly flag set, when current user is not System.
5730     *
5731     * @return filtered list
5732     */
5733    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5734        if (userId == UserHandle.USER_SYSTEM) {
5735            return resolveInfos;
5736        }
5737        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5738            ResolveInfo info = resolveInfos.get(i);
5739            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5740                resolveInfos.remove(i);
5741            }
5742        }
5743        return resolveInfos;
5744    }
5745
5746    /**
5747     * Filters out ephemeral activities.
5748     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
5749     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
5750     *
5751     * @param resolveInfos The pre-filtered list of resolved activities
5752     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
5753     *          is performed.
5754     * @return A filtered list of resolved activities.
5755     */
5756    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
5757            String ephemeralPkgName) {
5758        if (ephemeralPkgName == null) {
5759            return resolveInfos;
5760        }
5761        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5762            ResolveInfo info = resolveInfos.get(i);
5763            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
5764            // allow activities that are defined in the provided package
5765            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
5766                continue;
5767            }
5768            // allow activities that have been explicitly exposed to ephemeral apps
5769            if (!isEphemeralApp
5770                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
5771                continue;
5772            }
5773            resolveInfos.remove(i);
5774        }
5775        return resolveInfos;
5776    }
5777
5778    /**
5779     * @param resolveInfos list of resolve infos in descending priority order
5780     * @return if the list contains a resolve info with non-negative priority
5781     */
5782    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5783        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5784    }
5785
5786    private static boolean hasWebURI(Intent intent) {
5787        if (intent.getData() == null) {
5788            return false;
5789        }
5790        final String scheme = intent.getScheme();
5791        if (TextUtils.isEmpty(scheme)) {
5792            return false;
5793        }
5794        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5795    }
5796
5797    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5798            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5799            int userId) {
5800        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5801
5802        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5803            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5804                    candidates.size());
5805        }
5806
5807        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5808        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5809        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5810        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5811        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5812        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5813
5814        synchronized (mPackages) {
5815            final int count = candidates.size();
5816            // First, try to use linked apps. Partition the candidates into four lists:
5817            // one for the final results, one for the "do not use ever", one for "undefined status"
5818            // and finally one for "browser app type".
5819            for (int n=0; n<count; n++) {
5820                ResolveInfo info = candidates.get(n);
5821                String packageName = info.activityInfo.packageName;
5822                PackageSetting ps = mSettings.mPackages.get(packageName);
5823                if (ps != null) {
5824                    // Add to the special match all list (Browser use case)
5825                    if (info.handleAllWebDataURI) {
5826                        matchAllList.add(info);
5827                        continue;
5828                    }
5829                    // Try to get the status from User settings first
5830                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5831                    int status = (int)(packedStatus >> 32);
5832                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5833                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5834                        if (DEBUG_DOMAIN_VERIFICATION) {
5835                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5836                                    + " : linkgen=" + linkGeneration);
5837                        }
5838                        // Use link-enabled generation as preferredOrder, i.e.
5839                        // prefer newly-enabled over earlier-enabled.
5840                        info.preferredOrder = linkGeneration;
5841                        alwaysList.add(info);
5842                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5843                        if (DEBUG_DOMAIN_VERIFICATION) {
5844                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5845                        }
5846                        neverList.add(info);
5847                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5848                        if (DEBUG_DOMAIN_VERIFICATION) {
5849                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5850                        }
5851                        alwaysAskList.add(info);
5852                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5853                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5854                        if (DEBUG_DOMAIN_VERIFICATION) {
5855                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5856                        }
5857                        undefinedList.add(info);
5858                    }
5859                }
5860            }
5861
5862            // We'll want to include browser possibilities in a few cases
5863            boolean includeBrowser = false;
5864
5865            // First try to add the "always" resolution(s) for the current user, if any
5866            if (alwaysList.size() > 0) {
5867                result.addAll(alwaysList);
5868            } else {
5869                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5870                result.addAll(undefinedList);
5871                // Maybe add one for the other profile.
5872                if (xpDomainInfo != null && (
5873                        xpDomainInfo.bestDomainVerificationStatus
5874                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5875                    result.add(xpDomainInfo.resolveInfo);
5876                }
5877                includeBrowser = true;
5878            }
5879
5880            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5881            // If there were 'always' entries their preferred order has been set, so we also
5882            // back that off to make the alternatives equivalent
5883            if (alwaysAskList.size() > 0) {
5884                for (ResolveInfo i : result) {
5885                    i.preferredOrder = 0;
5886                }
5887                result.addAll(alwaysAskList);
5888                includeBrowser = true;
5889            }
5890
5891            if (includeBrowser) {
5892                // Also add browsers (all of them or only the default one)
5893                if (DEBUG_DOMAIN_VERIFICATION) {
5894                    Slog.v(TAG, "   ...including browsers in candidate set");
5895                }
5896                if ((matchFlags & MATCH_ALL) != 0) {
5897                    result.addAll(matchAllList);
5898                } else {
5899                    // Browser/generic handling case.  If there's a default browser, go straight
5900                    // to that (but only if there is no other higher-priority match).
5901                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5902                    int maxMatchPrio = 0;
5903                    ResolveInfo defaultBrowserMatch = null;
5904                    final int numCandidates = matchAllList.size();
5905                    for (int n = 0; n < numCandidates; n++) {
5906                        ResolveInfo info = matchAllList.get(n);
5907                        // track the highest overall match priority...
5908                        if (info.priority > maxMatchPrio) {
5909                            maxMatchPrio = info.priority;
5910                        }
5911                        // ...and the highest-priority default browser match
5912                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5913                            if (defaultBrowserMatch == null
5914                                    || (defaultBrowserMatch.priority < info.priority)) {
5915                                if (debug) {
5916                                    Slog.v(TAG, "Considering default browser match " + info);
5917                                }
5918                                defaultBrowserMatch = info;
5919                            }
5920                        }
5921                    }
5922                    if (defaultBrowserMatch != null
5923                            && defaultBrowserMatch.priority >= maxMatchPrio
5924                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5925                    {
5926                        if (debug) {
5927                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5928                        }
5929                        result.add(defaultBrowserMatch);
5930                    } else {
5931                        result.addAll(matchAllList);
5932                    }
5933                }
5934
5935                // If there is nothing selected, add all candidates and remove the ones that the user
5936                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5937                if (result.size() == 0) {
5938                    result.addAll(candidates);
5939                    result.removeAll(neverList);
5940                }
5941            }
5942        }
5943        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5944            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5945                    result.size());
5946            for (ResolveInfo info : result) {
5947                Slog.v(TAG, "  + " + info.activityInfo);
5948            }
5949        }
5950        return result;
5951    }
5952
5953    // Returns a packed value as a long:
5954    //
5955    // high 'int'-sized word: link status: undefined/ask/never/always.
5956    // low 'int'-sized word: relative priority among 'always' results.
5957    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5958        long result = ps.getDomainVerificationStatusForUser(userId);
5959        // if none available, get the master status
5960        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5961            if (ps.getIntentFilterVerificationInfo() != null) {
5962                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5963            }
5964        }
5965        return result;
5966    }
5967
5968    private ResolveInfo querySkipCurrentProfileIntents(
5969            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5970            int flags, int sourceUserId) {
5971        if (matchingFilters != null) {
5972            int size = matchingFilters.size();
5973            for (int i = 0; i < size; i ++) {
5974                CrossProfileIntentFilter filter = matchingFilters.get(i);
5975                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5976                    // Checking if there are activities in the target user that can handle the
5977                    // intent.
5978                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5979                            resolvedType, flags, sourceUserId);
5980                    if (resolveInfo != null) {
5981                        return resolveInfo;
5982                    }
5983                }
5984            }
5985        }
5986        return null;
5987    }
5988
5989    // Return matching ResolveInfo in target user if any.
5990    private ResolveInfo queryCrossProfileIntents(
5991            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5992            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5993        if (matchingFilters != null) {
5994            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5995            // match the same intent. For performance reasons, it is better not to
5996            // run queryIntent twice for the same userId
5997            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5998            int size = matchingFilters.size();
5999            for (int i = 0; i < size; i++) {
6000                CrossProfileIntentFilter filter = matchingFilters.get(i);
6001                int targetUserId = filter.getTargetUserId();
6002                boolean skipCurrentProfile =
6003                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6004                boolean skipCurrentProfileIfNoMatchFound =
6005                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6006                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6007                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6008                    // Checking if there are activities in the target user that can handle the
6009                    // intent.
6010                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6011                            resolvedType, flags, sourceUserId);
6012                    if (resolveInfo != null) return resolveInfo;
6013                    alreadyTriedUserIds.put(targetUserId, true);
6014                }
6015            }
6016        }
6017        return null;
6018    }
6019
6020    /**
6021     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6022     * will forward the intent to the filter's target user.
6023     * Otherwise, returns null.
6024     */
6025    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6026            String resolvedType, int flags, int sourceUserId) {
6027        int targetUserId = filter.getTargetUserId();
6028        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6029                resolvedType, flags, targetUserId);
6030        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6031            // If all the matches in the target profile are suspended, return null.
6032            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6033                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6034                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6035                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6036                            targetUserId);
6037                }
6038            }
6039        }
6040        return null;
6041    }
6042
6043    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6044            int sourceUserId, int targetUserId) {
6045        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6046        long ident = Binder.clearCallingIdentity();
6047        boolean targetIsProfile;
6048        try {
6049            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6050        } finally {
6051            Binder.restoreCallingIdentity(ident);
6052        }
6053        String className;
6054        if (targetIsProfile) {
6055            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6056        } else {
6057            className = FORWARD_INTENT_TO_PARENT;
6058        }
6059        ComponentName forwardingActivityComponentName = new ComponentName(
6060                mAndroidApplication.packageName, className);
6061        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6062                sourceUserId);
6063        if (!targetIsProfile) {
6064            forwardingActivityInfo.showUserIcon = targetUserId;
6065            forwardingResolveInfo.noResourceId = true;
6066        }
6067        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6068        forwardingResolveInfo.priority = 0;
6069        forwardingResolveInfo.preferredOrder = 0;
6070        forwardingResolveInfo.match = 0;
6071        forwardingResolveInfo.isDefault = true;
6072        forwardingResolveInfo.filter = filter;
6073        forwardingResolveInfo.targetUserId = targetUserId;
6074        return forwardingResolveInfo;
6075    }
6076
6077    @Override
6078    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6079            Intent[] specifics, String[] specificTypes, Intent intent,
6080            String resolvedType, int flags, int userId) {
6081        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6082                specificTypes, intent, resolvedType, flags, userId));
6083    }
6084
6085    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6086            Intent[] specifics, String[] specificTypes, Intent intent,
6087            String resolvedType, int flags, int userId) {
6088        if (!sUserManager.exists(userId)) return Collections.emptyList();
6089        flags = updateFlagsForResolve(flags, userId, intent);
6090        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6091                false /* requireFullPermission */, false /* checkShell */,
6092                "query intent activity options");
6093        final String resultsAction = intent.getAction();
6094
6095        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6096                | PackageManager.GET_RESOLVED_FILTER, userId);
6097
6098        if (DEBUG_INTENT_MATCHING) {
6099            Log.v(TAG, "Query " + intent + ": " + results);
6100        }
6101
6102        int specificsPos = 0;
6103        int N;
6104
6105        // todo: note that the algorithm used here is O(N^2).  This
6106        // isn't a problem in our current environment, but if we start running
6107        // into situations where we have more than 5 or 10 matches then this
6108        // should probably be changed to something smarter...
6109
6110        // First we go through and resolve each of the specific items
6111        // that were supplied, taking care of removing any corresponding
6112        // duplicate items in the generic resolve list.
6113        if (specifics != null) {
6114            for (int i=0; i<specifics.length; i++) {
6115                final Intent sintent = specifics[i];
6116                if (sintent == null) {
6117                    continue;
6118                }
6119
6120                if (DEBUG_INTENT_MATCHING) {
6121                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6122                }
6123
6124                String action = sintent.getAction();
6125                if (resultsAction != null && resultsAction.equals(action)) {
6126                    // If this action was explicitly requested, then don't
6127                    // remove things that have it.
6128                    action = null;
6129                }
6130
6131                ResolveInfo ri = null;
6132                ActivityInfo ai = null;
6133
6134                ComponentName comp = sintent.getComponent();
6135                if (comp == null) {
6136                    ri = resolveIntent(
6137                        sintent,
6138                        specificTypes != null ? specificTypes[i] : null,
6139                            flags, userId);
6140                    if (ri == null) {
6141                        continue;
6142                    }
6143                    if (ri == mResolveInfo) {
6144                        // ACK!  Must do something better with this.
6145                    }
6146                    ai = ri.activityInfo;
6147                    comp = new ComponentName(ai.applicationInfo.packageName,
6148                            ai.name);
6149                } else {
6150                    ai = getActivityInfo(comp, flags, userId);
6151                    if (ai == null) {
6152                        continue;
6153                    }
6154                }
6155
6156                // Look for any generic query activities that are duplicates
6157                // of this specific one, and remove them from the results.
6158                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6159                N = results.size();
6160                int j;
6161                for (j=specificsPos; j<N; j++) {
6162                    ResolveInfo sri = results.get(j);
6163                    if ((sri.activityInfo.name.equals(comp.getClassName())
6164                            && sri.activityInfo.applicationInfo.packageName.equals(
6165                                    comp.getPackageName()))
6166                        || (action != null && sri.filter.matchAction(action))) {
6167                        results.remove(j);
6168                        if (DEBUG_INTENT_MATCHING) Log.v(
6169                            TAG, "Removing duplicate item from " + j
6170                            + " due to specific " + specificsPos);
6171                        if (ri == null) {
6172                            ri = sri;
6173                        }
6174                        j--;
6175                        N--;
6176                    }
6177                }
6178
6179                // Add this specific item to its proper place.
6180                if (ri == null) {
6181                    ri = new ResolveInfo();
6182                    ri.activityInfo = ai;
6183                }
6184                results.add(specificsPos, ri);
6185                ri.specificIndex = i;
6186                specificsPos++;
6187            }
6188        }
6189
6190        // Now we go through the remaining generic results and remove any
6191        // duplicate actions that are found here.
6192        N = results.size();
6193        for (int i=specificsPos; i<N-1; i++) {
6194            final ResolveInfo rii = results.get(i);
6195            if (rii.filter == null) {
6196                continue;
6197            }
6198
6199            // Iterate over all of the actions of this result's intent
6200            // filter...  typically this should be just one.
6201            final Iterator<String> it = rii.filter.actionsIterator();
6202            if (it == null) {
6203                continue;
6204            }
6205            while (it.hasNext()) {
6206                final String action = it.next();
6207                if (resultsAction != null && resultsAction.equals(action)) {
6208                    // If this action was explicitly requested, then don't
6209                    // remove things that have it.
6210                    continue;
6211                }
6212                for (int j=i+1; j<N; j++) {
6213                    final ResolveInfo rij = results.get(j);
6214                    if (rij.filter != null && rij.filter.hasAction(action)) {
6215                        results.remove(j);
6216                        if (DEBUG_INTENT_MATCHING) Log.v(
6217                            TAG, "Removing duplicate item from " + j
6218                            + " due to action " + action + " at " + i);
6219                        j--;
6220                        N--;
6221                    }
6222                }
6223            }
6224
6225            // If the caller didn't request filter information, drop it now
6226            // so we don't have to marshall/unmarshall it.
6227            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6228                rii.filter = null;
6229            }
6230        }
6231
6232        // Filter out the caller activity if so requested.
6233        if (caller != null) {
6234            N = results.size();
6235            for (int i=0; i<N; i++) {
6236                ActivityInfo ainfo = results.get(i).activityInfo;
6237                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6238                        && caller.getClassName().equals(ainfo.name)) {
6239                    results.remove(i);
6240                    break;
6241                }
6242            }
6243        }
6244
6245        // If the caller didn't request filter information,
6246        // drop them now so we don't have to
6247        // marshall/unmarshall it.
6248        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6249            N = results.size();
6250            for (int i=0; i<N; i++) {
6251                results.get(i).filter = null;
6252            }
6253        }
6254
6255        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6256        return results;
6257    }
6258
6259    @Override
6260    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6261            String resolvedType, int flags, int userId) {
6262        return new ParceledListSlice<>(
6263                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6264    }
6265
6266    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6267            String resolvedType, int flags, int userId) {
6268        if (!sUserManager.exists(userId)) return Collections.emptyList();
6269        flags = updateFlagsForResolve(flags, userId, intent);
6270        ComponentName comp = intent.getComponent();
6271        if (comp == null) {
6272            if (intent.getSelector() != null) {
6273                intent = intent.getSelector();
6274                comp = intent.getComponent();
6275            }
6276        }
6277        if (comp != null) {
6278            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6279            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6280            if (ai != null) {
6281                ResolveInfo ri = new ResolveInfo();
6282                ri.activityInfo = ai;
6283                list.add(ri);
6284            }
6285            return list;
6286        }
6287
6288        // reader
6289        synchronized (mPackages) {
6290            String pkgName = intent.getPackage();
6291            if (pkgName == null) {
6292                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6293            }
6294            final PackageParser.Package pkg = mPackages.get(pkgName);
6295            if (pkg != null) {
6296                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6297                        userId);
6298            }
6299            return Collections.emptyList();
6300        }
6301    }
6302
6303    @Override
6304    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6305        if (!sUserManager.exists(userId)) return null;
6306        flags = updateFlagsForResolve(flags, userId, intent);
6307        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6308        if (query != null) {
6309            if (query.size() >= 1) {
6310                // If there is more than one service with the same priority,
6311                // just arbitrarily pick the first one.
6312                return query.get(0);
6313            }
6314        }
6315        return null;
6316    }
6317
6318    @Override
6319    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6320            String resolvedType, int flags, int userId) {
6321        return new ParceledListSlice<>(
6322                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6323    }
6324
6325    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6326            String resolvedType, int flags, int userId) {
6327        if (!sUserManager.exists(userId)) return Collections.emptyList();
6328        flags = updateFlagsForResolve(flags, userId, intent);
6329        ComponentName comp = intent.getComponent();
6330        if (comp == null) {
6331            if (intent.getSelector() != null) {
6332                intent = intent.getSelector();
6333                comp = intent.getComponent();
6334            }
6335        }
6336        if (comp != null) {
6337            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6338            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6339            if (si != null) {
6340                final ResolveInfo ri = new ResolveInfo();
6341                ri.serviceInfo = si;
6342                list.add(ri);
6343            }
6344            return list;
6345        }
6346
6347        // reader
6348        synchronized (mPackages) {
6349            String pkgName = intent.getPackage();
6350            if (pkgName == null) {
6351                return mServices.queryIntent(intent, resolvedType, flags, userId);
6352            }
6353            final PackageParser.Package pkg = mPackages.get(pkgName);
6354            if (pkg != null) {
6355                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6356                        userId);
6357            }
6358            return Collections.emptyList();
6359        }
6360    }
6361
6362    @Override
6363    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6364            String resolvedType, int flags, int userId) {
6365        return new ParceledListSlice<>(
6366                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6367    }
6368
6369    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6370            Intent intent, String resolvedType, int flags, int userId) {
6371        if (!sUserManager.exists(userId)) return Collections.emptyList();
6372        flags = updateFlagsForResolve(flags, userId, intent);
6373        ComponentName comp = intent.getComponent();
6374        if (comp == null) {
6375            if (intent.getSelector() != null) {
6376                intent = intent.getSelector();
6377                comp = intent.getComponent();
6378            }
6379        }
6380        if (comp != null) {
6381            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6382            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6383            if (pi != null) {
6384                final ResolveInfo ri = new ResolveInfo();
6385                ri.providerInfo = pi;
6386                list.add(ri);
6387            }
6388            return list;
6389        }
6390
6391        // reader
6392        synchronized (mPackages) {
6393            String pkgName = intent.getPackage();
6394            if (pkgName == null) {
6395                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6396            }
6397            final PackageParser.Package pkg = mPackages.get(pkgName);
6398            if (pkg != null) {
6399                return mProviders.queryIntentForPackage(
6400                        intent, resolvedType, flags, pkg.providers, userId);
6401            }
6402            return Collections.emptyList();
6403        }
6404    }
6405
6406    @Override
6407    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6408        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6409        flags = updateFlagsForPackage(flags, userId, null);
6410        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6412                true /* requireFullPermission */, false /* checkShell */,
6413                "get installed packages");
6414
6415        // writer
6416        synchronized (mPackages) {
6417            ArrayList<PackageInfo> list;
6418            if (listUninstalled) {
6419                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6420                for (PackageSetting ps : mSettings.mPackages.values()) {
6421                    final PackageInfo pi;
6422                    if (ps.pkg != null) {
6423                        pi = generatePackageInfo(ps, flags, userId);
6424                    } else {
6425                        pi = generatePackageInfo(ps, flags, userId);
6426                    }
6427                    if (pi != null) {
6428                        list.add(pi);
6429                    }
6430                }
6431            } else {
6432                list = new ArrayList<PackageInfo>(mPackages.size());
6433                for (PackageParser.Package p : mPackages.values()) {
6434                    final PackageInfo pi =
6435                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6436                    if (pi != null) {
6437                        list.add(pi);
6438                    }
6439                }
6440            }
6441
6442            return new ParceledListSlice<PackageInfo>(list);
6443        }
6444    }
6445
6446    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6447            String[] permissions, boolean[] tmp, int flags, int userId) {
6448        int numMatch = 0;
6449        final PermissionsState permissionsState = ps.getPermissionsState();
6450        for (int i=0; i<permissions.length; i++) {
6451            final String permission = permissions[i];
6452            if (permissionsState.hasPermission(permission, userId)) {
6453                tmp[i] = true;
6454                numMatch++;
6455            } else {
6456                tmp[i] = false;
6457            }
6458        }
6459        if (numMatch == 0) {
6460            return;
6461        }
6462        final PackageInfo pi;
6463        if (ps.pkg != null) {
6464            pi = generatePackageInfo(ps, flags, userId);
6465        } else {
6466            pi = generatePackageInfo(ps, flags, userId);
6467        }
6468        // The above might return null in cases of uninstalled apps or install-state
6469        // skew across users/profiles.
6470        if (pi != null) {
6471            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6472                if (numMatch == permissions.length) {
6473                    pi.requestedPermissions = permissions;
6474                } else {
6475                    pi.requestedPermissions = new String[numMatch];
6476                    numMatch = 0;
6477                    for (int i=0; i<permissions.length; i++) {
6478                        if (tmp[i]) {
6479                            pi.requestedPermissions[numMatch] = permissions[i];
6480                            numMatch++;
6481                        }
6482                    }
6483                }
6484            }
6485            list.add(pi);
6486        }
6487    }
6488
6489    @Override
6490    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6491            String[] permissions, int flags, int userId) {
6492        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6493        flags = updateFlagsForPackage(flags, userId, permissions);
6494        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6495                true /* requireFullPermission */, false /* checkShell */,
6496                "get packages holding permissions");
6497        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6498
6499        // writer
6500        synchronized (mPackages) {
6501            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6502            boolean[] tmpBools = new boolean[permissions.length];
6503            if (listUninstalled) {
6504                for (PackageSetting ps : mSettings.mPackages.values()) {
6505                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6506                            userId);
6507                }
6508            } else {
6509                for (PackageParser.Package pkg : mPackages.values()) {
6510                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6511                    if (ps != null) {
6512                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6513                                userId);
6514                    }
6515                }
6516            }
6517
6518            return new ParceledListSlice<PackageInfo>(list);
6519        }
6520    }
6521
6522    @Override
6523    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6524        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6525        flags = updateFlagsForApplication(flags, userId, null);
6526        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6527
6528        // writer
6529        synchronized (mPackages) {
6530            ArrayList<ApplicationInfo> list;
6531            if (listUninstalled) {
6532                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6533                for (PackageSetting ps : mSettings.mPackages.values()) {
6534                    ApplicationInfo ai;
6535                    int effectiveFlags = flags;
6536                    if (ps.isSystem()) {
6537                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6538                    }
6539                    if (ps.pkg != null) {
6540                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6541                                ps.readUserState(userId), userId);
6542                    } else {
6543                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6544                                userId);
6545                    }
6546                    if (ai != null) {
6547                        list.add(ai);
6548                    }
6549                }
6550            } else {
6551                list = new ArrayList<ApplicationInfo>(mPackages.size());
6552                for (PackageParser.Package p : mPackages.values()) {
6553                    if (p.mExtras != null) {
6554                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6555                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6556                        if (ai != null) {
6557                            list.add(ai);
6558                        }
6559                    }
6560                }
6561            }
6562
6563            return new ParceledListSlice<ApplicationInfo>(list);
6564        }
6565    }
6566
6567    @Override
6568    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6569        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6570            return null;
6571        }
6572
6573        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6574                "getEphemeralApplications");
6575        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6576                true /* requireFullPermission */, false /* checkShell */,
6577                "getEphemeralApplications");
6578        synchronized (mPackages) {
6579            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6580                    .getEphemeralApplicationsLPw(userId);
6581            if (ephemeralApps != null) {
6582                return new ParceledListSlice<>(ephemeralApps);
6583            }
6584        }
6585        return null;
6586    }
6587
6588    @Override
6589    public boolean isEphemeralApplication(String packageName, int userId) {
6590        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6591                true /* requireFullPermission */, false /* checkShell */,
6592                "isEphemeral");
6593        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6594            return false;
6595        }
6596
6597        if (!isCallerSameApp(packageName)) {
6598            return false;
6599        }
6600        synchronized (mPackages) {
6601            PackageParser.Package pkg = mPackages.get(packageName);
6602            if (pkg != null) {
6603                return pkg.applicationInfo.isEphemeralApp();
6604            }
6605        }
6606        return false;
6607    }
6608
6609    @Override
6610    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6611        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6612            return null;
6613        }
6614
6615        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6616                true /* requireFullPermission */, false /* checkShell */,
6617                "getCookie");
6618        if (!isCallerSameApp(packageName)) {
6619            return null;
6620        }
6621        synchronized (mPackages) {
6622            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6623                    packageName, userId);
6624        }
6625    }
6626
6627    @Override
6628    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6629        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6630            return true;
6631        }
6632
6633        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6634                true /* requireFullPermission */, true /* checkShell */,
6635                "setCookie");
6636        if (!isCallerSameApp(packageName)) {
6637            return false;
6638        }
6639        synchronized (mPackages) {
6640            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6641                    packageName, cookie, userId);
6642        }
6643    }
6644
6645    @Override
6646    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6647        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6648            return null;
6649        }
6650
6651        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6652                "getEphemeralApplicationIcon");
6653        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6654                true /* requireFullPermission */, false /* checkShell */,
6655                "getEphemeralApplicationIcon");
6656        synchronized (mPackages) {
6657            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6658                    packageName, userId);
6659        }
6660    }
6661
6662    private boolean isCallerSameApp(String packageName) {
6663        PackageParser.Package pkg = mPackages.get(packageName);
6664        return pkg != null
6665                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6666    }
6667
6668    @Override
6669    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6670        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6671    }
6672
6673    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6674        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6675
6676        // reader
6677        synchronized (mPackages) {
6678            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6679            final int userId = UserHandle.getCallingUserId();
6680            while (i.hasNext()) {
6681                final PackageParser.Package p = i.next();
6682                if (p.applicationInfo == null) continue;
6683
6684                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6685                        && !p.applicationInfo.isDirectBootAware();
6686                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6687                        && p.applicationInfo.isDirectBootAware();
6688
6689                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6690                        && (!mSafeMode || isSystemApp(p))
6691                        && (matchesUnaware || matchesAware)) {
6692                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6693                    if (ps != null) {
6694                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6695                                ps.readUserState(userId), userId);
6696                        if (ai != null) {
6697                            finalList.add(ai);
6698                        }
6699                    }
6700                }
6701            }
6702        }
6703
6704        return finalList;
6705    }
6706
6707    @Override
6708    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6709        if (!sUserManager.exists(userId)) return null;
6710        flags = updateFlagsForComponent(flags, userId, name);
6711        // reader
6712        synchronized (mPackages) {
6713            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6714            PackageSetting ps = provider != null
6715                    ? mSettings.mPackages.get(provider.owner.packageName)
6716                    : null;
6717            return ps != null
6718                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6719                    ? PackageParser.generateProviderInfo(provider, flags,
6720                            ps.readUserState(userId), userId)
6721                    : null;
6722        }
6723    }
6724
6725    /**
6726     * @deprecated
6727     */
6728    @Deprecated
6729    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6730        // reader
6731        synchronized (mPackages) {
6732            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6733                    .entrySet().iterator();
6734            final int userId = UserHandle.getCallingUserId();
6735            while (i.hasNext()) {
6736                Map.Entry<String, PackageParser.Provider> entry = i.next();
6737                PackageParser.Provider p = entry.getValue();
6738                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6739
6740                if (ps != null && p.syncable
6741                        && (!mSafeMode || (p.info.applicationInfo.flags
6742                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6743                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6744                            ps.readUserState(userId), userId);
6745                    if (info != null) {
6746                        outNames.add(entry.getKey());
6747                        outInfo.add(info);
6748                    }
6749                }
6750            }
6751        }
6752    }
6753
6754    @Override
6755    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6756            int uid, int flags) {
6757        final int userId = processName != null ? UserHandle.getUserId(uid)
6758                : UserHandle.getCallingUserId();
6759        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6760        flags = updateFlagsForComponent(flags, userId, processName);
6761
6762        ArrayList<ProviderInfo> finalList = null;
6763        // reader
6764        synchronized (mPackages) {
6765            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6766            while (i.hasNext()) {
6767                final PackageParser.Provider p = i.next();
6768                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6769                if (ps != null && p.info.authority != null
6770                        && (processName == null
6771                                || (p.info.processName.equals(processName)
6772                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6773                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6774                    if (finalList == null) {
6775                        finalList = new ArrayList<ProviderInfo>(3);
6776                    }
6777                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6778                            ps.readUserState(userId), userId);
6779                    if (info != null) {
6780                        finalList.add(info);
6781                    }
6782                }
6783            }
6784        }
6785
6786        if (finalList != null) {
6787            Collections.sort(finalList, mProviderInitOrderSorter);
6788            return new ParceledListSlice<ProviderInfo>(finalList);
6789        }
6790
6791        return ParceledListSlice.emptyList();
6792    }
6793
6794    @Override
6795    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6796        // reader
6797        synchronized (mPackages) {
6798            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6799            return PackageParser.generateInstrumentationInfo(i, flags);
6800        }
6801    }
6802
6803    @Override
6804    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6805            String targetPackage, int flags) {
6806        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6807    }
6808
6809    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6810            int flags) {
6811        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6812
6813        // reader
6814        synchronized (mPackages) {
6815            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6816            while (i.hasNext()) {
6817                final PackageParser.Instrumentation p = i.next();
6818                if (targetPackage == null
6819                        || targetPackage.equals(p.info.targetPackage)) {
6820                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6821                            flags);
6822                    if (ii != null) {
6823                        finalList.add(ii);
6824                    }
6825                }
6826            }
6827        }
6828
6829        return finalList;
6830    }
6831
6832    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6833        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6834        if (overlays == null) {
6835            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6836            return;
6837        }
6838        for (PackageParser.Package opkg : overlays.values()) {
6839            // Not much to do if idmap fails: we already logged the error
6840            // and we certainly don't want to abort installation of pkg simply
6841            // because an overlay didn't fit properly. For these reasons,
6842            // ignore the return value of createIdmapForPackagePairLI.
6843            createIdmapForPackagePairLI(pkg, opkg);
6844        }
6845    }
6846
6847    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6848            PackageParser.Package opkg) {
6849        if (!opkg.mTrustedOverlay) {
6850            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6851                    opkg.baseCodePath + ": overlay not trusted");
6852            return false;
6853        }
6854        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6855        if (overlaySet == null) {
6856            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6857                    opkg.baseCodePath + " but target package has no known overlays");
6858            return false;
6859        }
6860        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6861        // TODO: generate idmap for split APKs
6862        try {
6863            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6864        } catch (InstallerException e) {
6865            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6866                    + opkg.baseCodePath);
6867            return false;
6868        }
6869        PackageParser.Package[] overlayArray =
6870            overlaySet.values().toArray(new PackageParser.Package[0]);
6871        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6872            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6873                return p1.mOverlayPriority - p2.mOverlayPriority;
6874            }
6875        };
6876        Arrays.sort(overlayArray, cmp);
6877
6878        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6879        int i = 0;
6880        for (PackageParser.Package p : overlayArray) {
6881            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6882        }
6883        return true;
6884    }
6885
6886    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6887        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6888        try {
6889            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6890        } finally {
6891            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6892        }
6893    }
6894
6895    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6896        final File[] files = dir.listFiles();
6897        if (ArrayUtils.isEmpty(files)) {
6898            Log.d(TAG, "No files in app dir " + dir);
6899            return;
6900        }
6901
6902        if (DEBUG_PACKAGE_SCANNING) {
6903            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6904                    + " flags=0x" + Integer.toHexString(parseFlags));
6905        }
6906        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
6907                mSeparateProcesses, mOnlyCore, mMetrics);
6908
6909        // Submit files for parsing in parallel
6910        int fileCount = 0;
6911        for (File file : files) {
6912            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6913                    && !PackageInstallerService.isStageName(file.getName());
6914            if (!isPackage) {
6915                // Ignore entries which are not packages
6916                continue;
6917            }
6918            parallelPackageParser.submit(file, parseFlags);
6919            fileCount++;
6920        }
6921
6922        // Process results one by one
6923        for (; fileCount > 0; fileCount--) {
6924            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
6925            Throwable throwable = parseResult.throwable;
6926            int errorCode = PackageManager.INSTALL_SUCCEEDED;
6927
6928            if (throwable == null) {
6929                try {
6930                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
6931                            currentTime, null);
6932                } catch (PackageManagerException e) {
6933                    errorCode = e.error;
6934                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
6935                }
6936            } else if (throwable instanceof PackageParser.PackageParserException) {
6937                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
6938                        throwable;
6939                errorCode = e.error;
6940                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
6941            } else {
6942                throw new IllegalStateException("Unexpected exception occurred while parsing "
6943                        + parseResult.scanFile, throwable);
6944            }
6945
6946            // Delete invalid userdata apps
6947            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6948                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
6949                logCriticalInfo(Log.WARN,
6950                        "Deleting invalid package at " + parseResult.scanFile);
6951                removeCodePathLI(parseResult.scanFile);
6952            }
6953        }
6954        parallelPackageParser.close();
6955    }
6956
6957    private static File getSettingsProblemFile() {
6958        File dataDir = Environment.getDataDirectory();
6959        File systemDir = new File(dataDir, "system");
6960        File fname = new File(systemDir, "uiderrors.txt");
6961        return fname;
6962    }
6963
6964    static void reportSettingsProblem(int priority, String msg) {
6965        logCriticalInfo(priority, msg);
6966    }
6967
6968    static void logCriticalInfo(int priority, String msg) {
6969        Slog.println(priority, TAG, msg);
6970        EventLogTags.writePmCriticalInfo(msg);
6971        try {
6972            File fname = getSettingsProblemFile();
6973            FileOutputStream out = new FileOutputStream(fname, true);
6974            PrintWriter pw = new FastPrintWriter(out);
6975            SimpleDateFormat formatter = new SimpleDateFormat();
6976            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6977            pw.println(dateString + ": " + msg);
6978            pw.close();
6979            FileUtils.setPermissions(
6980                    fname.toString(),
6981                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6982                    -1, -1);
6983        } catch (java.io.IOException e) {
6984        }
6985    }
6986
6987    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6988        if (srcFile.isDirectory()) {
6989            final File baseFile = new File(pkg.baseCodePath);
6990            long maxModifiedTime = baseFile.lastModified();
6991            if (pkg.splitCodePaths != null) {
6992                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6993                    final File splitFile = new File(pkg.splitCodePaths[i]);
6994                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6995                }
6996            }
6997            return maxModifiedTime;
6998        }
6999        return srcFile.lastModified();
7000    }
7001
7002    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7003            final int policyFlags) throws PackageManagerException {
7004        // When upgrading from pre-N MR1, verify the package time stamp using the package
7005        // directory and not the APK file.
7006        final long lastModifiedTime = mIsPreNMR1Upgrade
7007                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7008        if (ps != null
7009                && ps.codePath.equals(srcFile)
7010                && ps.timeStamp == lastModifiedTime
7011                && !isCompatSignatureUpdateNeeded(pkg)
7012                && !isRecoverSignatureUpdateNeeded(pkg)) {
7013            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7014            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7015            ArraySet<PublicKey> signingKs;
7016            synchronized (mPackages) {
7017                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7018            }
7019            if (ps.signatures.mSignatures != null
7020                    && ps.signatures.mSignatures.length != 0
7021                    && signingKs != null) {
7022                // Optimization: reuse the existing cached certificates
7023                // if the package appears to be unchanged.
7024                pkg.mSignatures = ps.signatures.mSignatures;
7025                pkg.mSigningKeys = signingKs;
7026                return;
7027            }
7028
7029            Slog.w(TAG, "PackageSetting for " + ps.name
7030                    + " is missing signatures.  Collecting certs again to recover them.");
7031        } else {
7032            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7033        }
7034
7035        try {
7036            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7037            PackageParser.collectCertificates(pkg, policyFlags);
7038        } catch (PackageParserException e) {
7039            throw PackageManagerException.from(e);
7040        } finally {
7041            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7042        }
7043    }
7044
7045    /**
7046     *  Traces a package scan.
7047     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7048     */
7049    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7050            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7051        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7052        try {
7053            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7054        } finally {
7055            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7056        }
7057    }
7058
7059    /**
7060     *  Scans a package and returns the newly parsed package.
7061     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7062     */
7063    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7064            long currentTime, UserHandle user) throws PackageManagerException {
7065        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7066        PackageParser pp = new PackageParser();
7067        pp.setSeparateProcesses(mSeparateProcesses);
7068        pp.setOnlyCoreApps(mOnlyCore);
7069        pp.setDisplayMetrics(mMetrics);
7070
7071        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7072            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7073        }
7074
7075        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7076        final PackageParser.Package pkg;
7077        try {
7078            pkg = pp.parsePackage(scanFile, parseFlags);
7079        } catch (PackageParserException e) {
7080            throw PackageManagerException.from(e);
7081        } finally {
7082            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7083        }
7084
7085        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7086    }
7087
7088    /**
7089     *  Scans a package and returns the newly parsed package.
7090     *  @throws PackageManagerException on a parse error.
7091     */
7092    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7093            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7094            throws PackageManagerException {
7095        // If the package has children and this is the first dive in the function
7096        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7097        // packages (parent and children) would be successfully scanned before the
7098        // actual scan since scanning mutates internal state and we want to atomically
7099        // install the package and its children.
7100        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7101            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7102                scanFlags |= SCAN_CHECK_ONLY;
7103            }
7104        } else {
7105            scanFlags &= ~SCAN_CHECK_ONLY;
7106        }
7107
7108        // Scan the parent
7109        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7110                scanFlags, currentTime, user);
7111
7112        // Scan the children
7113        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7114        for (int i = 0; i < childCount; i++) {
7115            PackageParser.Package childPackage = pkg.childPackages.get(i);
7116            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7117                    currentTime, user);
7118        }
7119
7120
7121        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7122            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7123        }
7124
7125        return scannedPkg;
7126    }
7127
7128    /**
7129     *  Scans a package and returns the newly parsed package.
7130     *  @throws PackageManagerException on a parse error.
7131     */
7132    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7133            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7134            throws PackageManagerException {
7135        PackageSetting ps = null;
7136        PackageSetting updatedPkg;
7137        // reader
7138        synchronized (mPackages) {
7139            // Look to see if we already know about this package.
7140            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7141            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7142                // This package has been renamed to its original name.  Let's
7143                // use that.
7144                ps = mSettings.getPackageLPr(oldName);
7145            }
7146            // If there was no original package, see one for the real package name.
7147            if (ps == null) {
7148                ps = mSettings.getPackageLPr(pkg.packageName);
7149            }
7150            // Check to see if this package could be hiding/updating a system
7151            // package.  Must look for it either under the original or real
7152            // package name depending on our state.
7153            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7154            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7155
7156            // If this is a package we don't know about on the system partition, we
7157            // may need to remove disabled child packages on the system partition
7158            // or may need to not add child packages if the parent apk is updated
7159            // on the data partition and no longer defines this child package.
7160            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7161                // If this is a parent package for an updated system app and this system
7162                // app got an OTA update which no longer defines some of the child packages
7163                // we have to prune them from the disabled system packages.
7164                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7165                if (disabledPs != null) {
7166                    final int scannedChildCount = (pkg.childPackages != null)
7167                            ? pkg.childPackages.size() : 0;
7168                    final int disabledChildCount = disabledPs.childPackageNames != null
7169                            ? disabledPs.childPackageNames.size() : 0;
7170                    for (int i = 0; i < disabledChildCount; i++) {
7171                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7172                        boolean disabledPackageAvailable = false;
7173                        for (int j = 0; j < scannedChildCount; j++) {
7174                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7175                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7176                                disabledPackageAvailable = true;
7177                                break;
7178                            }
7179                         }
7180                         if (!disabledPackageAvailable) {
7181                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7182                         }
7183                    }
7184                }
7185            }
7186        }
7187
7188        boolean updatedPkgBetter = false;
7189        // First check if this is a system package that may involve an update
7190        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7191            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7192            // it needs to drop FLAG_PRIVILEGED.
7193            if (locationIsPrivileged(scanFile)) {
7194                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7195            } else {
7196                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7197            }
7198
7199            if (ps != null && !ps.codePath.equals(scanFile)) {
7200                // The path has changed from what was last scanned...  check the
7201                // version of the new path against what we have stored to determine
7202                // what to do.
7203                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7204                if (pkg.mVersionCode <= ps.versionCode) {
7205                    // The system package has been updated and the code path does not match
7206                    // Ignore entry. Skip it.
7207                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7208                            + " ignored: updated version " + ps.versionCode
7209                            + " better than this " + pkg.mVersionCode);
7210                    if (!updatedPkg.codePath.equals(scanFile)) {
7211                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7212                                + ps.name + " changing from " + updatedPkg.codePathString
7213                                + " to " + scanFile);
7214                        updatedPkg.codePath = scanFile;
7215                        updatedPkg.codePathString = scanFile.toString();
7216                        updatedPkg.resourcePath = scanFile;
7217                        updatedPkg.resourcePathString = scanFile.toString();
7218                    }
7219                    updatedPkg.pkg = pkg;
7220                    updatedPkg.versionCode = pkg.mVersionCode;
7221
7222                    // Update the disabled system child packages to point to the package too.
7223                    final int childCount = updatedPkg.childPackageNames != null
7224                            ? updatedPkg.childPackageNames.size() : 0;
7225                    for (int i = 0; i < childCount; i++) {
7226                        String childPackageName = updatedPkg.childPackageNames.get(i);
7227                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7228                                childPackageName);
7229                        if (updatedChildPkg != null) {
7230                            updatedChildPkg.pkg = pkg;
7231                            updatedChildPkg.versionCode = pkg.mVersionCode;
7232                        }
7233                    }
7234
7235                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7236                            + scanFile + " ignored: updated version " + ps.versionCode
7237                            + " better than this " + pkg.mVersionCode);
7238                } else {
7239                    // The current app on the system partition is better than
7240                    // what we have updated to on the data partition; switch
7241                    // back to the system partition version.
7242                    // At this point, its safely assumed that package installation for
7243                    // apps in system partition will go through. If not there won't be a working
7244                    // version of the app
7245                    // writer
7246                    synchronized (mPackages) {
7247                        // Just remove the loaded entries from package lists.
7248                        mPackages.remove(ps.name);
7249                    }
7250
7251                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7252                            + " reverting from " + ps.codePathString
7253                            + ": new version " + pkg.mVersionCode
7254                            + " better than installed " + ps.versionCode);
7255
7256                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7257                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7258                    synchronized (mInstallLock) {
7259                        args.cleanUpResourcesLI();
7260                    }
7261                    synchronized (mPackages) {
7262                        mSettings.enableSystemPackageLPw(ps.name);
7263                    }
7264                    updatedPkgBetter = true;
7265                }
7266            }
7267        }
7268
7269        if (updatedPkg != null) {
7270            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7271            // initially
7272            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7273
7274            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7275            // flag set initially
7276            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7277                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7278            }
7279        }
7280
7281        // Verify certificates against what was last scanned
7282        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7283
7284        /*
7285         * A new system app appeared, but we already had a non-system one of the
7286         * same name installed earlier.
7287         */
7288        boolean shouldHideSystemApp = false;
7289        if (updatedPkg == null && ps != null
7290                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7291            /*
7292             * Check to make sure the signatures match first. If they don't,
7293             * wipe the installed application and its data.
7294             */
7295            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7296                    != PackageManager.SIGNATURE_MATCH) {
7297                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7298                        + " signatures don't match existing userdata copy; removing");
7299                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7300                        "scanPackageInternalLI")) {
7301                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7302                }
7303                ps = null;
7304            } else {
7305                /*
7306                 * If the newly-added system app is an older version than the
7307                 * already installed version, hide it. It will be scanned later
7308                 * and re-added like an update.
7309                 */
7310                if (pkg.mVersionCode <= ps.versionCode) {
7311                    shouldHideSystemApp = true;
7312                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7313                            + " but new version " + pkg.mVersionCode + " better than installed "
7314                            + ps.versionCode + "; hiding system");
7315                } else {
7316                    /*
7317                     * The newly found system app is a newer version that the
7318                     * one previously installed. Simply remove the
7319                     * already-installed application and replace it with our own
7320                     * while keeping the application data.
7321                     */
7322                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7323                            + " reverting from " + ps.codePathString + ": new version "
7324                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7325                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7326                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7327                    synchronized (mInstallLock) {
7328                        args.cleanUpResourcesLI();
7329                    }
7330                }
7331            }
7332        }
7333
7334        // The apk is forward locked (not public) if its code and resources
7335        // are kept in different files. (except for app in either system or
7336        // vendor path).
7337        // TODO grab this value from PackageSettings
7338        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7339            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7340                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7341            }
7342        }
7343
7344        // TODO: extend to support forward-locked splits
7345        String resourcePath = null;
7346        String baseResourcePath = null;
7347        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7348            if (ps != null && ps.resourcePathString != null) {
7349                resourcePath = ps.resourcePathString;
7350                baseResourcePath = ps.resourcePathString;
7351            } else {
7352                // Should not happen at all. Just log an error.
7353                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7354            }
7355        } else {
7356            resourcePath = pkg.codePath;
7357            baseResourcePath = pkg.baseCodePath;
7358        }
7359
7360        // Set application objects path explicitly.
7361        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7362        pkg.setApplicationInfoCodePath(pkg.codePath);
7363        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7364        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7365        pkg.setApplicationInfoResourcePath(resourcePath);
7366        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7367        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7368
7369        // Note that we invoke the following method only if we are about to unpack an application
7370        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7371                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7372
7373        /*
7374         * If the system app should be overridden by a previously installed
7375         * data, hide the system app now and let the /data/app scan pick it up
7376         * again.
7377         */
7378        if (shouldHideSystemApp) {
7379            synchronized (mPackages) {
7380                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7381            }
7382        }
7383
7384        return scannedPkg;
7385    }
7386
7387    private static String fixProcessName(String defProcessName,
7388            String processName) {
7389        if (processName == null) {
7390            return defProcessName;
7391        }
7392        return processName;
7393    }
7394
7395    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7396            throws PackageManagerException {
7397        if (pkgSetting.signatures.mSignatures != null) {
7398            // Already existing package. Make sure signatures match
7399            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7400                    == PackageManager.SIGNATURE_MATCH;
7401            if (!match) {
7402                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7403                        == PackageManager.SIGNATURE_MATCH;
7404            }
7405            if (!match) {
7406                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7407                        == PackageManager.SIGNATURE_MATCH;
7408            }
7409            if (!match) {
7410                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7411                        + pkg.packageName + " signatures do not match the "
7412                        + "previously installed version; ignoring!");
7413            }
7414        }
7415
7416        // Check for shared user signatures
7417        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7418            // Already existing package. Make sure signatures match
7419            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7420                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7421            if (!match) {
7422                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7423                        == PackageManager.SIGNATURE_MATCH;
7424            }
7425            if (!match) {
7426                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7427                        == PackageManager.SIGNATURE_MATCH;
7428            }
7429            if (!match) {
7430                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7431                        "Package " + pkg.packageName
7432                        + " has no signatures that match those in shared user "
7433                        + pkgSetting.sharedUser.name + "; ignoring!");
7434            }
7435        }
7436    }
7437
7438    /**
7439     * Enforces that only the system UID or root's UID can call a method exposed
7440     * via Binder.
7441     *
7442     * @param message used as message if SecurityException is thrown
7443     * @throws SecurityException if the caller is not system or root
7444     */
7445    private static final void enforceSystemOrRoot(String message) {
7446        final int uid = Binder.getCallingUid();
7447        if (uid != Process.SYSTEM_UID && uid != 0) {
7448            throw new SecurityException(message);
7449        }
7450    }
7451
7452    @Override
7453    public void performFstrimIfNeeded() {
7454        enforceSystemOrRoot("Only the system can request fstrim");
7455
7456        // Before everything else, see whether we need to fstrim.
7457        try {
7458            IStorageManager sm = PackageHelper.getStorageManager();
7459            if (sm != null) {
7460                boolean doTrim = false;
7461                final long interval = android.provider.Settings.Global.getLong(
7462                        mContext.getContentResolver(),
7463                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7464                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7465                if (interval > 0) {
7466                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7467                    if (timeSinceLast > interval) {
7468                        doTrim = true;
7469                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7470                                + "; running immediately");
7471                    }
7472                }
7473                if (doTrim) {
7474                    final boolean dexOptDialogShown;
7475                    synchronized (mPackages) {
7476                        dexOptDialogShown = mDexOptDialogShown;
7477                    }
7478                    if (!isFirstBoot() && dexOptDialogShown) {
7479                        try {
7480                            ActivityManager.getService().showBootMessage(
7481                                    mContext.getResources().getString(
7482                                            R.string.android_upgrading_fstrim), true);
7483                        } catch (RemoteException e) {
7484                        }
7485                    }
7486                    sm.runMaintenance();
7487                }
7488            } else {
7489                Slog.e(TAG, "storageManager service unavailable!");
7490            }
7491        } catch (RemoteException e) {
7492            // Can't happen; StorageManagerService is local
7493        }
7494    }
7495
7496    @Override
7497    public void updatePackagesIfNeeded() {
7498        enforceSystemOrRoot("Only the system can request package update");
7499
7500        // We need to re-extract after an OTA.
7501        boolean causeUpgrade = isUpgrade();
7502
7503        // First boot or factory reset.
7504        // Note: we also handle devices that are upgrading to N right now as if it is their
7505        //       first boot, as they do not have profile data.
7506        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7507
7508        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7509        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7510
7511        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7512            return;
7513        }
7514
7515        List<PackageParser.Package> pkgs;
7516        synchronized (mPackages) {
7517            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7518        }
7519
7520        final long startTime = System.nanoTime();
7521        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7522                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7523
7524        final int elapsedTimeSeconds =
7525                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7526
7527        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7528        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7529        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7530        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7531        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7532    }
7533
7534    /**
7535     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7536     * containing statistics about the invocation. The array consists of three elements,
7537     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7538     * and {@code numberOfPackagesFailed}.
7539     */
7540    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7541            String compilerFilter) {
7542
7543        int numberOfPackagesVisited = 0;
7544        int numberOfPackagesOptimized = 0;
7545        int numberOfPackagesSkipped = 0;
7546        int numberOfPackagesFailed = 0;
7547        final int numberOfPackagesToDexopt = pkgs.size();
7548
7549        for (PackageParser.Package pkg : pkgs) {
7550            numberOfPackagesVisited++;
7551
7552            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7553                if (DEBUG_DEXOPT) {
7554                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7555                }
7556                numberOfPackagesSkipped++;
7557                continue;
7558            }
7559
7560            if (DEBUG_DEXOPT) {
7561                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7562                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7563            }
7564
7565            if (showDialog) {
7566                try {
7567                    ActivityManager.getService().showBootMessage(
7568                            mContext.getResources().getString(R.string.android_upgrading_apk,
7569                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7570                } catch (RemoteException e) {
7571                }
7572                synchronized (mPackages) {
7573                    mDexOptDialogShown = true;
7574                }
7575            }
7576
7577            // If the OTA updates a system app which was previously preopted to a non-preopted state
7578            // the app might end up being verified at runtime. That's because by default the apps
7579            // are verify-profile but for preopted apps there's no profile.
7580            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7581            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7582            // filter (by default interpret-only).
7583            // Note that at this stage unused apps are already filtered.
7584            if (isSystemApp(pkg) &&
7585                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7586                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7587                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7588            }
7589
7590            // checkProfiles is false to avoid merging profiles during boot which
7591            // might interfere with background compilation (b/28612421).
7592            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7593            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7594            // trade-off worth doing to save boot time work.
7595            int dexOptStatus = performDexOptTraced(pkg.packageName,
7596                    false /* checkProfiles */,
7597                    compilerFilter,
7598                    false /* force */);
7599            switch (dexOptStatus) {
7600                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7601                    numberOfPackagesOptimized++;
7602                    break;
7603                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7604                    numberOfPackagesSkipped++;
7605                    break;
7606                case PackageDexOptimizer.DEX_OPT_FAILED:
7607                    numberOfPackagesFailed++;
7608                    break;
7609                default:
7610                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7611                    break;
7612            }
7613        }
7614
7615        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7616                numberOfPackagesFailed };
7617    }
7618
7619    @Override
7620    public void notifyPackageUse(String packageName, int reason) {
7621        synchronized (mPackages) {
7622            PackageParser.Package p = mPackages.get(packageName);
7623            if (p == null) {
7624                return;
7625            }
7626            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7627        }
7628    }
7629
7630    // TODO: this is not used nor needed. Delete it.
7631    @Override
7632    public boolean performDexOptIfNeeded(String packageName) {
7633        int dexOptStatus = performDexOptTraced(packageName,
7634                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7635        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7636    }
7637
7638    @Override
7639    public boolean performDexOpt(String packageName,
7640            boolean checkProfiles, int compileReason, boolean force) {
7641        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7642                getCompilerFilterForReason(compileReason), force);
7643        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7644    }
7645
7646    @Override
7647    public boolean performDexOptMode(String packageName,
7648            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7649        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7650                targetCompilerFilter, force);
7651        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7652    }
7653
7654    private int performDexOptTraced(String packageName,
7655                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7656        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7657        try {
7658            return performDexOptInternal(packageName, checkProfiles,
7659                    targetCompilerFilter, force);
7660        } finally {
7661            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7662        }
7663    }
7664
7665    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7666    // if the package can now be considered up to date for the given filter.
7667    private int performDexOptInternal(String packageName,
7668                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7669        PackageParser.Package p;
7670        synchronized (mPackages) {
7671            p = mPackages.get(packageName);
7672            if (p == null) {
7673                // Package could not be found. Report failure.
7674                return PackageDexOptimizer.DEX_OPT_FAILED;
7675            }
7676            mPackageUsage.maybeWriteAsync(mPackages);
7677            mCompilerStats.maybeWriteAsync();
7678        }
7679        long callingId = Binder.clearCallingIdentity();
7680        try {
7681            synchronized (mInstallLock) {
7682                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7683                        targetCompilerFilter, force);
7684            }
7685        } finally {
7686            Binder.restoreCallingIdentity(callingId);
7687        }
7688    }
7689
7690    public ArraySet<String> getOptimizablePackages() {
7691        ArraySet<String> pkgs = new ArraySet<String>();
7692        synchronized (mPackages) {
7693            for (PackageParser.Package p : mPackages.values()) {
7694                if (PackageDexOptimizer.canOptimizePackage(p)) {
7695                    pkgs.add(p.packageName);
7696                }
7697            }
7698        }
7699        return pkgs;
7700    }
7701
7702    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7703            boolean checkProfiles, String targetCompilerFilter,
7704            boolean force) {
7705        // Select the dex optimizer based on the force parameter.
7706        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7707        //       allocate an object here.
7708        PackageDexOptimizer pdo = force
7709                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7710                : mPackageDexOptimizer;
7711
7712        // Optimize all dependencies first. Note: we ignore the return value and march on
7713        // on errors.
7714        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7715        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7716        if (!deps.isEmpty()) {
7717            for (PackageParser.Package depPackage : deps) {
7718                // TODO: Analyze and investigate if we (should) profile libraries.
7719                // Currently this will do a full compilation of the library by default.
7720                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7721                        false /* checkProfiles */,
7722                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7723                        getOrCreateCompilerPackageStats(depPackage));
7724            }
7725        }
7726        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7727                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7728    }
7729
7730    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7731        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7732            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7733            Set<String> collectedNames = new HashSet<>();
7734            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7735
7736            retValue.remove(p);
7737
7738            return retValue;
7739        } else {
7740            return Collections.emptyList();
7741        }
7742    }
7743
7744    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7745            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7746        if (!collectedNames.contains(p.packageName)) {
7747            collectedNames.add(p.packageName);
7748            collected.add(p);
7749
7750            if (p.usesLibraries != null) {
7751                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7752            }
7753            if (p.usesOptionalLibraries != null) {
7754                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7755                        collectedNames);
7756            }
7757        }
7758    }
7759
7760    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7761            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7762        for (String libName : libs) {
7763            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7764            if (libPkg != null) {
7765                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7766            }
7767        }
7768    }
7769
7770    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7771        synchronized (mPackages) {
7772            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7773            if (lib != null && lib.apk != null) {
7774                return mPackages.get(lib.apk);
7775            }
7776        }
7777        return null;
7778    }
7779
7780    public void shutdown() {
7781        mPackageUsage.writeNow(mPackages);
7782        mCompilerStats.writeNow();
7783    }
7784
7785    @Override
7786    public void dumpProfiles(String packageName) {
7787        PackageParser.Package pkg;
7788        synchronized (mPackages) {
7789            pkg = mPackages.get(packageName);
7790            if (pkg == null) {
7791                throw new IllegalArgumentException("Unknown package: " + packageName);
7792            }
7793        }
7794        /* Only the shell, root, or the app user should be able to dump profiles. */
7795        int callingUid = Binder.getCallingUid();
7796        if (callingUid != Process.SHELL_UID &&
7797            callingUid != Process.ROOT_UID &&
7798            callingUid != pkg.applicationInfo.uid) {
7799            throw new SecurityException("dumpProfiles");
7800        }
7801
7802        synchronized (mInstallLock) {
7803            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7804            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7805            try {
7806                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7807                String codePaths = TextUtils.join(";", allCodePaths);
7808                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7809            } catch (InstallerException e) {
7810                Slog.w(TAG, "Failed to dump profiles", e);
7811            }
7812            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7813        }
7814    }
7815
7816    @Override
7817    public void forceDexOpt(String packageName) {
7818        enforceSystemOrRoot("forceDexOpt");
7819
7820        PackageParser.Package pkg;
7821        synchronized (mPackages) {
7822            pkg = mPackages.get(packageName);
7823            if (pkg == null) {
7824                throw new IllegalArgumentException("Unknown package: " + packageName);
7825            }
7826        }
7827
7828        synchronized (mInstallLock) {
7829            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7830
7831            // Whoever is calling forceDexOpt wants a fully compiled package.
7832            // Don't use profiles since that may cause compilation to be skipped.
7833            final int res = performDexOptInternalWithDependenciesLI(pkg,
7834                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7835                    true /* force */);
7836
7837            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7838            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7839                throw new IllegalStateException("Failed to dexopt: " + res);
7840            }
7841        }
7842    }
7843
7844    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7845        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7846            Slog.w(TAG, "Unable to update from " + oldPkg.name
7847                    + " to " + newPkg.packageName
7848                    + ": old package not in system partition");
7849            return false;
7850        } else if (mPackages.get(oldPkg.name) != null) {
7851            Slog.w(TAG, "Unable to update from " + oldPkg.name
7852                    + " to " + newPkg.packageName
7853                    + ": old package still exists");
7854            return false;
7855        }
7856        return true;
7857    }
7858
7859    void removeCodePathLI(File codePath) {
7860        if (codePath.isDirectory()) {
7861            try {
7862                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7863            } catch (InstallerException e) {
7864                Slog.w(TAG, "Failed to remove code path", e);
7865            }
7866        } else {
7867            codePath.delete();
7868        }
7869    }
7870
7871    private int[] resolveUserIds(int userId) {
7872        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7873    }
7874
7875    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7876        if (pkg == null) {
7877            Slog.wtf(TAG, "Package was null!", new Throwable());
7878            return;
7879        }
7880        clearAppDataLeafLIF(pkg, userId, flags);
7881        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7882        for (int i = 0; i < childCount; i++) {
7883            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7884        }
7885    }
7886
7887    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7888        final PackageSetting ps;
7889        synchronized (mPackages) {
7890            ps = mSettings.mPackages.get(pkg.packageName);
7891        }
7892        for (int realUserId : resolveUserIds(userId)) {
7893            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7894            try {
7895                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7896                        ceDataInode);
7897            } catch (InstallerException e) {
7898                Slog.w(TAG, String.valueOf(e));
7899            }
7900        }
7901    }
7902
7903    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7904        if (pkg == null) {
7905            Slog.wtf(TAG, "Package was null!", new Throwable());
7906            return;
7907        }
7908        destroyAppDataLeafLIF(pkg, userId, flags);
7909        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7910        for (int i = 0; i < childCount; i++) {
7911            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7912        }
7913    }
7914
7915    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7916        final PackageSetting ps;
7917        synchronized (mPackages) {
7918            ps = mSettings.mPackages.get(pkg.packageName);
7919        }
7920        for (int realUserId : resolveUserIds(userId)) {
7921            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7922            try {
7923                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7924                        ceDataInode);
7925            } catch (InstallerException e) {
7926                Slog.w(TAG, String.valueOf(e));
7927            }
7928        }
7929    }
7930
7931    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7932        if (pkg == null) {
7933            Slog.wtf(TAG, "Package was null!", new Throwable());
7934            return;
7935        }
7936        destroyAppProfilesLeafLIF(pkg);
7937        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7938        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7939        for (int i = 0; i < childCount; i++) {
7940            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7941            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7942                    true /* removeBaseMarker */);
7943        }
7944    }
7945
7946    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7947            boolean removeBaseMarker) {
7948        if (pkg.isForwardLocked()) {
7949            return;
7950        }
7951
7952        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7953            try {
7954                path = PackageManagerServiceUtils.realpath(new File(path));
7955            } catch (IOException e) {
7956                // TODO: Should we return early here ?
7957                Slog.w(TAG, "Failed to get canonical path", e);
7958                continue;
7959            }
7960
7961            final String useMarker = path.replace('/', '@');
7962            for (int realUserId : resolveUserIds(userId)) {
7963                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7964                if (removeBaseMarker) {
7965                    File foreignUseMark = new File(profileDir, useMarker);
7966                    if (foreignUseMark.exists()) {
7967                        if (!foreignUseMark.delete()) {
7968                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7969                                    + pkg.packageName);
7970                        }
7971                    }
7972                }
7973
7974                File[] markers = profileDir.listFiles();
7975                if (markers != null) {
7976                    final String searchString = "@" + pkg.packageName + "@";
7977                    // We also delete all markers that contain the package name we're
7978                    // uninstalling. These are associated with secondary dex-files belonging
7979                    // to the package. Reconstructing the path of these dex files is messy
7980                    // in general.
7981                    for (File marker : markers) {
7982                        if (marker.getName().indexOf(searchString) > 0) {
7983                            if (!marker.delete()) {
7984                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7985                                    + pkg.packageName);
7986                            }
7987                        }
7988                    }
7989                }
7990            }
7991        }
7992    }
7993
7994    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7995        try {
7996            mInstaller.destroyAppProfiles(pkg.packageName);
7997        } catch (InstallerException e) {
7998            Slog.w(TAG, String.valueOf(e));
7999        }
8000    }
8001
8002    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8003        if (pkg == null) {
8004            Slog.wtf(TAG, "Package was null!", new Throwable());
8005            return;
8006        }
8007        clearAppProfilesLeafLIF(pkg);
8008        // We don't remove the base foreign use marker when clearing profiles because
8009        // we will rename it when the app is updated. Unlike the actual profile contents,
8010        // the foreign use marker is good across installs.
8011        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8012        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8013        for (int i = 0; i < childCount; i++) {
8014            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8015        }
8016    }
8017
8018    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8019        try {
8020            mInstaller.clearAppProfiles(pkg.packageName);
8021        } catch (InstallerException e) {
8022            Slog.w(TAG, String.valueOf(e));
8023        }
8024    }
8025
8026    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8027            long lastUpdateTime) {
8028        // Set parent install/update time
8029        PackageSetting ps = (PackageSetting) pkg.mExtras;
8030        if (ps != null) {
8031            ps.firstInstallTime = firstInstallTime;
8032            ps.lastUpdateTime = lastUpdateTime;
8033        }
8034        // Set children install/update time
8035        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8036        for (int i = 0; i < childCount; i++) {
8037            PackageParser.Package childPkg = pkg.childPackages.get(i);
8038            ps = (PackageSetting) childPkg.mExtras;
8039            if (ps != null) {
8040                ps.firstInstallTime = firstInstallTime;
8041                ps.lastUpdateTime = lastUpdateTime;
8042            }
8043        }
8044    }
8045
8046    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8047            PackageParser.Package changingLib) {
8048        if (file.path != null) {
8049            usesLibraryFiles.add(file.path);
8050            return;
8051        }
8052        PackageParser.Package p = mPackages.get(file.apk);
8053        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8054            // If we are doing this while in the middle of updating a library apk,
8055            // then we need to make sure to use that new apk for determining the
8056            // dependencies here.  (We haven't yet finished committing the new apk
8057            // to the package manager state.)
8058            if (p == null || p.packageName.equals(changingLib.packageName)) {
8059                p = changingLib;
8060            }
8061        }
8062        if (p != null) {
8063            usesLibraryFiles.addAll(p.getAllCodePaths());
8064        }
8065    }
8066
8067    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8068            PackageParser.Package changingLib) throws PackageManagerException {
8069        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
8070            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8071            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8072            for (int i=0; i<N; i++) {
8073                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8074                if (file == null) {
8075                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8076                            "Package " + pkg.packageName + " requires unavailable shared library "
8077                            + pkg.usesLibraries.get(i) + "; failing!");
8078                }
8079                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8080            }
8081            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8082            for (int i=0; i<N; i++) {
8083                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8084                if (file == null) {
8085                    Slog.w(TAG, "Package " + pkg.packageName
8086                            + " desires unavailable shared library "
8087                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8088                } else {
8089                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8090                }
8091            }
8092            N = usesLibraryFiles.size();
8093            if (N > 0) {
8094                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8095            } else {
8096                pkg.usesLibraryFiles = null;
8097            }
8098        }
8099    }
8100
8101    private static boolean hasString(List<String> list, List<String> which) {
8102        if (list == null) {
8103            return false;
8104        }
8105        for (int i=list.size()-1; i>=0; i--) {
8106            for (int j=which.size()-1; j>=0; j--) {
8107                if (which.get(j).equals(list.get(i))) {
8108                    return true;
8109                }
8110            }
8111        }
8112        return false;
8113    }
8114
8115    private void updateAllSharedLibrariesLPw() {
8116        for (PackageParser.Package pkg : mPackages.values()) {
8117            try {
8118                updateSharedLibrariesLPr(pkg, null);
8119            } catch (PackageManagerException e) {
8120                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8121            }
8122        }
8123    }
8124
8125    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8126            PackageParser.Package changingPkg) {
8127        ArrayList<PackageParser.Package> res = null;
8128        for (PackageParser.Package pkg : mPackages.values()) {
8129            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8130                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8131                if (res == null) {
8132                    res = new ArrayList<PackageParser.Package>();
8133                }
8134                res.add(pkg);
8135                try {
8136                    updateSharedLibrariesLPr(pkg, changingPkg);
8137                } catch (PackageManagerException e) {
8138                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8139                }
8140            }
8141        }
8142        return res;
8143    }
8144
8145    /**
8146     * Derive the value of the {@code cpuAbiOverride} based on the provided
8147     * value and an optional stored value from the package settings.
8148     */
8149    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8150        String cpuAbiOverride = null;
8151
8152        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8153            cpuAbiOverride = null;
8154        } else if (abiOverride != null) {
8155            cpuAbiOverride = abiOverride;
8156        } else if (settings != null) {
8157            cpuAbiOverride = settings.cpuAbiOverrideString;
8158        }
8159
8160        return cpuAbiOverride;
8161    }
8162
8163    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8164            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8165                    throws PackageManagerException {
8166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8167        // If the package has children and this is the first dive in the function
8168        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8169        // whether all packages (parent and children) would be successfully scanned
8170        // before the actual scan since scanning mutates internal state and we want
8171        // to atomically install the package and its children.
8172        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8173            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8174                scanFlags |= SCAN_CHECK_ONLY;
8175            }
8176        } else {
8177            scanFlags &= ~SCAN_CHECK_ONLY;
8178        }
8179
8180        final PackageParser.Package scannedPkg;
8181        try {
8182            // Scan the parent
8183            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8184            // Scan the children
8185            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8186            for (int i = 0; i < childCount; i++) {
8187                PackageParser.Package childPkg = pkg.childPackages.get(i);
8188                scanPackageLI(childPkg, policyFlags,
8189                        scanFlags, currentTime, user);
8190            }
8191        } finally {
8192            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8193        }
8194
8195        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8196            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8197        }
8198
8199        return scannedPkg;
8200    }
8201
8202    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8203            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8204        boolean success = false;
8205        try {
8206            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8207                    currentTime, user);
8208            success = true;
8209            return res;
8210        } finally {
8211            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8212                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8213                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8214                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8215                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8216            }
8217        }
8218    }
8219
8220    /**
8221     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8222     */
8223    private static boolean apkHasCode(String fileName) {
8224        StrictJarFile jarFile = null;
8225        try {
8226            jarFile = new StrictJarFile(fileName,
8227                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8228            return jarFile.findEntry("classes.dex") != null;
8229        } catch (IOException ignore) {
8230        } finally {
8231            try {
8232                if (jarFile != null) {
8233                    jarFile.close();
8234                }
8235            } catch (IOException ignore) {}
8236        }
8237        return false;
8238    }
8239
8240    /**
8241     * Enforces code policy for the package. This ensures that if an APK has
8242     * declared hasCode="true" in its manifest that the APK actually contains
8243     * code.
8244     *
8245     * @throws PackageManagerException If bytecode could not be found when it should exist
8246     */
8247    private static void assertCodePolicy(PackageParser.Package pkg)
8248            throws PackageManagerException {
8249        final boolean shouldHaveCode =
8250                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8251        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8252            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8253                    "Package " + pkg.baseCodePath + " code is missing");
8254        }
8255
8256        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8257            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8258                final boolean splitShouldHaveCode =
8259                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8260                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8261                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8262                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8263                }
8264            }
8265        }
8266    }
8267
8268    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8269            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8270                    throws PackageManagerException {
8271        if (DEBUG_PACKAGE_SCANNING) {
8272            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8273                Log.d(TAG, "Scanning package " + pkg.packageName);
8274        }
8275
8276        applyPolicy(pkg, policyFlags);
8277
8278        assertPackageIsValid(pkg, policyFlags, scanFlags);
8279
8280        // Initialize package source and resource directories
8281        final File scanFile = new File(pkg.codePath);
8282        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8283        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8284
8285        SharedUserSetting suid = null;
8286        PackageSetting pkgSetting = null;
8287
8288        // Getting the package setting may have a side-effect, so if we
8289        // are only checking if scan would succeed, stash a copy of the
8290        // old setting to restore at the end.
8291        PackageSetting nonMutatedPs = null;
8292
8293        // We keep references to the derived CPU Abis from settings in oder to reuse
8294        // them in the case where we're not upgrading or booting for the first time.
8295        String primaryCpuAbiFromSettings = null;
8296        String secondaryCpuAbiFromSettings = null;
8297
8298        // writer
8299        synchronized (mPackages) {
8300            if (pkg.mSharedUserId != null) {
8301                // SIDE EFFECTS; may potentially allocate a new shared user
8302                suid = mSettings.getSharedUserLPw(
8303                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8304                if (DEBUG_PACKAGE_SCANNING) {
8305                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8306                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8307                                + "): packages=" + suid.packages);
8308                }
8309            }
8310
8311            // Check if we are renaming from an original package name.
8312            PackageSetting origPackage = null;
8313            String realName = null;
8314            if (pkg.mOriginalPackages != null) {
8315                // This package may need to be renamed to a previously
8316                // installed name.  Let's check on that...
8317                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8318                if (pkg.mOriginalPackages.contains(renamed)) {
8319                    // This package had originally been installed as the
8320                    // original name, and we have already taken care of
8321                    // transitioning to the new one.  Just update the new
8322                    // one to continue using the old name.
8323                    realName = pkg.mRealPackage;
8324                    if (!pkg.packageName.equals(renamed)) {
8325                        // Callers into this function may have already taken
8326                        // care of renaming the package; only do it here if
8327                        // it is not already done.
8328                        pkg.setPackageName(renamed);
8329                    }
8330                } else {
8331                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8332                        if ((origPackage = mSettings.getPackageLPr(
8333                                pkg.mOriginalPackages.get(i))) != null) {
8334                            // We do have the package already installed under its
8335                            // original name...  should we use it?
8336                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8337                                // New package is not compatible with original.
8338                                origPackage = null;
8339                                continue;
8340                            } else if (origPackage.sharedUser != null) {
8341                                // Make sure uid is compatible between packages.
8342                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8343                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8344                                            + " to " + pkg.packageName + ": old uid "
8345                                            + origPackage.sharedUser.name
8346                                            + " differs from " + pkg.mSharedUserId);
8347                                    origPackage = null;
8348                                    continue;
8349                                }
8350                                // TODO: Add case when shared user id is added [b/28144775]
8351                            } else {
8352                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8353                                        + pkg.packageName + " to old name " + origPackage.name);
8354                            }
8355                            break;
8356                        }
8357                    }
8358                }
8359            }
8360
8361            if (mTransferedPackages.contains(pkg.packageName)) {
8362                Slog.w(TAG, "Package " + pkg.packageName
8363                        + " was transferred to another, but its .apk remains");
8364            }
8365
8366            // See comments in nonMutatedPs declaration
8367            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8368                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8369                if (foundPs != null) {
8370                    nonMutatedPs = new PackageSetting(foundPs);
8371                }
8372            }
8373
8374            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8375                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8376                if (foundPs != null) {
8377                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8378                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8379                }
8380            }
8381
8382            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8383            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8384                PackageManagerService.reportSettingsProblem(Log.WARN,
8385                        "Package " + pkg.packageName + " shared user changed from "
8386                                + (pkgSetting.sharedUser != null
8387                                        ? pkgSetting.sharedUser.name : "<nothing>")
8388                                + " to "
8389                                + (suid != null ? suid.name : "<nothing>")
8390                                + "; replacing with new");
8391                pkgSetting = null;
8392            }
8393            final PackageSetting oldPkgSetting =
8394                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8395            final PackageSetting disabledPkgSetting =
8396                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8397            if (pkgSetting == null) {
8398                final String parentPackageName = (pkg.parentPackage != null)
8399                        ? pkg.parentPackage.packageName : null;
8400                // REMOVE SharedUserSetting from method; update in a separate call
8401                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8402                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8403                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8404                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8405                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8406                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8407                        UserManagerService.getInstance());
8408                // SIDE EFFECTS; updates system state; move elsewhere
8409                if (origPackage != null) {
8410                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8411                }
8412                mSettings.addUserToSettingLPw(pkgSetting);
8413            } else {
8414                // REMOVE SharedUserSetting from method; update in a separate call.
8415                //
8416                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8417                // secondaryCpuAbi are not known at this point so we always update them
8418                // to null here, only to reset them at a later point.
8419                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8420                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8421                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8422                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8423                        UserManagerService.getInstance());
8424            }
8425            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8426            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8427
8428            // SIDE EFFECTS; modifies system state; move elsewhere
8429            if (pkgSetting.origPackage != null) {
8430                // If we are first transitioning from an original package,
8431                // fix up the new package's name now.  We need to do this after
8432                // looking up the package under its new name, so getPackageLP
8433                // can take care of fiddling things correctly.
8434                pkg.setPackageName(origPackage.name);
8435
8436                // File a report about this.
8437                String msg = "New package " + pkgSetting.realName
8438                        + " renamed to replace old package " + pkgSetting.name;
8439                reportSettingsProblem(Log.WARN, msg);
8440
8441                // Make a note of it.
8442                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8443                    mTransferedPackages.add(origPackage.name);
8444                }
8445
8446                // No longer need to retain this.
8447                pkgSetting.origPackage = null;
8448            }
8449
8450            // SIDE EFFECTS; modifies system state; move elsewhere
8451            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8452                // Make a note of it.
8453                mTransferedPackages.add(pkg.packageName);
8454            }
8455
8456            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8457                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8458            }
8459
8460            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8461                // Check all shared libraries and map to their actual file path.
8462                // We only do this here for apps not on a system dir, because those
8463                // are the only ones that can fail an install due to this.  We
8464                // will take care of the system apps by updating all of their
8465                // library paths after the scan is done.
8466                updateSharedLibrariesLPr(pkg, null);
8467            }
8468
8469            if (mFoundPolicyFile) {
8470                SELinuxMMAC.assignSeinfoValue(pkg);
8471            }
8472
8473            pkg.applicationInfo.uid = pkgSetting.appId;
8474            pkg.mExtras = pkgSetting;
8475            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8476                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8477                    // We just determined the app is signed correctly, so bring
8478                    // over the latest parsed certs.
8479                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8480                } else {
8481                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8482                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8483                                "Package " + pkg.packageName + " upgrade keys do not match the "
8484                                + "previously installed version");
8485                    } else {
8486                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8487                        String msg = "System package " + pkg.packageName
8488                                + " signature changed; retaining data.";
8489                        reportSettingsProblem(Log.WARN, msg);
8490                    }
8491                }
8492            } else {
8493                try {
8494                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8495                    verifySignaturesLP(pkgSetting, pkg);
8496                    // We just determined the app is signed correctly, so bring
8497                    // over the latest parsed certs.
8498                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8499                } catch (PackageManagerException e) {
8500                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8501                        throw e;
8502                    }
8503                    // The signature has changed, but this package is in the system
8504                    // image...  let's recover!
8505                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8506                    // However...  if this package is part of a shared user, but it
8507                    // doesn't match the signature of the shared user, let's fail.
8508                    // What this means is that you can't change the signatures
8509                    // associated with an overall shared user, which doesn't seem all
8510                    // that unreasonable.
8511                    if (pkgSetting.sharedUser != null) {
8512                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8513                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8514                            throw new PackageManagerException(
8515                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8516                                    "Signature mismatch for shared user: "
8517                                            + pkgSetting.sharedUser);
8518                        }
8519                    }
8520                    // File a report about this.
8521                    String msg = "System package " + pkg.packageName
8522                            + " signature changed; retaining data.";
8523                    reportSettingsProblem(Log.WARN, msg);
8524                }
8525            }
8526
8527            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8528                // This package wants to adopt ownership of permissions from
8529                // another package.
8530                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8531                    final String origName = pkg.mAdoptPermissions.get(i);
8532                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8533                    if (orig != null) {
8534                        if (verifyPackageUpdateLPr(orig, pkg)) {
8535                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8536                                    + pkg.packageName);
8537                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8538                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8539                        }
8540                    }
8541                }
8542            }
8543        }
8544
8545        pkg.applicationInfo.processName = fixProcessName(
8546                pkg.applicationInfo.packageName,
8547                pkg.applicationInfo.processName);
8548
8549        if (pkg != mPlatformPackage) {
8550            // Get all of our default paths setup
8551            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8552        }
8553
8554        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8555
8556        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8557            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8558                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8559                derivePackageAbi(
8560                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8561                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8562
8563                // Some system apps still use directory structure for native libraries
8564                // in which case we might end up not detecting abi solely based on apk
8565                // structure. Try to detect abi based on directory structure.
8566                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8567                        pkg.applicationInfo.primaryCpuAbi == null) {
8568                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8569                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8570                }
8571            } else {
8572                // This is not a first boot or an upgrade, don't bother deriving the
8573                // ABI during the scan. Instead, trust the value that was stored in the
8574                // package setting.
8575                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8576                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8577
8578                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8579
8580                if (DEBUG_ABI_SELECTION) {
8581                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8582                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8583                        pkg.applicationInfo.secondaryCpuAbi);
8584                }
8585            }
8586        } else {
8587            if ((scanFlags & SCAN_MOVE) != 0) {
8588                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8589                // but we already have this packages package info in the PackageSetting. We just
8590                // use that and derive the native library path based on the new codepath.
8591                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8592                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8593            }
8594
8595            // Set native library paths again. For moves, the path will be updated based on the
8596            // ABIs we've determined above. For non-moves, the path will be updated based on the
8597            // ABIs we determined during compilation, but the path will depend on the final
8598            // package path (after the rename away from the stage path).
8599            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8600        }
8601
8602        // This is a special case for the "system" package, where the ABI is
8603        // dictated by the zygote configuration (and init.rc). We should keep track
8604        // of this ABI so that we can deal with "normal" applications that run under
8605        // the same UID correctly.
8606        if (mPlatformPackage == pkg) {
8607            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8608                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8609        }
8610
8611        // If there's a mismatch between the abi-override in the package setting
8612        // and the abiOverride specified for the install. Warn about this because we
8613        // would've already compiled the app without taking the package setting into
8614        // account.
8615        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8616            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8617                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8618                        " for package " + pkg.packageName);
8619            }
8620        }
8621
8622        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8623        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8624        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8625
8626        // Copy the derived override back to the parsed package, so that we can
8627        // update the package settings accordingly.
8628        pkg.cpuAbiOverride = cpuAbiOverride;
8629
8630        if (DEBUG_ABI_SELECTION) {
8631            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8632                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8633                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8634        }
8635
8636        // Push the derived path down into PackageSettings so we know what to
8637        // clean up at uninstall time.
8638        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8639
8640        if (DEBUG_ABI_SELECTION) {
8641            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8642                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8643                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8644        }
8645
8646        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8647        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8648            // We don't do this here during boot because we can do it all
8649            // at once after scanning all existing packages.
8650            //
8651            // We also do this *before* we perform dexopt on this package, so that
8652            // we can avoid redundant dexopts, and also to make sure we've got the
8653            // code and package path correct.
8654            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8655        }
8656
8657        if (mFactoryTest && pkg.requestedPermissions.contains(
8658                android.Manifest.permission.FACTORY_TEST)) {
8659            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8660        }
8661
8662        if (isSystemApp(pkg)) {
8663            pkgSetting.isOrphaned = true;
8664        }
8665
8666        // Take care of first install / last update times.
8667        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8668        if (currentTime != 0) {
8669            if (pkgSetting.firstInstallTime == 0) {
8670                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8671            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8672                pkgSetting.lastUpdateTime = currentTime;
8673            }
8674        } else if (pkgSetting.firstInstallTime == 0) {
8675            // We need *something*.  Take time time stamp of the file.
8676            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8677        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8678            if (scanFileTime != pkgSetting.timeStamp) {
8679                // A package on the system image has changed; consider this
8680                // to be an update.
8681                pkgSetting.lastUpdateTime = scanFileTime;
8682            }
8683        }
8684        pkgSetting.setTimeStamp(scanFileTime);
8685
8686        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8687            if (nonMutatedPs != null) {
8688                synchronized (mPackages) {
8689                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8690                }
8691            }
8692        } else {
8693            // Modify state for the given package setting
8694            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8695                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8696        }
8697        return pkg;
8698    }
8699
8700    /**
8701     * Applies policy to the parsed package based upon the given policy flags.
8702     * Ensures the package is in a good state.
8703     * <p>
8704     * Implementation detail: This method must NOT have any side effect. It would
8705     * ideally be static, but, it requires locks to read system state.
8706     */
8707    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8708        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8709            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8710            if (pkg.applicationInfo.isDirectBootAware()) {
8711                // we're direct boot aware; set for all components
8712                for (PackageParser.Service s : pkg.services) {
8713                    s.info.encryptionAware = s.info.directBootAware = true;
8714                }
8715                for (PackageParser.Provider p : pkg.providers) {
8716                    p.info.encryptionAware = p.info.directBootAware = true;
8717                }
8718                for (PackageParser.Activity a : pkg.activities) {
8719                    a.info.encryptionAware = a.info.directBootAware = true;
8720                }
8721                for (PackageParser.Activity r : pkg.receivers) {
8722                    r.info.encryptionAware = r.info.directBootAware = true;
8723                }
8724            }
8725        } else {
8726            // Only allow system apps to be flagged as core apps.
8727            pkg.coreApp = false;
8728            // clear flags not applicable to regular apps
8729            pkg.applicationInfo.privateFlags &=
8730                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8731            pkg.applicationInfo.privateFlags &=
8732                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8733        }
8734        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8735
8736        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8737            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8738        }
8739
8740        if (!isSystemApp(pkg)) {
8741            // Only system apps can use these features.
8742            pkg.mOriginalPackages = null;
8743            pkg.mRealPackage = null;
8744            pkg.mAdoptPermissions = null;
8745        }
8746    }
8747
8748    /**
8749     * Asserts the parsed package is valid according to teh given policy. If the
8750     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8751     * <p>
8752     * Implementation detail: This method must NOT have any side effects. It would
8753     * ideally be static, but, it requires locks to read system state.
8754     *
8755     * @throws PackageManagerException If the package fails any of the validation checks
8756     */
8757    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8758            throws PackageManagerException {
8759        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8760            assertCodePolicy(pkg);
8761        }
8762
8763        if (pkg.applicationInfo.getCodePath() == null ||
8764                pkg.applicationInfo.getResourcePath() == null) {
8765            // Bail out. The resource and code paths haven't been set.
8766            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8767                    "Code and resource paths haven't been set correctly");
8768        }
8769
8770        // Make sure we're not adding any bogus keyset info
8771        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8772        ksms.assertScannedPackageValid(pkg);
8773
8774        synchronized (mPackages) {
8775            // The special "android" package can only be defined once
8776            if (pkg.packageName.equals("android")) {
8777                if (mAndroidApplication != null) {
8778                    Slog.w(TAG, "*************************************************");
8779                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8780                    Slog.w(TAG, " codePath=" + pkg.codePath);
8781                    Slog.w(TAG, "*************************************************");
8782                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8783                            "Core android package being redefined.  Skipping.");
8784                }
8785            }
8786
8787            // A package name must be unique; don't allow duplicates
8788            if (mPackages.containsKey(pkg.packageName)
8789                    || mSharedLibraries.containsKey(pkg.packageName)) {
8790                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8791                        "Application package " + pkg.packageName
8792                        + " already installed.  Skipping duplicate.");
8793            }
8794
8795            // Only privileged apps and updated privileged apps can add child packages.
8796            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8797                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8798                    throw new PackageManagerException("Only privileged apps can add child "
8799                            + "packages. Ignoring package " + pkg.packageName);
8800                }
8801                final int childCount = pkg.childPackages.size();
8802                for (int i = 0; i < childCount; i++) {
8803                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8804                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8805                            childPkg.packageName)) {
8806                        throw new PackageManagerException("Can't override child of "
8807                                + "another disabled app. Ignoring package " + pkg.packageName);
8808                    }
8809                }
8810            }
8811
8812            // If we're only installing presumed-existing packages, require that the
8813            // scanned APK is both already known and at the path previously established
8814            // for it.  Previously unknown packages we pick up normally, but if we have an
8815            // a priori expectation about this package's install presence, enforce it.
8816            // With a singular exception for new system packages. When an OTA contains
8817            // a new system package, we allow the codepath to change from a system location
8818            // to the user-installed location. If we don't allow this change, any newer,
8819            // user-installed version of the application will be ignored.
8820            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8821                if (mExpectingBetter.containsKey(pkg.packageName)) {
8822                    logCriticalInfo(Log.WARN,
8823                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8824                } else {
8825                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8826                    if (known != null) {
8827                        if (DEBUG_PACKAGE_SCANNING) {
8828                            Log.d(TAG, "Examining " + pkg.codePath
8829                                    + " and requiring known paths " + known.codePathString
8830                                    + " & " + known.resourcePathString);
8831                        }
8832                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8833                                || !pkg.applicationInfo.getResourcePath().equals(
8834                                        known.resourcePathString)) {
8835                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8836                                    "Application package " + pkg.packageName
8837                                    + " found at " + pkg.applicationInfo.getCodePath()
8838                                    + " but expected at " + known.codePathString
8839                                    + "; ignoring.");
8840                        }
8841                    }
8842                }
8843            }
8844
8845            // Verify that this new package doesn't have any content providers
8846            // that conflict with existing packages.  Only do this if the
8847            // package isn't already installed, since we don't want to break
8848            // things that are installed.
8849            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8850                final int N = pkg.providers.size();
8851                int i;
8852                for (i=0; i<N; i++) {
8853                    PackageParser.Provider p = pkg.providers.get(i);
8854                    if (p.info.authority != null) {
8855                        String names[] = p.info.authority.split(";");
8856                        for (int j = 0; j < names.length; j++) {
8857                            if (mProvidersByAuthority.containsKey(names[j])) {
8858                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8859                                final String otherPackageName =
8860                                        ((other != null && other.getComponentName() != null) ?
8861                                                other.getComponentName().getPackageName() : "?");
8862                                throw new PackageManagerException(
8863                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8864                                        "Can't install because provider name " + names[j]
8865                                                + " (in package " + pkg.applicationInfo.packageName
8866                                                + ") is already used by " + otherPackageName);
8867                            }
8868                        }
8869                    }
8870                }
8871            }
8872        }
8873    }
8874
8875    /**
8876     * Adds a scanned package to the system. When this method is finished, the package will
8877     * be available for query, resolution, etc...
8878     */
8879    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8880            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8881        final String pkgName = pkg.packageName;
8882        if (mCustomResolverComponentName != null &&
8883                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8884            setUpCustomResolverActivity(pkg);
8885        }
8886
8887        if (pkg.packageName.equals("android")) {
8888            synchronized (mPackages) {
8889                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8890                    // Set up information for our fall-back user intent resolution activity.
8891                    mPlatformPackage = pkg;
8892                    pkg.mVersionCode = mSdkVersion;
8893                    mAndroidApplication = pkg.applicationInfo;
8894
8895                    if (!mResolverReplaced) {
8896                        mResolveActivity.applicationInfo = mAndroidApplication;
8897                        mResolveActivity.name = ResolverActivity.class.getName();
8898                        mResolveActivity.packageName = mAndroidApplication.packageName;
8899                        mResolveActivity.processName = "system:ui";
8900                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8901                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8902                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8903                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8904                        mResolveActivity.exported = true;
8905                        mResolveActivity.enabled = true;
8906                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8907                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8908                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8909                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8910                                | ActivityInfo.CONFIG_ORIENTATION
8911                                | ActivityInfo.CONFIG_KEYBOARD
8912                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8913                        mResolveInfo.activityInfo = mResolveActivity;
8914                        mResolveInfo.priority = 0;
8915                        mResolveInfo.preferredOrder = 0;
8916                        mResolveInfo.match = 0;
8917                        mResolveComponentName = new ComponentName(
8918                                mAndroidApplication.packageName, mResolveActivity.name);
8919                    }
8920                }
8921            }
8922        }
8923
8924        ArrayList<PackageParser.Package> clientLibPkgs = null;
8925        // writer
8926        synchronized (mPackages) {
8927            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8928                // Only system apps can add new shared libraries.
8929                if (pkg.libraryNames != null) {
8930                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8931                        String name = pkg.libraryNames.get(i);
8932                        boolean allowed = false;
8933                        if (pkg.isUpdatedSystemApp()) {
8934                            // New library entries can only be added through the
8935                            // system image.  This is important to get rid of a lot
8936                            // of nasty edge cases: for example if we allowed a non-
8937                            // system update of the app to add a library, then uninstalling
8938                            // the update would make the library go away, and assumptions
8939                            // we made such as through app install filtering would now
8940                            // have allowed apps on the device which aren't compatible
8941                            // with it.  Better to just have the restriction here, be
8942                            // conservative, and create many fewer cases that can negatively
8943                            // impact the user experience.
8944                            final PackageSetting sysPs = mSettings
8945                                    .getDisabledSystemPkgLPr(pkg.packageName);
8946                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8947                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8948                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8949                                        allowed = true;
8950                                        break;
8951                                    }
8952                                }
8953                            }
8954                        } else {
8955                            allowed = true;
8956                        }
8957                        if (allowed) {
8958                            if (!mSharedLibraries.containsKey(name)) {
8959                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8960                            } else if (!name.equals(pkg.packageName)) {
8961                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8962                                        + name + " already exists; skipping");
8963                            }
8964                        } else {
8965                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8966                                    + name + " that is not declared on system image; skipping");
8967                        }
8968                    }
8969                    if ((scanFlags & SCAN_BOOTING) == 0) {
8970                        // If we are not booting, we need to update any applications
8971                        // that are clients of our shared library.  If we are booting,
8972                        // this will all be done once the scan is complete.
8973                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8974                    }
8975                }
8976            }
8977        }
8978
8979        if ((scanFlags & SCAN_BOOTING) != 0) {
8980            // No apps can run during boot scan, so they don't need to be frozen
8981        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8982            // Caller asked to not kill app, so it's probably not frozen
8983        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8984            // Caller asked us to ignore frozen check for some reason; they
8985            // probably didn't know the package name
8986        } else {
8987            // We're doing major surgery on this package, so it better be frozen
8988            // right now to keep it from launching
8989            checkPackageFrozen(pkgName);
8990        }
8991
8992        // Also need to kill any apps that are dependent on the library.
8993        if (clientLibPkgs != null) {
8994            for (int i=0; i<clientLibPkgs.size(); i++) {
8995                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8996                killApplication(clientPkg.applicationInfo.packageName,
8997                        clientPkg.applicationInfo.uid, "update lib");
8998            }
8999        }
9000
9001        // writer
9002        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9003
9004        boolean createIdmapFailed = false;
9005        synchronized (mPackages) {
9006            // We don't expect installation to fail beyond this point
9007
9008            if (pkgSetting.pkg != null) {
9009                // Note that |user| might be null during the initial boot scan. If a codePath
9010                // for an app has changed during a boot scan, it's due to an app update that's
9011                // part of the system partition and marker changes must be applied to all users.
9012                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9013                final int[] userIds = resolveUserIds(userId);
9014                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9015            }
9016
9017            // Add the new setting to mSettings
9018            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9019            // Add the new setting to mPackages
9020            mPackages.put(pkg.applicationInfo.packageName, pkg);
9021            // Make sure we don't accidentally delete its data.
9022            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9023            while (iter.hasNext()) {
9024                PackageCleanItem item = iter.next();
9025                if (pkgName.equals(item.packageName)) {
9026                    iter.remove();
9027                }
9028            }
9029
9030            // Add the package's KeySets to the global KeySetManagerService
9031            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9032            ksms.addScannedPackageLPw(pkg);
9033
9034            int N = pkg.providers.size();
9035            StringBuilder r = null;
9036            int i;
9037            for (i=0; i<N; i++) {
9038                PackageParser.Provider p = pkg.providers.get(i);
9039                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9040                        p.info.processName);
9041                mProviders.addProvider(p);
9042                p.syncable = p.info.isSyncable;
9043                if (p.info.authority != null) {
9044                    String names[] = p.info.authority.split(";");
9045                    p.info.authority = null;
9046                    for (int j = 0; j < names.length; j++) {
9047                        if (j == 1 && p.syncable) {
9048                            // We only want the first authority for a provider to possibly be
9049                            // syncable, so if we already added this provider using a different
9050                            // authority clear the syncable flag. We copy the provider before
9051                            // changing it because the mProviders object contains a reference
9052                            // to a provider that we don't want to change.
9053                            // Only do this for the second authority since the resulting provider
9054                            // object can be the same for all future authorities for this provider.
9055                            p = new PackageParser.Provider(p);
9056                            p.syncable = false;
9057                        }
9058                        if (!mProvidersByAuthority.containsKey(names[j])) {
9059                            mProvidersByAuthority.put(names[j], p);
9060                            if (p.info.authority == null) {
9061                                p.info.authority = names[j];
9062                            } else {
9063                                p.info.authority = p.info.authority + ";" + names[j];
9064                            }
9065                            if (DEBUG_PACKAGE_SCANNING) {
9066                                if (chatty)
9067                                    Log.d(TAG, "Registered content provider: " + names[j]
9068                                            + ", className = " + p.info.name + ", isSyncable = "
9069                                            + p.info.isSyncable);
9070                            }
9071                        } else {
9072                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9073                            Slog.w(TAG, "Skipping provider name " + names[j] +
9074                                    " (in package " + pkg.applicationInfo.packageName +
9075                                    "): name already used by "
9076                                    + ((other != null && other.getComponentName() != null)
9077                                            ? other.getComponentName().getPackageName() : "?"));
9078                        }
9079                    }
9080                }
9081                if (chatty) {
9082                    if (r == null) {
9083                        r = new StringBuilder(256);
9084                    } else {
9085                        r.append(' ');
9086                    }
9087                    r.append(p.info.name);
9088                }
9089            }
9090            if (r != null) {
9091                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9092            }
9093
9094            N = pkg.services.size();
9095            r = null;
9096            for (i=0; i<N; i++) {
9097                PackageParser.Service s = pkg.services.get(i);
9098                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9099                        s.info.processName);
9100                mServices.addService(s);
9101                if (chatty) {
9102                    if (r == null) {
9103                        r = new StringBuilder(256);
9104                    } else {
9105                        r.append(' ');
9106                    }
9107                    r.append(s.info.name);
9108                }
9109            }
9110            if (r != null) {
9111                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9112            }
9113
9114            N = pkg.receivers.size();
9115            r = null;
9116            for (i=0; i<N; i++) {
9117                PackageParser.Activity a = pkg.receivers.get(i);
9118                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9119                        a.info.processName);
9120                mReceivers.addActivity(a, "receiver");
9121                if (chatty) {
9122                    if (r == null) {
9123                        r = new StringBuilder(256);
9124                    } else {
9125                        r.append(' ');
9126                    }
9127                    r.append(a.info.name);
9128                }
9129            }
9130            if (r != null) {
9131                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9132            }
9133
9134            N = pkg.activities.size();
9135            r = null;
9136            for (i=0; i<N; i++) {
9137                PackageParser.Activity a = pkg.activities.get(i);
9138                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9139                        a.info.processName);
9140                mActivities.addActivity(a, "activity");
9141                if (chatty) {
9142                    if (r == null) {
9143                        r = new StringBuilder(256);
9144                    } else {
9145                        r.append(' ');
9146                    }
9147                    r.append(a.info.name);
9148                }
9149            }
9150            if (r != null) {
9151                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9152            }
9153
9154            N = pkg.permissionGroups.size();
9155            r = null;
9156            for (i=0; i<N; i++) {
9157                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9158                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9159                final String curPackageName = cur == null ? null : cur.info.packageName;
9160                // Dont allow ephemeral apps to define new permission groups.
9161                if (pkg.applicationInfo.isEphemeralApp()) {
9162                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9163                            + pg.info.packageName
9164                            + " ignored: ephemeral apps cannot define new permission groups.");
9165                    continue;
9166                }
9167                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9168                if (cur == null || isPackageUpdate) {
9169                    mPermissionGroups.put(pg.info.name, pg);
9170                    if (chatty) {
9171                        if (r == null) {
9172                            r = new StringBuilder(256);
9173                        } else {
9174                            r.append(' ');
9175                        }
9176                        if (isPackageUpdate) {
9177                            r.append("UPD:");
9178                        }
9179                        r.append(pg.info.name);
9180                    }
9181                } else {
9182                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9183                            + pg.info.packageName + " ignored: original from "
9184                            + cur.info.packageName);
9185                    if (chatty) {
9186                        if (r == null) {
9187                            r = new StringBuilder(256);
9188                        } else {
9189                            r.append(' ');
9190                        }
9191                        r.append("DUP:");
9192                        r.append(pg.info.name);
9193                    }
9194                }
9195            }
9196            if (r != null) {
9197                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9198            }
9199
9200            N = pkg.permissions.size();
9201            r = null;
9202            for (i=0; i<N; i++) {
9203                PackageParser.Permission p = pkg.permissions.get(i);
9204
9205                // Dont allow ephemeral apps to define new permissions.
9206                if (pkg.applicationInfo.isEphemeralApp()) {
9207                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9208                            + p.info.packageName
9209                            + " ignored: ephemeral apps cannot define new permissions.");
9210                    continue;
9211                }
9212
9213                // Assume by default that we did not install this permission into the system.
9214                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9215
9216                // Now that permission groups have a special meaning, we ignore permission
9217                // groups for legacy apps to prevent unexpected behavior. In particular,
9218                // permissions for one app being granted to someone just becase they happen
9219                // to be in a group defined by another app (before this had no implications).
9220                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9221                    p.group = mPermissionGroups.get(p.info.group);
9222                    // Warn for a permission in an unknown group.
9223                    if (p.info.group != null && p.group == null) {
9224                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9225                                + p.info.packageName + " in an unknown group " + p.info.group);
9226                    }
9227                }
9228
9229                ArrayMap<String, BasePermission> permissionMap =
9230                        p.tree ? mSettings.mPermissionTrees
9231                                : mSettings.mPermissions;
9232                BasePermission bp = permissionMap.get(p.info.name);
9233
9234                // Allow system apps to redefine non-system permissions
9235                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9236                    final boolean currentOwnerIsSystem = (bp.perm != null
9237                            && isSystemApp(bp.perm.owner));
9238                    if (isSystemApp(p.owner)) {
9239                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9240                            // It's a built-in permission and no owner, take ownership now
9241                            bp.packageSetting = pkgSetting;
9242                            bp.perm = p;
9243                            bp.uid = pkg.applicationInfo.uid;
9244                            bp.sourcePackage = p.info.packageName;
9245                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9246                        } else if (!currentOwnerIsSystem) {
9247                            String msg = "New decl " + p.owner + " of permission  "
9248                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9249                            reportSettingsProblem(Log.WARN, msg);
9250                            bp = null;
9251                        }
9252                    }
9253                }
9254
9255                if (bp == null) {
9256                    bp = new BasePermission(p.info.name, p.info.packageName,
9257                            BasePermission.TYPE_NORMAL);
9258                    permissionMap.put(p.info.name, bp);
9259                }
9260
9261                if (bp.perm == null) {
9262                    if (bp.sourcePackage == null
9263                            || bp.sourcePackage.equals(p.info.packageName)) {
9264                        BasePermission tree = findPermissionTreeLP(p.info.name);
9265                        if (tree == null
9266                                || tree.sourcePackage.equals(p.info.packageName)) {
9267                            bp.packageSetting = pkgSetting;
9268                            bp.perm = p;
9269                            bp.uid = pkg.applicationInfo.uid;
9270                            bp.sourcePackage = p.info.packageName;
9271                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9272                            if (chatty) {
9273                                if (r == null) {
9274                                    r = new StringBuilder(256);
9275                                } else {
9276                                    r.append(' ');
9277                                }
9278                                r.append(p.info.name);
9279                            }
9280                        } else {
9281                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9282                                    + p.info.packageName + " ignored: base tree "
9283                                    + tree.name + " is from package "
9284                                    + tree.sourcePackage);
9285                        }
9286                    } else {
9287                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9288                                + p.info.packageName + " ignored: original from "
9289                                + bp.sourcePackage);
9290                    }
9291                } else if (chatty) {
9292                    if (r == null) {
9293                        r = new StringBuilder(256);
9294                    } else {
9295                        r.append(' ');
9296                    }
9297                    r.append("DUP:");
9298                    r.append(p.info.name);
9299                }
9300                if (bp.perm == p) {
9301                    bp.protectionLevel = p.info.protectionLevel;
9302                }
9303            }
9304
9305            if (r != null) {
9306                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9307            }
9308
9309            N = pkg.instrumentation.size();
9310            r = null;
9311            for (i=0; i<N; i++) {
9312                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9313                a.info.packageName = pkg.applicationInfo.packageName;
9314                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9315                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9316                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9317                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9318                a.info.dataDir = pkg.applicationInfo.dataDir;
9319                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9320                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9321                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9322                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9323                mInstrumentation.put(a.getComponentName(), a);
9324                if (chatty) {
9325                    if (r == null) {
9326                        r = new StringBuilder(256);
9327                    } else {
9328                        r.append(' ');
9329                    }
9330                    r.append(a.info.name);
9331                }
9332            }
9333            if (r != null) {
9334                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9335            }
9336
9337            if (pkg.protectedBroadcasts != null) {
9338                N = pkg.protectedBroadcasts.size();
9339                for (i=0; i<N; i++) {
9340                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9341                }
9342            }
9343
9344            // Create idmap files for pairs of (packages, overlay packages).
9345            // Note: "android", ie framework-res.apk, is handled by native layers.
9346            if (pkg.mOverlayTarget != null) {
9347                // This is an overlay package.
9348                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9349                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9350                        mOverlays.put(pkg.mOverlayTarget,
9351                                new ArrayMap<String, PackageParser.Package>());
9352                    }
9353                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9354                    map.put(pkg.packageName, pkg);
9355                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9356                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9357                        createIdmapFailed = true;
9358                    }
9359                }
9360            } else if (mOverlays.containsKey(pkg.packageName) &&
9361                    !pkg.packageName.equals("android")) {
9362                // This is a regular package, with one or more known overlay packages.
9363                createIdmapsForPackageLI(pkg);
9364            }
9365        }
9366
9367        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9368
9369        if (createIdmapFailed) {
9370            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9371                    "scanPackageLI failed to createIdmap");
9372        }
9373    }
9374
9375    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9376            PackageParser.Package update, int[] userIds) {
9377        if (existing.applicationInfo == null || update.applicationInfo == null) {
9378            // This isn't due to an app installation.
9379            return;
9380        }
9381
9382        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9383        final File newCodePath = new File(update.applicationInfo.getCodePath());
9384
9385        // The codePath hasn't changed, so there's nothing for us to do.
9386        if (Objects.equals(oldCodePath, newCodePath)) {
9387            return;
9388        }
9389
9390        File canonicalNewCodePath;
9391        try {
9392            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9393        } catch (IOException e) {
9394            Slog.w(TAG, "Failed to get canonical path.", e);
9395            return;
9396        }
9397
9398        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9399        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9400        // that the last component of the path (i.e, the name) doesn't need canonicalization
9401        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9402        // but may change in the future. Hopefully this function won't exist at that point.
9403        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9404                oldCodePath.getName());
9405
9406        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9407        // with "@".
9408        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9409        if (!oldMarkerPrefix.endsWith("@")) {
9410            oldMarkerPrefix += "@";
9411        }
9412        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9413        if (!newMarkerPrefix.endsWith("@")) {
9414            newMarkerPrefix += "@";
9415        }
9416
9417        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9418        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9419        for (String updatedPath : updatedPaths) {
9420            String updatedPathName = new File(updatedPath).getName();
9421            markerSuffixes.add(updatedPathName.replace('/', '@'));
9422        }
9423
9424        for (int userId : userIds) {
9425            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9426
9427            for (String markerSuffix : markerSuffixes) {
9428                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9429                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9430                if (oldForeignUseMark.exists()) {
9431                    try {
9432                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9433                                newForeignUseMark.getAbsolutePath());
9434                    } catch (ErrnoException e) {
9435                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9436                        oldForeignUseMark.delete();
9437                    }
9438                }
9439            }
9440        }
9441    }
9442
9443    /**
9444     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9445     * is derived purely on the basis of the contents of {@code scanFile} and
9446     * {@code cpuAbiOverride}.
9447     *
9448     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9449     */
9450    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9451                                 String cpuAbiOverride, boolean extractLibs,
9452                                 File appLib32InstallDir)
9453            throws PackageManagerException {
9454        // Give ourselves some initial paths; we'll come back for another
9455        // pass once we've determined ABI below.
9456        setNativeLibraryPaths(pkg, appLib32InstallDir);
9457
9458        // We would never need to extract libs for forward-locked and external packages,
9459        // since the container service will do it for us. We shouldn't attempt to
9460        // extract libs from system app when it was not updated.
9461        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9462                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9463            extractLibs = false;
9464        }
9465
9466        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9467        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9468
9469        NativeLibraryHelper.Handle handle = null;
9470        try {
9471            handle = NativeLibraryHelper.Handle.create(pkg);
9472            // TODO(multiArch): This can be null for apps that didn't go through the
9473            // usual installation process. We can calculate it again, like we
9474            // do during install time.
9475            //
9476            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9477            // unnecessary.
9478            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9479
9480            // Null out the abis so that they can be recalculated.
9481            pkg.applicationInfo.primaryCpuAbi = null;
9482            pkg.applicationInfo.secondaryCpuAbi = null;
9483            if (isMultiArch(pkg.applicationInfo)) {
9484                // Warn if we've set an abiOverride for multi-lib packages..
9485                // By definition, we need to copy both 32 and 64 bit libraries for
9486                // such packages.
9487                if (pkg.cpuAbiOverride != null
9488                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9489                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9490                }
9491
9492                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9493                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9494                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9495                    if (extractLibs) {
9496                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9497                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9498                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9499                                useIsaSpecificSubdirs);
9500                    } else {
9501                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9502                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9503                    }
9504                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9505                }
9506
9507                maybeThrowExceptionForMultiArchCopy(
9508                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9509
9510                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9511                    if (extractLibs) {
9512                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9513                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9514                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9515                                useIsaSpecificSubdirs);
9516                    } else {
9517                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9518                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9519                    }
9520                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9521                }
9522
9523                maybeThrowExceptionForMultiArchCopy(
9524                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9525
9526                if (abi64 >= 0) {
9527                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9528                }
9529
9530                if (abi32 >= 0) {
9531                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9532                    if (abi64 >= 0) {
9533                        if (pkg.use32bitAbi) {
9534                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9535                            pkg.applicationInfo.primaryCpuAbi = abi;
9536                        } else {
9537                            pkg.applicationInfo.secondaryCpuAbi = abi;
9538                        }
9539                    } else {
9540                        pkg.applicationInfo.primaryCpuAbi = abi;
9541                    }
9542                }
9543
9544            } else {
9545                String[] abiList = (cpuAbiOverride != null) ?
9546                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9547
9548                // Enable gross and lame hacks for apps that are built with old
9549                // SDK tools. We must scan their APKs for renderscript bitcode and
9550                // not launch them if it's present. Don't bother checking on devices
9551                // that don't have 64 bit support.
9552                boolean needsRenderScriptOverride = false;
9553                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9554                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9555                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9556                    needsRenderScriptOverride = true;
9557                }
9558
9559                final int copyRet;
9560                if (extractLibs) {
9561                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9562                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9563                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9564                } else {
9565                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9566                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9567                }
9568                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9569
9570                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9571                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9572                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9573                }
9574
9575                if (copyRet >= 0) {
9576                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9577                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9578                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9579                } else if (needsRenderScriptOverride) {
9580                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9581                }
9582            }
9583        } catch (IOException ioe) {
9584            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9585        } finally {
9586            IoUtils.closeQuietly(handle);
9587        }
9588
9589        // Now that we've calculated the ABIs and determined if it's an internal app,
9590        // we will go ahead and populate the nativeLibraryPath.
9591        setNativeLibraryPaths(pkg, appLib32InstallDir);
9592    }
9593
9594    /**
9595     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9596     * i.e, so that all packages can be run inside a single process if required.
9597     *
9598     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9599     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9600     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9601     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9602     * updating a package that belongs to a shared user.
9603     *
9604     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9605     * adds unnecessary complexity.
9606     */
9607    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9608            PackageParser.Package scannedPackage) {
9609        String requiredInstructionSet = null;
9610        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9611            requiredInstructionSet = VMRuntime.getInstructionSet(
9612                     scannedPackage.applicationInfo.primaryCpuAbi);
9613        }
9614
9615        PackageSetting requirer = null;
9616        for (PackageSetting ps : packagesForUser) {
9617            // If packagesForUser contains scannedPackage, we skip it. This will happen
9618            // when scannedPackage is an update of an existing package. Without this check,
9619            // we will never be able to change the ABI of any package belonging to a shared
9620            // user, even if it's compatible with other packages.
9621            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9622                if (ps.primaryCpuAbiString == null) {
9623                    continue;
9624                }
9625
9626                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9627                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9628                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9629                    // this but there's not much we can do.
9630                    String errorMessage = "Instruction set mismatch, "
9631                            + ((requirer == null) ? "[caller]" : requirer)
9632                            + " requires " + requiredInstructionSet + " whereas " + ps
9633                            + " requires " + instructionSet;
9634                    Slog.w(TAG, errorMessage);
9635                }
9636
9637                if (requiredInstructionSet == null) {
9638                    requiredInstructionSet = instructionSet;
9639                    requirer = ps;
9640                }
9641            }
9642        }
9643
9644        if (requiredInstructionSet != null) {
9645            String adjustedAbi;
9646            if (requirer != null) {
9647                // requirer != null implies that either scannedPackage was null or that scannedPackage
9648                // did not require an ABI, in which case we have to adjust scannedPackage to match
9649                // the ABI of the set (which is the same as requirer's ABI)
9650                adjustedAbi = requirer.primaryCpuAbiString;
9651                if (scannedPackage != null) {
9652                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9653                }
9654            } else {
9655                // requirer == null implies that we're updating all ABIs in the set to
9656                // match scannedPackage.
9657                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9658            }
9659
9660            for (PackageSetting ps : packagesForUser) {
9661                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9662                    if (ps.primaryCpuAbiString != null) {
9663                        continue;
9664                    }
9665
9666                    ps.primaryCpuAbiString = adjustedAbi;
9667                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9668                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9669                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9670                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9671                                + " (requirer="
9672                                + (requirer == null ? "null" : requirer.pkg.packageName)
9673                                + ", scannedPackage="
9674                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9675                                + ")");
9676                        try {
9677                            mInstaller.rmdex(ps.codePathString,
9678                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9679                        } catch (InstallerException ignored) {
9680                        }
9681                    }
9682                }
9683            }
9684        }
9685    }
9686
9687    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9688        synchronized (mPackages) {
9689            mResolverReplaced = true;
9690            // Set up information for custom user intent resolution activity.
9691            mResolveActivity.applicationInfo = pkg.applicationInfo;
9692            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9693            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9694            mResolveActivity.processName = pkg.applicationInfo.packageName;
9695            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9696            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9697                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9698            mResolveActivity.theme = 0;
9699            mResolveActivity.exported = true;
9700            mResolveActivity.enabled = true;
9701            mResolveInfo.activityInfo = mResolveActivity;
9702            mResolveInfo.priority = 0;
9703            mResolveInfo.preferredOrder = 0;
9704            mResolveInfo.match = 0;
9705            mResolveComponentName = mCustomResolverComponentName;
9706            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9707                    mResolveComponentName);
9708        }
9709    }
9710
9711    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9712        if (installerComponent == null) {
9713            if (DEBUG_EPHEMERAL) {
9714                Slog.d(TAG, "Clear ephemeral installer activity");
9715            }
9716            mEphemeralInstallerActivity.applicationInfo = null;
9717            return;
9718        }
9719
9720        if (DEBUG_EPHEMERAL) {
9721            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9722        }
9723        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9724        // Set up information for ephemeral installer activity
9725        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9726        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9727        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9728        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9729        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9730        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9731                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9732        mEphemeralInstallerActivity.theme = 0;
9733        mEphemeralInstallerActivity.exported = true;
9734        mEphemeralInstallerActivity.enabled = true;
9735        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9736        mEphemeralInstallerInfo.priority = 0;
9737        mEphemeralInstallerInfo.preferredOrder = 1;
9738        mEphemeralInstallerInfo.isDefault = true;
9739        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9740                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9741    }
9742
9743    private static String calculateBundledApkRoot(final String codePathString) {
9744        final File codePath = new File(codePathString);
9745        final File codeRoot;
9746        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9747            codeRoot = Environment.getRootDirectory();
9748        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9749            codeRoot = Environment.getOemDirectory();
9750        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9751            codeRoot = Environment.getVendorDirectory();
9752        } else {
9753            // Unrecognized code path; take its top real segment as the apk root:
9754            // e.g. /something/app/blah.apk => /something
9755            try {
9756                File f = codePath.getCanonicalFile();
9757                File parent = f.getParentFile();    // non-null because codePath is a file
9758                File tmp;
9759                while ((tmp = parent.getParentFile()) != null) {
9760                    f = parent;
9761                    parent = tmp;
9762                }
9763                codeRoot = f;
9764                Slog.w(TAG, "Unrecognized code path "
9765                        + codePath + " - using " + codeRoot);
9766            } catch (IOException e) {
9767                // Can't canonicalize the code path -- shenanigans?
9768                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9769                return Environment.getRootDirectory().getPath();
9770            }
9771        }
9772        return codeRoot.getPath();
9773    }
9774
9775    /**
9776     * Derive and set the location of native libraries for the given package,
9777     * which varies depending on where and how the package was installed.
9778     */
9779    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9780        final ApplicationInfo info = pkg.applicationInfo;
9781        final String codePath = pkg.codePath;
9782        final File codeFile = new File(codePath);
9783        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9784        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9785
9786        info.nativeLibraryRootDir = null;
9787        info.nativeLibraryRootRequiresIsa = false;
9788        info.nativeLibraryDir = null;
9789        info.secondaryNativeLibraryDir = null;
9790
9791        if (isApkFile(codeFile)) {
9792            // Monolithic install
9793            if (bundledApp) {
9794                // If "/system/lib64/apkname" exists, assume that is the per-package
9795                // native library directory to use; otherwise use "/system/lib/apkname".
9796                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9797                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9798                        getPrimaryInstructionSet(info));
9799
9800                // This is a bundled system app so choose the path based on the ABI.
9801                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9802                // is just the default path.
9803                final String apkName = deriveCodePathName(codePath);
9804                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9805                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9806                        apkName).getAbsolutePath();
9807
9808                if (info.secondaryCpuAbi != null) {
9809                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9810                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9811                            secondaryLibDir, apkName).getAbsolutePath();
9812                }
9813            } else if (asecApp) {
9814                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9815                        .getAbsolutePath();
9816            } else {
9817                final String apkName = deriveCodePathName(codePath);
9818                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9819                        .getAbsolutePath();
9820            }
9821
9822            info.nativeLibraryRootRequiresIsa = false;
9823            info.nativeLibraryDir = info.nativeLibraryRootDir;
9824        } else {
9825            // Cluster install
9826            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9827            info.nativeLibraryRootRequiresIsa = true;
9828
9829            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9830                    getPrimaryInstructionSet(info)).getAbsolutePath();
9831
9832            if (info.secondaryCpuAbi != null) {
9833                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9834                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9835            }
9836        }
9837    }
9838
9839    /**
9840     * Calculate the abis and roots for a bundled app. These can uniquely
9841     * be determined from the contents of the system partition, i.e whether
9842     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9843     * of this information, and instead assume that the system was built
9844     * sensibly.
9845     */
9846    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9847                                           PackageSetting pkgSetting) {
9848        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9849
9850        // If "/system/lib64/apkname" exists, assume that is the per-package
9851        // native library directory to use; otherwise use "/system/lib/apkname".
9852        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9853        setBundledAppAbi(pkg, apkRoot, apkName);
9854        // pkgSetting might be null during rescan following uninstall of updates
9855        // to a bundled app, so accommodate that possibility.  The settings in
9856        // that case will be established later from the parsed package.
9857        //
9858        // If the settings aren't null, sync them up with what we've just derived.
9859        // note that apkRoot isn't stored in the package settings.
9860        if (pkgSetting != null) {
9861            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9862            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9863        }
9864    }
9865
9866    /**
9867     * Deduces the ABI of a bundled app and sets the relevant fields on the
9868     * parsed pkg object.
9869     *
9870     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9871     *        under which system libraries are installed.
9872     * @param apkName the name of the installed package.
9873     */
9874    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9875        final File codeFile = new File(pkg.codePath);
9876
9877        final boolean has64BitLibs;
9878        final boolean has32BitLibs;
9879        if (isApkFile(codeFile)) {
9880            // Monolithic install
9881            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9882            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9883        } else {
9884            // Cluster install
9885            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9886            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9887                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9888                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9889                has64BitLibs = (new File(rootDir, isa)).exists();
9890            } else {
9891                has64BitLibs = false;
9892            }
9893            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9894                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9895                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9896                has32BitLibs = (new File(rootDir, isa)).exists();
9897            } else {
9898                has32BitLibs = false;
9899            }
9900        }
9901
9902        if (has64BitLibs && !has32BitLibs) {
9903            // The package has 64 bit libs, but not 32 bit libs. Its primary
9904            // ABI should be 64 bit. We can safely assume here that the bundled
9905            // native libraries correspond to the most preferred ABI in the list.
9906
9907            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9908            pkg.applicationInfo.secondaryCpuAbi = null;
9909        } else if (has32BitLibs && !has64BitLibs) {
9910            // The package has 32 bit libs but not 64 bit libs. Its primary
9911            // ABI should be 32 bit.
9912
9913            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9914            pkg.applicationInfo.secondaryCpuAbi = null;
9915        } else if (has32BitLibs && has64BitLibs) {
9916            // The application has both 64 and 32 bit bundled libraries. We check
9917            // here that the app declares multiArch support, and warn if it doesn't.
9918            //
9919            // We will be lenient here and record both ABIs. The primary will be the
9920            // ABI that's higher on the list, i.e, a device that's configured to prefer
9921            // 64 bit apps will see a 64 bit primary ABI,
9922
9923            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9924                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9925            }
9926
9927            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9928                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9929                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9930            } else {
9931                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9932                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9933            }
9934        } else {
9935            pkg.applicationInfo.primaryCpuAbi = null;
9936            pkg.applicationInfo.secondaryCpuAbi = null;
9937        }
9938    }
9939
9940    private void killApplication(String pkgName, int appId, String reason) {
9941        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9942    }
9943
9944    private void killApplication(String pkgName, int appId, int userId, String reason) {
9945        // Request the ActivityManager to kill the process(only for existing packages)
9946        // so that we do not end up in a confused state while the user is still using the older
9947        // version of the application while the new one gets installed.
9948        final long token = Binder.clearCallingIdentity();
9949        try {
9950            IActivityManager am = ActivityManager.getService();
9951            if (am != null) {
9952                try {
9953                    am.killApplication(pkgName, appId, userId, reason);
9954                } catch (RemoteException e) {
9955                }
9956            }
9957        } finally {
9958            Binder.restoreCallingIdentity(token);
9959        }
9960    }
9961
9962    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9963        // Remove the parent package setting
9964        PackageSetting ps = (PackageSetting) pkg.mExtras;
9965        if (ps != null) {
9966            removePackageLI(ps, chatty);
9967        }
9968        // Remove the child package setting
9969        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9970        for (int i = 0; i < childCount; i++) {
9971            PackageParser.Package childPkg = pkg.childPackages.get(i);
9972            ps = (PackageSetting) childPkg.mExtras;
9973            if (ps != null) {
9974                removePackageLI(ps, chatty);
9975            }
9976        }
9977    }
9978
9979    void removePackageLI(PackageSetting ps, boolean chatty) {
9980        if (DEBUG_INSTALL) {
9981            if (chatty)
9982                Log.d(TAG, "Removing package " + ps.name);
9983        }
9984
9985        // writer
9986        synchronized (mPackages) {
9987            mPackages.remove(ps.name);
9988            final PackageParser.Package pkg = ps.pkg;
9989            if (pkg != null) {
9990                cleanPackageDataStructuresLILPw(pkg, chatty);
9991            }
9992        }
9993    }
9994
9995    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9996        if (DEBUG_INSTALL) {
9997            if (chatty)
9998                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9999        }
10000
10001        // writer
10002        synchronized (mPackages) {
10003            // Remove the parent package
10004            mPackages.remove(pkg.applicationInfo.packageName);
10005            cleanPackageDataStructuresLILPw(pkg, chatty);
10006
10007            // Remove the child packages
10008            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10009            for (int i = 0; i < childCount; i++) {
10010                PackageParser.Package childPkg = pkg.childPackages.get(i);
10011                mPackages.remove(childPkg.applicationInfo.packageName);
10012                cleanPackageDataStructuresLILPw(childPkg, chatty);
10013            }
10014        }
10015    }
10016
10017    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10018        int N = pkg.providers.size();
10019        StringBuilder r = null;
10020        int i;
10021        for (i=0; i<N; i++) {
10022            PackageParser.Provider p = pkg.providers.get(i);
10023            mProviders.removeProvider(p);
10024            if (p.info.authority == null) {
10025
10026                /* There was another ContentProvider with this authority when
10027                 * this app was installed so this authority is null,
10028                 * Ignore it as we don't have to unregister the provider.
10029                 */
10030                continue;
10031            }
10032            String names[] = p.info.authority.split(";");
10033            for (int j = 0; j < names.length; j++) {
10034                if (mProvidersByAuthority.get(names[j]) == p) {
10035                    mProvidersByAuthority.remove(names[j]);
10036                    if (DEBUG_REMOVE) {
10037                        if (chatty)
10038                            Log.d(TAG, "Unregistered content provider: " + names[j]
10039                                    + ", className = " + p.info.name + ", isSyncable = "
10040                                    + p.info.isSyncable);
10041                    }
10042                }
10043            }
10044            if (DEBUG_REMOVE && chatty) {
10045                if (r == null) {
10046                    r = new StringBuilder(256);
10047                } else {
10048                    r.append(' ');
10049                }
10050                r.append(p.info.name);
10051            }
10052        }
10053        if (r != null) {
10054            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10055        }
10056
10057        N = pkg.services.size();
10058        r = null;
10059        for (i=0; i<N; i++) {
10060            PackageParser.Service s = pkg.services.get(i);
10061            mServices.removeService(s);
10062            if (chatty) {
10063                if (r == null) {
10064                    r = new StringBuilder(256);
10065                } else {
10066                    r.append(' ');
10067                }
10068                r.append(s.info.name);
10069            }
10070        }
10071        if (r != null) {
10072            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10073        }
10074
10075        N = pkg.receivers.size();
10076        r = null;
10077        for (i=0; i<N; i++) {
10078            PackageParser.Activity a = pkg.receivers.get(i);
10079            mReceivers.removeActivity(a, "receiver");
10080            if (DEBUG_REMOVE && chatty) {
10081                if (r == null) {
10082                    r = new StringBuilder(256);
10083                } else {
10084                    r.append(' ');
10085                }
10086                r.append(a.info.name);
10087            }
10088        }
10089        if (r != null) {
10090            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10091        }
10092
10093        N = pkg.activities.size();
10094        r = null;
10095        for (i=0; i<N; i++) {
10096            PackageParser.Activity a = pkg.activities.get(i);
10097            mActivities.removeActivity(a, "activity");
10098            if (DEBUG_REMOVE && chatty) {
10099                if (r == null) {
10100                    r = new StringBuilder(256);
10101                } else {
10102                    r.append(' ');
10103                }
10104                r.append(a.info.name);
10105            }
10106        }
10107        if (r != null) {
10108            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10109        }
10110
10111        N = pkg.permissions.size();
10112        r = null;
10113        for (i=0; i<N; i++) {
10114            PackageParser.Permission p = pkg.permissions.get(i);
10115            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10116            if (bp == null) {
10117                bp = mSettings.mPermissionTrees.get(p.info.name);
10118            }
10119            if (bp != null && bp.perm == p) {
10120                bp.perm = null;
10121                if (DEBUG_REMOVE && chatty) {
10122                    if (r == null) {
10123                        r = new StringBuilder(256);
10124                    } else {
10125                        r.append(' ');
10126                    }
10127                    r.append(p.info.name);
10128                }
10129            }
10130            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10131                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10132                if (appOpPkgs != null) {
10133                    appOpPkgs.remove(pkg.packageName);
10134                }
10135            }
10136        }
10137        if (r != null) {
10138            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10139        }
10140
10141        N = pkg.requestedPermissions.size();
10142        r = null;
10143        for (i=0; i<N; i++) {
10144            String perm = pkg.requestedPermissions.get(i);
10145            BasePermission bp = mSettings.mPermissions.get(perm);
10146            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10147                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10148                if (appOpPkgs != null) {
10149                    appOpPkgs.remove(pkg.packageName);
10150                    if (appOpPkgs.isEmpty()) {
10151                        mAppOpPermissionPackages.remove(perm);
10152                    }
10153                }
10154            }
10155        }
10156        if (r != null) {
10157            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10158        }
10159
10160        N = pkg.instrumentation.size();
10161        r = null;
10162        for (i=0; i<N; i++) {
10163            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10164            mInstrumentation.remove(a.getComponentName());
10165            if (DEBUG_REMOVE && chatty) {
10166                if (r == null) {
10167                    r = new StringBuilder(256);
10168                } else {
10169                    r.append(' ');
10170                }
10171                r.append(a.info.name);
10172            }
10173        }
10174        if (r != null) {
10175            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10176        }
10177
10178        r = null;
10179        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10180            // Only system apps can hold shared libraries.
10181            if (pkg.libraryNames != null) {
10182                for (i=0; i<pkg.libraryNames.size(); i++) {
10183                    String name = pkg.libraryNames.get(i);
10184                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10185                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10186                        mSharedLibraries.remove(name);
10187                        if (DEBUG_REMOVE && chatty) {
10188                            if (r == null) {
10189                                r = new StringBuilder(256);
10190                            } else {
10191                                r.append(' ');
10192                            }
10193                            r.append(name);
10194                        }
10195                    }
10196                }
10197            }
10198        }
10199        if (r != null) {
10200            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10201        }
10202    }
10203
10204    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10205        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10206            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10207                return true;
10208            }
10209        }
10210        return false;
10211    }
10212
10213    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10214    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10215    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10216
10217    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10218        // Update the parent permissions
10219        updatePermissionsLPw(pkg.packageName, pkg, flags);
10220        // Update the child permissions
10221        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10222        for (int i = 0; i < childCount; i++) {
10223            PackageParser.Package childPkg = pkg.childPackages.get(i);
10224            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10225        }
10226    }
10227
10228    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10229            int flags) {
10230        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10231        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10232    }
10233
10234    private void updatePermissionsLPw(String changingPkg,
10235            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10236        // Make sure there are no dangling permission trees.
10237        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10238        while (it.hasNext()) {
10239            final BasePermission bp = it.next();
10240            if (bp.packageSetting == null) {
10241                // We may not yet have parsed the package, so just see if
10242                // we still know about its settings.
10243                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10244            }
10245            if (bp.packageSetting == null) {
10246                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10247                        + " from package " + bp.sourcePackage);
10248                it.remove();
10249            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10250                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10251                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10252                            + " from package " + bp.sourcePackage);
10253                    flags |= UPDATE_PERMISSIONS_ALL;
10254                    it.remove();
10255                }
10256            }
10257        }
10258
10259        // Make sure all dynamic permissions have been assigned to a package,
10260        // and make sure there are no dangling permissions.
10261        it = mSettings.mPermissions.values().iterator();
10262        while (it.hasNext()) {
10263            final BasePermission bp = it.next();
10264            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10265                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10266                        + bp.name + " pkg=" + bp.sourcePackage
10267                        + " info=" + bp.pendingInfo);
10268                if (bp.packageSetting == null && bp.pendingInfo != null) {
10269                    final BasePermission tree = findPermissionTreeLP(bp.name);
10270                    if (tree != null && tree.perm != null) {
10271                        bp.packageSetting = tree.packageSetting;
10272                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10273                                new PermissionInfo(bp.pendingInfo));
10274                        bp.perm.info.packageName = tree.perm.info.packageName;
10275                        bp.perm.info.name = bp.name;
10276                        bp.uid = tree.uid;
10277                    }
10278                }
10279            }
10280            if (bp.packageSetting == null) {
10281                // We may not yet have parsed the package, so just see if
10282                // we still know about its settings.
10283                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10284            }
10285            if (bp.packageSetting == null) {
10286                Slog.w(TAG, "Removing dangling permission: " + bp.name
10287                        + " from package " + bp.sourcePackage);
10288                it.remove();
10289            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10290                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10291                    Slog.i(TAG, "Removing old permission: " + bp.name
10292                            + " from package " + bp.sourcePackage);
10293                    flags |= UPDATE_PERMISSIONS_ALL;
10294                    it.remove();
10295                }
10296            }
10297        }
10298
10299        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10300        // Now update the permissions for all packages, in particular
10301        // replace the granted permissions of the system packages.
10302        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10303            for (PackageParser.Package pkg : mPackages.values()) {
10304                if (pkg != pkgInfo) {
10305                    // Only replace for packages on requested volume
10306                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10307                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10308                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10309                    grantPermissionsLPw(pkg, replace, changingPkg);
10310                }
10311            }
10312        }
10313
10314        if (pkgInfo != null) {
10315            // Only replace for packages on requested volume
10316            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10317            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10318                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10319            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10320        }
10321        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10322    }
10323
10324    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10325            String packageOfInterest) {
10326        // IMPORTANT: There are two types of permissions: install and runtime.
10327        // Install time permissions are granted when the app is installed to
10328        // all device users and users added in the future. Runtime permissions
10329        // are granted at runtime explicitly to specific users. Normal and signature
10330        // protected permissions are install time permissions. Dangerous permissions
10331        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10332        // otherwise they are runtime permissions. This function does not manage
10333        // runtime permissions except for the case an app targeting Lollipop MR1
10334        // being upgraded to target a newer SDK, in which case dangerous permissions
10335        // are transformed from install time to runtime ones.
10336
10337        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10338        if (ps == null) {
10339            return;
10340        }
10341
10342        PermissionsState permissionsState = ps.getPermissionsState();
10343        PermissionsState origPermissions = permissionsState;
10344
10345        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10346
10347        boolean runtimePermissionsRevoked = false;
10348        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10349
10350        boolean changedInstallPermission = false;
10351
10352        if (replace) {
10353            ps.installPermissionsFixed = false;
10354            if (!ps.isSharedUser()) {
10355                origPermissions = new PermissionsState(permissionsState);
10356                permissionsState.reset();
10357            } else {
10358                // We need to know only about runtime permission changes since the
10359                // calling code always writes the install permissions state but
10360                // the runtime ones are written only if changed. The only cases of
10361                // changed runtime permissions here are promotion of an install to
10362                // runtime and revocation of a runtime from a shared user.
10363                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10364                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10365                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10366                    runtimePermissionsRevoked = true;
10367                }
10368            }
10369        }
10370
10371        permissionsState.setGlobalGids(mGlobalGids);
10372
10373        final int N = pkg.requestedPermissions.size();
10374        for (int i=0; i<N; i++) {
10375            final String name = pkg.requestedPermissions.get(i);
10376            final BasePermission bp = mSettings.mPermissions.get(name);
10377
10378            if (DEBUG_INSTALL) {
10379                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10380            }
10381
10382            if (bp == null || bp.packageSetting == null) {
10383                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10384                    Slog.w(TAG, "Unknown permission " + name
10385                            + " in package " + pkg.packageName);
10386                }
10387                continue;
10388            }
10389
10390
10391            // Limit ephemeral apps to ephemeral allowed permissions.
10392            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10393                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10394                        + pkg.packageName);
10395                continue;
10396            }
10397
10398            final String perm = bp.name;
10399            boolean allowedSig = false;
10400            int grant = GRANT_DENIED;
10401
10402            // Keep track of app op permissions.
10403            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10404                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10405                if (pkgs == null) {
10406                    pkgs = new ArraySet<>();
10407                    mAppOpPermissionPackages.put(bp.name, pkgs);
10408                }
10409                pkgs.add(pkg.packageName);
10410            }
10411
10412            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10413            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10414                    >= Build.VERSION_CODES.M;
10415            switch (level) {
10416                case PermissionInfo.PROTECTION_NORMAL: {
10417                    // For all apps normal permissions are install time ones.
10418                    grant = GRANT_INSTALL;
10419                } break;
10420
10421                case PermissionInfo.PROTECTION_DANGEROUS: {
10422                    // If a permission review is required for legacy apps we represent
10423                    // their permissions as always granted runtime ones since we need
10424                    // to keep the review required permission flag per user while an
10425                    // install permission's state is shared across all users.
10426                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10427                        // For legacy apps dangerous permissions are install time ones.
10428                        grant = GRANT_INSTALL;
10429                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10430                        // For legacy apps that became modern, install becomes runtime.
10431                        grant = GRANT_UPGRADE;
10432                    } else if (mPromoteSystemApps
10433                            && isSystemApp(ps)
10434                            && mExistingSystemPackages.contains(ps.name)) {
10435                        // For legacy system apps, install becomes runtime.
10436                        // We cannot check hasInstallPermission() for system apps since those
10437                        // permissions were granted implicitly and not persisted pre-M.
10438                        grant = GRANT_UPGRADE;
10439                    } else {
10440                        // For modern apps keep runtime permissions unchanged.
10441                        grant = GRANT_RUNTIME;
10442                    }
10443                } break;
10444
10445                case PermissionInfo.PROTECTION_SIGNATURE: {
10446                    // For all apps signature permissions are install time ones.
10447                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10448                    if (allowedSig) {
10449                        grant = GRANT_INSTALL;
10450                    }
10451                } break;
10452            }
10453
10454            if (DEBUG_INSTALL) {
10455                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10456            }
10457
10458            if (grant != GRANT_DENIED) {
10459                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10460                    // If this is an existing, non-system package, then
10461                    // we can't add any new permissions to it.
10462                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10463                        // Except...  if this is a permission that was added
10464                        // to the platform (note: need to only do this when
10465                        // updating the platform).
10466                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10467                            grant = GRANT_DENIED;
10468                        }
10469                    }
10470                }
10471
10472                switch (grant) {
10473                    case GRANT_INSTALL: {
10474                        // Revoke this as runtime permission to handle the case of
10475                        // a runtime permission being downgraded to an install one.
10476                        // Also in permission review mode we keep dangerous permissions
10477                        // for legacy apps
10478                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10479                            if (origPermissions.getRuntimePermissionState(
10480                                    bp.name, userId) != null) {
10481                                // Revoke the runtime permission and clear the flags.
10482                                origPermissions.revokeRuntimePermission(bp, userId);
10483                                origPermissions.updatePermissionFlags(bp, userId,
10484                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10485                                // If we revoked a permission permission, we have to write.
10486                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10487                                        changedRuntimePermissionUserIds, userId);
10488                            }
10489                        }
10490                        // Grant an install permission.
10491                        if (permissionsState.grantInstallPermission(bp) !=
10492                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10493                            changedInstallPermission = true;
10494                        }
10495                    } break;
10496
10497                    case GRANT_RUNTIME: {
10498                        // Grant previously granted runtime permissions.
10499                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10500                            PermissionState permissionState = origPermissions
10501                                    .getRuntimePermissionState(bp.name, userId);
10502                            int flags = permissionState != null
10503                                    ? permissionState.getFlags() : 0;
10504                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10505                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10506                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10507                                    // If we cannot put the permission as it was, we have to write.
10508                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10509                                            changedRuntimePermissionUserIds, userId);
10510                                }
10511                                // If the app supports runtime permissions no need for a review.
10512                                if (mPermissionReviewRequired
10513                                        && appSupportsRuntimePermissions
10514                                        && (flags & PackageManager
10515                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10516                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10517                                    // Since we changed the flags, we have to write.
10518                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10519                                            changedRuntimePermissionUserIds, userId);
10520                                }
10521                            } else if (mPermissionReviewRequired
10522                                    && !appSupportsRuntimePermissions) {
10523                                // For legacy apps that need a permission review, every new
10524                                // runtime permission is granted but it is pending a review.
10525                                // We also need to review only platform defined runtime
10526                                // permissions as these are the only ones the platform knows
10527                                // how to disable the API to simulate revocation as legacy
10528                                // apps don't expect to run with revoked permissions.
10529                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10530                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10531                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10532                                        // We changed the flags, hence have to write.
10533                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10534                                                changedRuntimePermissionUserIds, userId);
10535                                    }
10536                                }
10537                                if (permissionsState.grantRuntimePermission(bp, userId)
10538                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10539                                    // We changed the permission, hence have to write.
10540                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10541                                            changedRuntimePermissionUserIds, userId);
10542                                }
10543                            }
10544                            // Propagate the permission flags.
10545                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10546                        }
10547                    } break;
10548
10549                    case GRANT_UPGRADE: {
10550                        // Grant runtime permissions for a previously held install permission.
10551                        PermissionState permissionState = origPermissions
10552                                .getInstallPermissionState(bp.name);
10553                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10554
10555                        if (origPermissions.revokeInstallPermission(bp)
10556                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10557                            // We will be transferring the permission flags, so clear them.
10558                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10559                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10560                            changedInstallPermission = true;
10561                        }
10562
10563                        // If the permission is not to be promoted to runtime we ignore it and
10564                        // also its other flags as they are not applicable to install permissions.
10565                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10566                            for (int userId : currentUserIds) {
10567                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10568                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10569                                    // Transfer the permission flags.
10570                                    permissionsState.updatePermissionFlags(bp, userId,
10571                                            flags, flags);
10572                                    // If we granted the permission, we have to write.
10573                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10574                                            changedRuntimePermissionUserIds, userId);
10575                                }
10576                            }
10577                        }
10578                    } break;
10579
10580                    default: {
10581                        if (packageOfInterest == null
10582                                || packageOfInterest.equals(pkg.packageName)) {
10583                            Slog.w(TAG, "Not granting permission " + perm
10584                                    + " to package " + pkg.packageName
10585                                    + " because it was previously installed without");
10586                        }
10587                    } break;
10588                }
10589            } else {
10590                if (permissionsState.revokeInstallPermission(bp) !=
10591                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10592                    // Also drop the permission flags.
10593                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10594                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10595                    changedInstallPermission = true;
10596                    Slog.i(TAG, "Un-granting permission " + perm
10597                            + " from package " + pkg.packageName
10598                            + " (protectionLevel=" + bp.protectionLevel
10599                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10600                            + ")");
10601                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10602                    // Don't print warning for app op permissions, since it is fine for them
10603                    // not to be granted, there is a UI for the user to decide.
10604                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10605                        Slog.w(TAG, "Not granting permission " + perm
10606                                + " to package " + pkg.packageName
10607                                + " (protectionLevel=" + bp.protectionLevel
10608                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10609                                + ")");
10610                    }
10611                }
10612            }
10613        }
10614
10615        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10616                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10617            // This is the first that we have heard about this package, so the
10618            // permissions we have now selected are fixed until explicitly
10619            // changed.
10620            ps.installPermissionsFixed = true;
10621        }
10622
10623        // Persist the runtime permissions state for users with changes. If permissions
10624        // were revoked because no app in the shared user declares them we have to
10625        // write synchronously to avoid losing runtime permissions state.
10626        for (int userId : changedRuntimePermissionUserIds) {
10627            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10628        }
10629    }
10630
10631    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10632        boolean allowed = false;
10633        final int NP = PackageParser.NEW_PERMISSIONS.length;
10634        for (int ip=0; ip<NP; ip++) {
10635            final PackageParser.NewPermissionInfo npi
10636                    = PackageParser.NEW_PERMISSIONS[ip];
10637            if (npi.name.equals(perm)
10638                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10639                allowed = true;
10640                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10641                        + pkg.packageName);
10642                break;
10643            }
10644        }
10645        return allowed;
10646    }
10647
10648    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10649            BasePermission bp, PermissionsState origPermissions) {
10650        boolean privilegedPermission = (bp.protectionLevel
10651                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10652        boolean privappPermissionsDisable =
10653                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10654        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10655        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10656        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10657                && !platformPackage && platformPermission) {
10658            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10659                    .getPrivAppPermissions(pkg.packageName);
10660            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10661            if (!whitelisted) {
10662                Slog.w(TAG, "Privileged permission " + perm + " for package "
10663                        + pkg.packageName + " - not in privapp-permissions whitelist");
10664                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10665                    return false;
10666                }
10667            }
10668        }
10669        boolean allowed = (compareSignatures(
10670                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10671                        == PackageManager.SIGNATURE_MATCH)
10672                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10673                        == PackageManager.SIGNATURE_MATCH);
10674        if (!allowed && privilegedPermission) {
10675            if (isSystemApp(pkg)) {
10676                // For updated system applications, a system permission
10677                // is granted only if it had been defined by the original application.
10678                if (pkg.isUpdatedSystemApp()) {
10679                    final PackageSetting sysPs = mSettings
10680                            .getDisabledSystemPkgLPr(pkg.packageName);
10681                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10682                        // If the original was granted this permission, we take
10683                        // that grant decision as read and propagate it to the
10684                        // update.
10685                        if (sysPs.isPrivileged()) {
10686                            allowed = true;
10687                        }
10688                    } else {
10689                        // The system apk may have been updated with an older
10690                        // version of the one on the data partition, but which
10691                        // granted a new system permission that it didn't have
10692                        // before.  In this case we do want to allow the app to
10693                        // now get the new permission if the ancestral apk is
10694                        // privileged to get it.
10695                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10696                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10697                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10698                                    allowed = true;
10699                                    break;
10700                                }
10701                            }
10702                        }
10703                        // Also if a privileged parent package on the system image or any of
10704                        // its children requested a privileged permission, the updated child
10705                        // packages can also get the permission.
10706                        if (pkg.parentPackage != null) {
10707                            final PackageSetting disabledSysParentPs = mSettings
10708                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10709                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10710                                    && disabledSysParentPs.isPrivileged()) {
10711                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10712                                    allowed = true;
10713                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10714                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10715                                    for (int i = 0; i < count; i++) {
10716                                        PackageParser.Package disabledSysChildPkg =
10717                                                disabledSysParentPs.pkg.childPackages.get(i);
10718                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10719                                                perm)) {
10720                                            allowed = true;
10721                                            break;
10722                                        }
10723                                    }
10724                                }
10725                            }
10726                        }
10727                    }
10728                } else {
10729                    allowed = isPrivilegedApp(pkg);
10730                }
10731            }
10732        }
10733        if (!allowed) {
10734            if (!allowed && (bp.protectionLevel
10735                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10736                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10737                // If this was a previously normal/dangerous permission that got moved
10738                // to a system permission as part of the runtime permission redesign, then
10739                // we still want to blindly grant it to old apps.
10740                allowed = true;
10741            }
10742            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10743                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10744                // If this permission is to be granted to the system installer and
10745                // this app is an installer, then it gets the permission.
10746                allowed = true;
10747            }
10748            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10749                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10750                // If this permission is to be granted to the system verifier and
10751                // this app is a verifier, then it gets the permission.
10752                allowed = true;
10753            }
10754            if (!allowed && (bp.protectionLevel
10755                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10756                    && isSystemApp(pkg)) {
10757                // Any pre-installed system app is allowed to get this permission.
10758                allowed = true;
10759            }
10760            if (!allowed && (bp.protectionLevel
10761                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10762                // For development permissions, a development permission
10763                // is granted only if it was already granted.
10764                allowed = origPermissions.hasInstallPermission(perm);
10765            }
10766            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10767                    && pkg.packageName.equals(mSetupWizardPackage)) {
10768                // If this permission is to be granted to the system setup wizard and
10769                // this app is a setup wizard, then it gets the permission.
10770                allowed = true;
10771            }
10772        }
10773        return allowed;
10774    }
10775
10776    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10777        final int permCount = pkg.requestedPermissions.size();
10778        for (int j = 0; j < permCount; j++) {
10779            String requestedPermission = pkg.requestedPermissions.get(j);
10780            if (permission.equals(requestedPermission)) {
10781                return true;
10782            }
10783        }
10784        return false;
10785    }
10786
10787    final class ActivityIntentResolver
10788            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10789        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10790                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
10791            if (!sUserManager.exists(userId)) return null;
10792            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
10793                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
10794                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
10795            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
10796                    isEphemeral, userId);
10797        }
10798
10799        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10800                int userId) {
10801            if (!sUserManager.exists(userId)) return null;
10802            mFlags = flags;
10803            return super.queryIntent(intent, resolvedType,
10804                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
10805                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
10806                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
10807        }
10808
10809        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10810                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10811            if (!sUserManager.exists(userId)) return null;
10812            if (packageActivities == null) {
10813                return null;
10814            }
10815            mFlags = flags;
10816            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10817            final boolean vislbleToEphemeral =
10818                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
10819            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
10820            final int N = packageActivities.size();
10821            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10822                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10823
10824            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10825            for (int i = 0; i < N; ++i) {
10826                intentFilters = packageActivities.get(i).intents;
10827                if (intentFilters != null && intentFilters.size() > 0) {
10828                    PackageParser.ActivityIntentInfo[] array =
10829                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10830                    intentFilters.toArray(array);
10831                    listCut.add(array);
10832                }
10833            }
10834            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
10835                    vislbleToEphemeral, isEphemeral, listCut, userId);
10836        }
10837
10838        /**
10839         * Finds a privileged activity that matches the specified activity names.
10840         */
10841        private PackageParser.Activity findMatchingActivity(
10842                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10843            for (PackageParser.Activity sysActivity : activityList) {
10844                if (sysActivity.info.name.equals(activityInfo.name)) {
10845                    return sysActivity;
10846                }
10847                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10848                    return sysActivity;
10849                }
10850                if (sysActivity.info.targetActivity != null) {
10851                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10852                        return sysActivity;
10853                    }
10854                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10855                        return sysActivity;
10856                    }
10857                }
10858            }
10859            return null;
10860        }
10861
10862        public class IterGenerator<E> {
10863            public Iterator<E> generate(ActivityIntentInfo info) {
10864                return null;
10865            }
10866        }
10867
10868        public class ActionIterGenerator extends IterGenerator<String> {
10869            @Override
10870            public Iterator<String> generate(ActivityIntentInfo info) {
10871                return info.actionsIterator();
10872            }
10873        }
10874
10875        public class CategoriesIterGenerator extends IterGenerator<String> {
10876            @Override
10877            public Iterator<String> generate(ActivityIntentInfo info) {
10878                return info.categoriesIterator();
10879            }
10880        }
10881
10882        public class SchemesIterGenerator extends IterGenerator<String> {
10883            @Override
10884            public Iterator<String> generate(ActivityIntentInfo info) {
10885                return info.schemesIterator();
10886            }
10887        }
10888
10889        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10890            @Override
10891            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10892                return info.authoritiesIterator();
10893            }
10894        }
10895
10896        /**
10897         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10898         * MODIFIED. Do not pass in a list that should not be changed.
10899         */
10900        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10901                IterGenerator<T> generator, Iterator<T> searchIterator) {
10902            // loop through the set of actions; every one must be found in the intent filter
10903            while (searchIterator.hasNext()) {
10904                // we must have at least one filter in the list to consider a match
10905                if (intentList.size() == 0) {
10906                    break;
10907                }
10908
10909                final T searchAction = searchIterator.next();
10910
10911                // loop through the set of intent filters
10912                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10913                while (intentIter.hasNext()) {
10914                    final ActivityIntentInfo intentInfo = intentIter.next();
10915                    boolean selectionFound = false;
10916
10917                    // loop through the intent filter's selection criteria; at least one
10918                    // of them must match the searched criteria
10919                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10920                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10921                        final T intentSelection = intentSelectionIter.next();
10922                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10923                            selectionFound = true;
10924                            break;
10925                        }
10926                    }
10927
10928                    // the selection criteria wasn't found in this filter's set; this filter
10929                    // is not a potential match
10930                    if (!selectionFound) {
10931                        intentIter.remove();
10932                    }
10933                }
10934            }
10935        }
10936
10937        private boolean isProtectedAction(ActivityIntentInfo filter) {
10938            final Iterator<String> actionsIter = filter.actionsIterator();
10939            while (actionsIter != null && actionsIter.hasNext()) {
10940                final String filterAction = actionsIter.next();
10941                if (PROTECTED_ACTIONS.contains(filterAction)) {
10942                    return true;
10943                }
10944            }
10945            return false;
10946        }
10947
10948        /**
10949         * Adjusts the priority of the given intent filter according to policy.
10950         * <p>
10951         * <ul>
10952         * <li>The priority for non privileged applications is capped to '0'</li>
10953         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10954         * <li>The priority for unbundled updates to privileged applications is capped to the
10955         *      priority defined on the system partition</li>
10956         * </ul>
10957         * <p>
10958         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10959         * allowed to obtain any priority on any action.
10960         */
10961        private void adjustPriority(
10962                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10963            // nothing to do; priority is fine as-is
10964            if (intent.getPriority() <= 0) {
10965                return;
10966            }
10967
10968            final ActivityInfo activityInfo = intent.activity.info;
10969            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10970
10971            final boolean privilegedApp =
10972                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10973            if (!privilegedApp) {
10974                // non-privileged applications can never define a priority >0
10975                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10976                        + " package: " + applicationInfo.packageName
10977                        + " activity: " + intent.activity.className
10978                        + " origPrio: " + intent.getPriority());
10979                intent.setPriority(0);
10980                return;
10981            }
10982
10983            if (systemActivities == null) {
10984                // the system package is not disabled; we're parsing the system partition
10985                if (isProtectedAction(intent)) {
10986                    if (mDeferProtectedFilters) {
10987                        // We can't deal with these just yet. No component should ever obtain a
10988                        // >0 priority for a protected actions, with ONE exception -- the setup
10989                        // wizard. The setup wizard, however, cannot be known until we're able to
10990                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10991                        // until all intent filters have been processed. Chicken, meet egg.
10992                        // Let the filter temporarily have a high priority and rectify the
10993                        // priorities after all system packages have been scanned.
10994                        mProtectedFilters.add(intent);
10995                        if (DEBUG_FILTERS) {
10996                            Slog.i(TAG, "Protected action; save for later;"
10997                                    + " package: " + applicationInfo.packageName
10998                                    + " activity: " + intent.activity.className
10999                                    + " origPrio: " + intent.getPriority());
11000                        }
11001                        return;
11002                    } else {
11003                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11004                            Slog.i(TAG, "No setup wizard;"
11005                                + " All protected intents capped to priority 0");
11006                        }
11007                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11008                            if (DEBUG_FILTERS) {
11009                                Slog.i(TAG, "Found setup wizard;"
11010                                    + " allow priority " + intent.getPriority() + ";"
11011                                    + " package: " + intent.activity.info.packageName
11012                                    + " activity: " + intent.activity.className
11013                                    + " priority: " + intent.getPriority());
11014                            }
11015                            // setup wizard gets whatever it wants
11016                            return;
11017                        }
11018                        Slog.w(TAG, "Protected action; cap priority to 0;"
11019                                + " package: " + intent.activity.info.packageName
11020                                + " activity: " + intent.activity.className
11021                                + " origPrio: " + intent.getPriority());
11022                        intent.setPriority(0);
11023                        return;
11024                    }
11025                }
11026                // privileged apps on the system image get whatever priority they request
11027                return;
11028            }
11029
11030            // privileged app unbundled update ... try to find the same activity
11031            final PackageParser.Activity foundActivity =
11032                    findMatchingActivity(systemActivities, activityInfo);
11033            if (foundActivity == null) {
11034                // this is a new activity; it cannot obtain >0 priority
11035                if (DEBUG_FILTERS) {
11036                    Slog.i(TAG, "New activity; cap priority to 0;"
11037                            + " package: " + applicationInfo.packageName
11038                            + " activity: " + intent.activity.className
11039                            + " origPrio: " + intent.getPriority());
11040                }
11041                intent.setPriority(0);
11042                return;
11043            }
11044
11045            // found activity, now check for filter equivalence
11046
11047            // a shallow copy is enough; we modify the list, not its contents
11048            final List<ActivityIntentInfo> intentListCopy =
11049                    new ArrayList<>(foundActivity.intents);
11050            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11051
11052            // find matching action subsets
11053            final Iterator<String> actionsIterator = intent.actionsIterator();
11054            if (actionsIterator != null) {
11055                getIntentListSubset(
11056                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11057                if (intentListCopy.size() == 0) {
11058                    // no more intents to match; we're not equivalent
11059                    if (DEBUG_FILTERS) {
11060                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11061                                + " package: " + applicationInfo.packageName
11062                                + " activity: " + intent.activity.className
11063                                + " origPrio: " + intent.getPriority());
11064                    }
11065                    intent.setPriority(0);
11066                    return;
11067                }
11068            }
11069
11070            // find matching category subsets
11071            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11072            if (categoriesIterator != null) {
11073                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11074                        categoriesIterator);
11075                if (intentListCopy.size() == 0) {
11076                    // no more intents to match; we're not equivalent
11077                    if (DEBUG_FILTERS) {
11078                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11079                                + " package: " + applicationInfo.packageName
11080                                + " activity: " + intent.activity.className
11081                                + " origPrio: " + intent.getPriority());
11082                    }
11083                    intent.setPriority(0);
11084                    return;
11085                }
11086            }
11087
11088            // find matching schemes subsets
11089            final Iterator<String> schemesIterator = intent.schemesIterator();
11090            if (schemesIterator != null) {
11091                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11092                        schemesIterator);
11093                if (intentListCopy.size() == 0) {
11094                    // no more intents to match; we're not equivalent
11095                    if (DEBUG_FILTERS) {
11096                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11097                                + " package: " + applicationInfo.packageName
11098                                + " activity: " + intent.activity.className
11099                                + " origPrio: " + intent.getPriority());
11100                    }
11101                    intent.setPriority(0);
11102                    return;
11103                }
11104            }
11105
11106            // find matching authorities subsets
11107            final Iterator<IntentFilter.AuthorityEntry>
11108                    authoritiesIterator = intent.authoritiesIterator();
11109            if (authoritiesIterator != null) {
11110                getIntentListSubset(intentListCopy,
11111                        new AuthoritiesIterGenerator(),
11112                        authoritiesIterator);
11113                if (intentListCopy.size() == 0) {
11114                    // no more intents to match; we're not equivalent
11115                    if (DEBUG_FILTERS) {
11116                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11117                                + " package: " + applicationInfo.packageName
11118                                + " activity: " + intent.activity.className
11119                                + " origPrio: " + intent.getPriority());
11120                    }
11121                    intent.setPriority(0);
11122                    return;
11123                }
11124            }
11125
11126            // we found matching filter(s); app gets the max priority of all intents
11127            int cappedPriority = 0;
11128            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11129                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11130            }
11131            if (intent.getPriority() > cappedPriority) {
11132                if (DEBUG_FILTERS) {
11133                    Slog.i(TAG, "Found matching filter(s);"
11134                            + " cap priority to " + cappedPriority + ";"
11135                            + " package: " + applicationInfo.packageName
11136                            + " activity: " + intent.activity.className
11137                            + " origPrio: " + intent.getPriority());
11138                }
11139                intent.setPriority(cappedPriority);
11140                return;
11141            }
11142            // all this for nothing; the requested priority was <= what was on the system
11143        }
11144
11145        public final void addActivity(PackageParser.Activity a, String type) {
11146            mActivities.put(a.getComponentName(), a);
11147            if (DEBUG_SHOW_INFO)
11148                Log.v(
11149                TAG, "  " + type + " " +
11150                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11151            if (DEBUG_SHOW_INFO)
11152                Log.v(TAG, "    Class=" + a.info.name);
11153            final int NI = a.intents.size();
11154            for (int j=0; j<NI; j++) {
11155                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11156                if ("activity".equals(type)) {
11157                    final PackageSetting ps =
11158                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11159                    final List<PackageParser.Activity> systemActivities =
11160                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11161                    adjustPriority(systemActivities, intent);
11162                }
11163                if (DEBUG_SHOW_INFO) {
11164                    Log.v(TAG, "    IntentFilter:");
11165                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11166                }
11167                if (!intent.debugCheck()) {
11168                    Log.w(TAG, "==> For Activity " + a.info.name);
11169                }
11170                addFilter(intent);
11171            }
11172        }
11173
11174        public final void removeActivity(PackageParser.Activity a, String type) {
11175            mActivities.remove(a.getComponentName());
11176            if (DEBUG_SHOW_INFO) {
11177                Log.v(TAG, "  " + type + " "
11178                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11179                                : a.info.name) + ":");
11180                Log.v(TAG, "    Class=" + a.info.name);
11181            }
11182            final int NI = a.intents.size();
11183            for (int j=0; j<NI; j++) {
11184                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11185                if (DEBUG_SHOW_INFO) {
11186                    Log.v(TAG, "    IntentFilter:");
11187                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11188                }
11189                removeFilter(intent);
11190            }
11191        }
11192
11193        @Override
11194        protected boolean allowFilterResult(
11195                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11196            ActivityInfo filterAi = filter.activity.info;
11197            for (int i=dest.size()-1; i>=0; i--) {
11198                ActivityInfo destAi = dest.get(i).activityInfo;
11199                if (destAi.name == filterAi.name
11200                        && destAi.packageName == filterAi.packageName) {
11201                    return false;
11202                }
11203            }
11204            return true;
11205        }
11206
11207        @Override
11208        protected ActivityIntentInfo[] newArray(int size) {
11209            return new ActivityIntentInfo[size];
11210        }
11211
11212        @Override
11213        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11214            if (!sUserManager.exists(userId)) return true;
11215            PackageParser.Package p = filter.activity.owner;
11216            if (p != null) {
11217                PackageSetting ps = (PackageSetting)p.mExtras;
11218                if (ps != null) {
11219                    // System apps are never considered stopped for purposes of
11220                    // filtering, because there may be no way for the user to
11221                    // actually re-launch them.
11222                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11223                            && ps.getStopped(userId);
11224                }
11225            }
11226            return false;
11227        }
11228
11229        @Override
11230        protected boolean isPackageForFilter(String packageName,
11231                PackageParser.ActivityIntentInfo info) {
11232            return packageName.equals(info.activity.owner.packageName);
11233        }
11234
11235        @Override
11236        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11237                int match, int userId) {
11238            if (!sUserManager.exists(userId)) return null;
11239            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11240                return null;
11241            }
11242            final PackageParser.Activity activity = info.activity;
11243            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11244            if (ps == null) {
11245                return null;
11246            }
11247            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11248                    ps.readUserState(userId), userId);
11249            if (ai == null) {
11250                return null;
11251            }
11252            final ResolveInfo res = new ResolveInfo();
11253            res.activityInfo = ai;
11254            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11255                res.filter = info;
11256            }
11257            if (info != null) {
11258                res.handleAllWebDataURI = info.handleAllWebDataURI();
11259            }
11260            res.priority = info.getPriority();
11261            res.preferredOrder = activity.owner.mPreferredOrder;
11262            //System.out.println("Result: " + res.activityInfo.className +
11263            //                   " = " + res.priority);
11264            res.match = match;
11265            res.isDefault = info.hasDefault;
11266            res.labelRes = info.labelRes;
11267            res.nonLocalizedLabel = info.nonLocalizedLabel;
11268            if (userNeedsBadging(userId)) {
11269                res.noResourceId = true;
11270            } else {
11271                res.icon = info.icon;
11272            }
11273            res.iconResourceId = info.icon;
11274            res.system = res.activityInfo.applicationInfo.isSystemApp();
11275            return res;
11276        }
11277
11278        @Override
11279        protected void sortResults(List<ResolveInfo> results) {
11280            Collections.sort(results, mResolvePrioritySorter);
11281        }
11282
11283        @Override
11284        protected void dumpFilter(PrintWriter out, String prefix,
11285                PackageParser.ActivityIntentInfo filter) {
11286            out.print(prefix); out.print(
11287                    Integer.toHexString(System.identityHashCode(filter.activity)));
11288                    out.print(' ');
11289                    filter.activity.printComponentShortName(out);
11290                    out.print(" filter ");
11291                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11292        }
11293
11294        @Override
11295        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11296            return filter.activity;
11297        }
11298
11299        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11300            PackageParser.Activity activity = (PackageParser.Activity)label;
11301            out.print(prefix); out.print(
11302                    Integer.toHexString(System.identityHashCode(activity)));
11303                    out.print(' ');
11304                    activity.printComponentShortName(out);
11305            if (count > 1) {
11306                out.print(" ("); out.print(count); out.print(" filters)");
11307            }
11308            out.println();
11309        }
11310
11311        // Keys are String (activity class name), values are Activity.
11312        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11313                = new ArrayMap<ComponentName, PackageParser.Activity>();
11314        private int mFlags;
11315    }
11316
11317    private final class ServiceIntentResolver
11318            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11319        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11320                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11321            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11322            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11323                    isEphemeral, userId);
11324        }
11325
11326        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11327                int userId) {
11328            if (!sUserManager.exists(userId)) return null;
11329            mFlags = flags;
11330            return super.queryIntent(intent, resolvedType,
11331                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11332                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11333                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11334        }
11335
11336        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11337                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11338            if (!sUserManager.exists(userId)) return null;
11339            if (packageServices == null) {
11340                return null;
11341            }
11342            mFlags = flags;
11343            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11344            final boolean vislbleToEphemeral =
11345                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11346            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11347            final int N = packageServices.size();
11348            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11349                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11350
11351            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11352            for (int i = 0; i < N; ++i) {
11353                intentFilters = packageServices.get(i).intents;
11354                if (intentFilters != null && intentFilters.size() > 0) {
11355                    PackageParser.ServiceIntentInfo[] array =
11356                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11357                    intentFilters.toArray(array);
11358                    listCut.add(array);
11359                }
11360            }
11361            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11362                    vislbleToEphemeral, isEphemeral, listCut, userId);
11363        }
11364
11365        public final void addService(PackageParser.Service s) {
11366            mServices.put(s.getComponentName(), s);
11367            if (DEBUG_SHOW_INFO) {
11368                Log.v(TAG, "  "
11369                        + (s.info.nonLocalizedLabel != null
11370                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11371                Log.v(TAG, "    Class=" + s.info.name);
11372            }
11373            final int NI = s.intents.size();
11374            int j;
11375            for (j=0; j<NI; j++) {
11376                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11377                if (DEBUG_SHOW_INFO) {
11378                    Log.v(TAG, "    IntentFilter:");
11379                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11380                }
11381                if (!intent.debugCheck()) {
11382                    Log.w(TAG, "==> For Service " + s.info.name);
11383                }
11384                addFilter(intent);
11385            }
11386        }
11387
11388        public final void removeService(PackageParser.Service s) {
11389            mServices.remove(s.getComponentName());
11390            if (DEBUG_SHOW_INFO) {
11391                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11392                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11393                Log.v(TAG, "    Class=" + s.info.name);
11394            }
11395            final int NI = s.intents.size();
11396            int j;
11397            for (j=0; j<NI; j++) {
11398                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11399                if (DEBUG_SHOW_INFO) {
11400                    Log.v(TAG, "    IntentFilter:");
11401                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11402                }
11403                removeFilter(intent);
11404            }
11405        }
11406
11407        @Override
11408        protected boolean allowFilterResult(
11409                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11410            ServiceInfo filterSi = filter.service.info;
11411            for (int i=dest.size()-1; i>=0; i--) {
11412                ServiceInfo destAi = dest.get(i).serviceInfo;
11413                if (destAi.name == filterSi.name
11414                        && destAi.packageName == filterSi.packageName) {
11415                    return false;
11416                }
11417            }
11418            return true;
11419        }
11420
11421        @Override
11422        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11423            return new PackageParser.ServiceIntentInfo[size];
11424        }
11425
11426        @Override
11427        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11428            if (!sUserManager.exists(userId)) return true;
11429            PackageParser.Package p = filter.service.owner;
11430            if (p != null) {
11431                PackageSetting ps = (PackageSetting)p.mExtras;
11432                if (ps != null) {
11433                    // System apps are never considered stopped for purposes of
11434                    // filtering, because there may be no way for the user to
11435                    // actually re-launch them.
11436                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11437                            && ps.getStopped(userId);
11438                }
11439            }
11440            return false;
11441        }
11442
11443        @Override
11444        protected boolean isPackageForFilter(String packageName,
11445                PackageParser.ServiceIntentInfo info) {
11446            return packageName.equals(info.service.owner.packageName);
11447        }
11448
11449        @Override
11450        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11451                int match, int userId) {
11452            if (!sUserManager.exists(userId)) return null;
11453            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11454            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11455                return null;
11456            }
11457            final PackageParser.Service service = info.service;
11458            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11459            if (ps == null) {
11460                return null;
11461            }
11462            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11463                    ps.readUserState(userId), userId);
11464            if (si == null) {
11465                return null;
11466            }
11467            final ResolveInfo res = new ResolveInfo();
11468            res.serviceInfo = si;
11469            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11470                res.filter = filter;
11471            }
11472            res.priority = info.getPriority();
11473            res.preferredOrder = service.owner.mPreferredOrder;
11474            res.match = match;
11475            res.isDefault = info.hasDefault;
11476            res.labelRes = info.labelRes;
11477            res.nonLocalizedLabel = info.nonLocalizedLabel;
11478            res.icon = info.icon;
11479            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11480            return res;
11481        }
11482
11483        @Override
11484        protected void sortResults(List<ResolveInfo> results) {
11485            Collections.sort(results, mResolvePrioritySorter);
11486        }
11487
11488        @Override
11489        protected void dumpFilter(PrintWriter out, String prefix,
11490                PackageParser.ServiceIntentInfo filter) {
11491            out.print(prefix); out.print(
11492                    Integer.toHexString(System.identityHashCode(filter.service)));
11493                    out.print(' ');
11494                    filter.service.printComponentShortName(out);
11495                    out.print(" filter ");
11496                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11497        }
11498
11499        @Override
11500        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11501            return filter.service;
11502        }
11503
11504        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11505            PackageParser.Service service = (PackageParser.Service)label;
11506            out.print(prefix); out.print(
11507                    Integer.toHexString(System.identityHashCode(service)));
11508                    out.print(' ');
11509                    service.printComponentShortName(out);
11510            if (count > 1) {
11511                out.print(" ("); out.print(count); out.print(" filters)");
11512            }
11513            out.println();
11514        }
11515
11516//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11517//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11518//            final List<ResolveInfo> retList = Lists.newArrayList();
11519//            while (i.hasNext()) {
11520//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11521//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11522//                    retList.add(resolveInfo);
11523//                }
11524//            }
11525//            return retList;
11526//        }
11527
11528        // Keys are String (activity class name), values are Activity.
11529        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11530                = new ArrayMap<ComponentName, PackageParser.Service>();
11531        private int mFlags;
11532    }
11533
11534    private final class ProviderIntentResolver
11535            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11536        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11537                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11538            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11539            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11540                    isEphemeral, userId);
11541        }
11542
11543        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11544                int userId) {
11545            if (!sUserManager.exists(userId))
11546                return null;
11547            mFlags = flags;
11548            return super.queryIntent(intent, resolvedType,
11549                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11550                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11551                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11552        }
11553
11554        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11555                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11556            if (!sUserManager.exists(userId))
11557                return null;
11558            if (packageProviders == null) {
11559                return null;
11560            }
11561            mFlags = flags;
11562            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11563            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11564            final boolean vislbleToEphemeral =
11565                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11566            final int N = packageProviders.size();
11567            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11568                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11569
11570            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11571            for (int i = 0; i < N; ++i) {
11572                intentFilters = packageProviders.get(i).intents;
11573                if (intentFilters != null && intentFilters.size() > 0) {
11574                    PackageParser.ProviderIntentInfo[] array =
11575                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11576                    intentFilters.toArray(array);
11577                    listCut.add(array);
11578                }
11579            }
11580            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11581                    vislbleToEphemeral, isEphemeral, listCut, userId);
11582        }
11583
11584        public final void addProvider(PackageParser.Provider p) {
11585            if (mProviders.containsKey(p.getComponentName())) {
11586                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11587                return;
11588            }
11589
11590            mProviders.put(p.getComponentName(), p);
11591            if (DEBUG_SHOW_INFO) {
11592                Log.v(TAG, "  "
11593                        + (p.info.nonLocalizedLabel != null
11594                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11595                Log.v(TAG, "    Class=" + p.info.name);
11596            }
11597            final int NI = p.intents.size();
11598            int j;
11599            for (j = 0; j < NI; j++) {
11600                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11601                if (DEBUG_SHOW_INFO) {
11602                    Log.v(TAG, "    IntentFilter:");
11603                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11604                }
11605                if (!intent.debugCheck()) {
11606                    Log.w(TAG, "==> For Provider " + p.info.name);
11607                }
11608                addFilter(intent);
11609            }
11610        }
11611
11612        public final void removeProvider(PackageParser.Provider p) {
11613            mProviders.remove(p.getComponentName());
11614            if (DEBUG_SHOW_INFO) {
11615                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11616                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11617                Log.v(TAG, "    Class=" + p.info.name);
11618            }
11619            final int NI = p.intents.size();
11620            int j;
11621            for (j = 0; j < NI; j++) {
11622                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11623                if (DEBUG_SHOW_INFO) {
11624                    Log.v(TAG, "    IntentFilter:");
11625                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11626                }
11627                removeFilter(intent);
11628            }
11629        }
11630
11631        @Override
11632        protected boolean allowFilterResult(
11633                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11634            ProviderInfo filterPi = filter.provider.info;
11635            for (int i = dest.size() - 1; i >= 0; i--) {
11636                ProviderInfo destPi = dest.get(i).providerInfo;
11637                if (destPi.name == filterPi.name
11638                        && destPi.packageName == filterPi.packageName) {
11639                    return false;
11640                }
11641            }
11642            return true;
11643        }
11644
11645        @Override
11646        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11647            return new PackageParser.ProviderIntentInfo[size];
11648        }
11649
11650        @Override
11651        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11652            if (!sUserManager.exists(userId))
11653                return true;
11654            PackageParser.Package p = filter.provider.owner;
11655            if (p != null) {
11656                PackageSetting ps = (PackageSetting) p.mExtras;
11657                if (ps != null) {
11658                    // System apps are never considered stopped for purposes of
11659                    // filtering, because there may be no way for the user to
11660                    // actually re-launch them.
11661                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11662                            && ps.getStopped(userId);
11663                }
11664            }
11665            return false;
11666        }
11667
11668        @Override
11669        protected boolean isPackageForFilter(String packageName,
11670                PackageParser.ProviderIntentInfo info) {
11671            return packageName.equals(info.provider.owner.packageName);
11672        }
11673
11674        @Override
11675        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11676                int match, int userId) {
11677            if (!sUserManager.exists(userId))
11678                return null;
11679            final PackageParser.ProviderIntentInfo info = filter;
11680            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11681                return null;
11682            }
11683            final PackageParser.Provider provider = info.provider;
11684            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11685            if (ps == null) {
11686                return null;
11687            }
11688            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11689                    ps.readUserState(userId), userId);
11690            if (pi == null) {
11691                return null;
11692            }
11693            final ResolveInfo res = new ResolveInfo();
11694            res.providerInfo = pi;
11695            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11696                res.filter = filter;
11697            }
11698            res.priority = info.getPriority();
11699            res.preferredOrder = provider.owner.mPreferredOrder;
11700            res.match = match;
11701            res.isDefault = info.hasDefault;
11702            res.labelRes = info.labelRes;
11703            res.nonLocalizedLabel = info.nonLocalizedLabel;
11704            res.icon = info.icon;
11705            res.system = res.providerInfo.applicationInfo.isSystemApp();
11706            return res;
11707        }
11708
11709        @Override
11710        protected void sortResults(List<ResolveInfo> results) {
11711            Collections.sort(results, mResolvePrioritySorter);
11712        }
11713
11714        @Override
11715        protected void dumpFilter(PrintWriter out, String prefix,
11716                PackageParser.ProviderIntentInfo filter) {
11717            out.print(prefix);
11718            out.print(
11719                    Integer.toHexString(System.identityHashCode(filter.provider)));
11720            out.print(' ');
11721            filter.provider.printComponentShortName(out);
11722            out.print(" filter ");
11723            out.println(Integer.toHexString(System.identityHashCode(filter)));
11724        }
11725
11726        @Override
11727        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11728            return filter.provider;
11729        }
11730
11731        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11732            PackageParser.Provider provider = (PackageParser.Provider)label;
11733            out.print(prefix); out.print(
11734                    Integer.toHexString(System.identityHashCode(provider)));
11735                    out.print(' ');
11736                    provider.printComponentShortName(out);
11737            if (count > 1) {
11738                out.print(" ("); out.print(count); out.print(" filters)");
11739            }
11740            out.println();
11741        }
11742
11743        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11744                = new ArrayMap<ComponentName, PackageParser.Provider>();
11745        private int mFlags;
11746    }
11747
11748    static final class EphemeralIntentResolver
11749            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11750        /**
11751         * The result that has the highest defined order. Ordering applies on a
11752         * per-package basis. Mapping is from package name to Pair of order and
11753         * EphemeralResolveInfo.
11754         * <p>
11755         * NOTE: This is implemented as a field variable for convenience and efficiency.
11756         * By having a field variable, we're able to track filter ordering as soon as
11757         * a non-zero order is defined. Otherwise, multiple loops across the result set
11758         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11759         * this needs to be contained entirely within {@link #filterResults()}.
11760         */
11761        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11762
11763        @Override
11764        protected EphemeralResponse[] newArray(int size) {
11765            return new EphemeralResponse[size];
11766        }
11767
11768        @Override
11769        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11770            return true;
11771        }
11772
11773        @Override
11774        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11775                int userId) {
11776            if (!sUserManager.exists(userId)) {
11777                return null;
11778            }
11779            final String packageName = responseObj.resolveInfo.getPackageName();
11780            final Integer order = responseObj.getOrder();
11781            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11782                    mOrderResult.get(packageName);
11783            // ordering is enabled and this item's order isn't high enough
11784            if (lastOrderResult != null && lastOrderResult.first >= order) {
11785                return null;
11786            }
11787            final EphemeralResolveInfo res = responseObj.resolveInfo;
11788            if (order > 0) {
11789                // non-zero order, enable ordering
11790                mOrderResult.put(packageName, new Pair<>(order, res));
11791            }
11792            return responseObj;
11793        }
11794
11795        @Override
11796        protected void filterResults(List<EphemeralResponse> results) {
11797            // only do work if ordering is enabled [most of the time it won't be]
11798            if (mOrderResult.size() == 0) {
11799                return;
11800            }
11801            int resultSize = results.size();
11802            for (int i = 0; i < resultSize; i++) {
11803                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11804                final String packageName = info.getPackageName();
11805                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11806                if (savedInfo == null) {
11807                    // package doesn't having ordering
11808                    continue;
11809                }
11810                if (savedInfo.second == info) {
11811                    // circled back to the highest ordered item; remove from order list
11812                    mOrderResult.remove(savedInfo);
11813                    if (mOrderResult.size() == 0) {
11814                        // no more ordered items
11815                        break;
11816                    }
11817                    continue;
11818                }
11819                // item has a worse order, remove it from the result list
11820                results.remove(i);
11821                resultSize--;
11822                i--;
11823            }
11824        }
11825    }
11826
11827    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11828            new Comparator<ResolveInfo>() {
11829        public int compare(ResolveInfo r1, ResolveInfo r2) {
11830            int v1 = r1.priority;
11831            int v2 = r2.priority;
11832            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11833            if (v1 != v2) {
11834                return (v1 > v2) ? -1 : 1;
11835            }
11836            v1 = r1.preferredOrder;
11837            v2 = r2.preferredOrder;
11838            if (v1 != v2) {
11839                return (v1 > v2) ? -1 : 1;
11840            }
11841            if (r1.isDefault != r2.isDefault) {
11842                return r1.isDefault ? -1 : 1;
11843            }
11844            v1 = r1.match;
11845            v2 = r2.match;
11846            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11847            if (v1 != v2) {
11848                return (v1 > v2) ? -1 : 1;
11849            }
11850            if (r1.system != r2.system) {
11851                return r1.system ? -1 : 1;
11852            }
11853            if (r1.activityInfo != null) {
11854                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11855            }
11856            if (r1.serviceInfo != null) {
11857                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11858            }
11859            if (r1.providerInfo != null) {
11860                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11861            }
11862            return 0;
11863        }
11864    };
11865
11866    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11867            new Comparator<ProviderInfo>() {
11868        public int compare(ProviderInfo p1, ProviderInfo p2) {
11869            final int v1 = p1.initOrder;
11870            final int v2 = p2.initOrder;
11871            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11872        }
11873    };
11874
11875    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11876            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11877            final int[] userIds) {
11878        mHandler.post(new Runnable() {
11879            @Override
11880            public void run() {
11881                try {
11882                    final IActivityManager am = ActivityManager.getService();
11883                    if (am == null) return;
11884                    final int[] resolvedUserIds;
11885                    if (userIds == null) {
11886                        resolvedUserIds = am.getRunningUserIds();
11887                    } else {
11888                        resolvedUserIds = userIds;
11889                    }
11890                    for (int id : resolvedUserIds) {
11891                        final Intent intent = new Intent(action,
11892                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11893                        if (extras != null) {
11894                            intent.putExtras(extras);
11895                        }
11896                        if (targetPkg != null) {
11897                            intent.setPackage(targetPkg);
11898                        }
11899                        // Modify the UID when posting to other users
11900                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11901                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11902                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11903                            intent.putExtra(Intent.EXTRA_UID, uid);
11904                        }
11905                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11906                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11907                        if (DEBUG_BROADCASTS) {
11908                            RuntimeException here = new RuntimeException("here");
11909                            here.fillInStackTrace();
11910                            Slog.d(TAG, "Sending to user " + id + ": "
11911                                    + intent.toShortString(false, true, false, false)
11912                                    + " " + intent.getExtras(), here);
11913                        }
11914                        am.broadcastIntent(null, intent, null, finishedReceiver,
11915                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11916                                null, finishedReceiver != null, false, id);
11917                    }
11918                } catch (RemoteException ex) {
11919                }
11920            }
11921        });
11922    }
11923
11924    /**
11925     * Check if the external storage media is available. This is true if there
11926     * is a mounted external storage medium or if the external storage is
11927     * emulated.
11928     */
11929    private boolean isExternalMediaAvailable() {
11930        return mMediaMounted || Environment.isExternalStorageEmulated();
11931    }
11932
11933    @Override
11934    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11935        // writer
11936        synchronized (mPackages) {
11937            if (!isExternalMediaAvailable()) {
11938                // If the external storage is no longer mounted at this point,
11939                // the caller may not have been able to delete all of this
11940                // packages files and can not delete any more.  Bail.
11941                return null;
11942            }
11943            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11944            if (lastPackage != null) {
11945                pkgs.remove(lastPackage);
11946            }
11947            if (pkgs.size() > 0) {
11948                return pkgs.get(0);
11949            }
11950        }
11951        return null;
11952    }
11953
11954    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11955        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11956                userId, andCode ? 1 : 0, packageName);
11957        if (mSystemReady) {
11958            msg.sendToTarget();
11959        } else {
11960            if (mPostSystemReadyMessages == null) {
11961                mPostSystemReadyMessages = new ArrayList<>();
11962            }
11963            mPostSystemReadyMessages.add(msg);
11964        }
11965    }
11966
11967    void startCleaningPackages() {
11968        // reader
11969        if (!isExternalMediaAvailable()) {
11970            return;
11971        }
11972        synchronized (mPackages) {
11973            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11974                return;
11975            }
11976        }
11977        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11978        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11979        IActivityManager am = ActivityManager.getService();
11980        if (am != null) {
11981            try {
11982                am.startService(null, intent, null, mContext.getOpPackageName(),
11983                        UserHandle.USER_SYSTEM);
11984            } catch (RemoteException e) {
11985            }
11986        }
11987    }
11988
11989    @Override
11990    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11991            int installFlags, String installerPackageName, int userId) {
11992        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11993
11994        final int callingUid = Binder.getCallingUid();
11995        enforceCrossUserPermission(callingUid, userId,
11996                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11997
11998        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11999            try {
12000                if (observer != null) {
12001                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12002                }
12003            } catch (RemoteException re) {
12004            }
12005            return;
12006        }
12007
12008        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12009            installFlags |= PackageManager.INSTALL_FROM_ADB;
12010
12011        } else {
12012            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12013            // about installerPackageName.
12014
12015            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12016            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12017        }
12018
12019        UserHandle user;
12020        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12021            user = UserHandle.ALL;
12022        } else {
12023            user = new UserHandle(userId);
12024        }
12025
12026        // Only system components can circumvent runtime permissions when installing.
12027        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12028                && mContext.checkCallingOrSelfPermission(Manifest.permission
12029                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12030            throw new SecurityException("You need the "
12031                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12032                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12033        }
12034
12035        final File originFile = new File(originPath);
12036        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12037
12038        final Message msg = mHandler.obtainMessage(INIT_COPY);
12039        final VerificationInfo verificationInfo = new VerificationInfo(
12040                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12041        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12042                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12043                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12044                null /*certificates*/);
12045        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12046        msg.obj = params;
12047
12048        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12049                System.identityHashCode(msg.obj));
12050        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12051                System.identityHashCode(msg.obj));
12052
12053        mHandler.sendMessage(msg);
12054    }
12055
12056    void installStage(String packageName, File stagedDir, String stagedCid,
12057            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12058            String installerPackageName, int installerUid, UserHandle user,
12059            Certificate[][] certificates) {
12060        if (DEBUG_EPHEMERAL) {
12061            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12062                Slog.d(TAG, "Ephemeral install of " + packageName);
12063            }
12064        }
12065        final VerificationInfo verificationInfo = new VerificationInfo(
12066                sessionParams.originatingUri, sessionParams.referrerUri,
12067                sessionParams.originatingUid, installerUid);
12068
12069        final OriginInfo origin;
12070        if (stagedDir != null) {
12071            origin = OriginInfo.fromStagedFile(stagedDir);
12072        } else {
12073            origin = OriginInfo.fromStagedContainer(stagedCid);
12074        }
12075
12076        final Message msg = mHandler.obtainMessage(INIT_COPY);
12077        final InstallParams params = new InstallParams(origin, null, observer,
12078                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12079                verificationInfo, user, sessionParams.abiOverride,
12080                sessionParams.grantedRuntimePermissions, certificates);
12081        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12082        msg.obj = params;
12083
12084        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12085                System.identityHashCode(msg.obj));
12086        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12087                System.identityHashCode(msg.obj));
12088
12089        mHandler.sendMessage(msg);
12090    }
12091
12092    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12093            int userId) {
12094        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12095        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12096    }
12097
12098    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12099            int appId, int... userIds) {
12100        if (ArrayUtils.isEmpty(userIds)) {
12101            return;
12102        }
12103        Bundle extras = new Bundle(1);
12104        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12105        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12106
12107        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12108                packageName, extras, 0, null, null, userIds);
12109        if (isSystem) {
12110            mHandler.post(() -> {
12111                        for (int userId : userIds) {
12112                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12113                        }
12114                    }
12115            );
12116        }
12117    }
12118
12119    /**
12120     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12121     * automatically without needing an explicit launch.
12122     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12123     */
12124    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12125        // If user is not running, the app didn't miss any broadcast
12126        if (!mUserManagerInternal.isUserRunning(userId)) {
12127            return;
12128        }
12129        final IActivityManager am = ActivityManager.getService();
12130        try {
12131            // Deliver LOCKED_BOOT_COMPLETED first
12132            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12133                    .setPackage(packageName);
12134            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12135            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12136                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12137
12138            // Deliver BOOT_COMPLETED only if user is unlocked
12139            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12140                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12141                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12142                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12143            }
12144        } catch (RemoteException e) {
12145            throw e.rethrowFromSystemServer();
12146        }
12147    }
12148
12149    @Override
12150    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12151            int userId) {
12152        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12153        PackageSetting pkgSetting;
12154        final int uid = Binder.getCallingUid();
12155        enforceCrossUserPermission(uid, userId,
12156                true /* requireFullPermission */, true /* checkShell */,
12157                "setApplicationHiddenSetting for user " + userId);
12158
12159        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12160            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12161            return false;
12162        }
12163
12164        long callingId = Binder.clearCallingIdentity();
12165        try {
12166            boolean sendAdded = false;
12167            boolean sendRemoved = false;
12168            // writer
12169            synchronized (mPackages) {
12170                pkgSetting = mSettings.mPackages.get(packageName);
12171                if (pkgSetting == null) {
12172                    return false;
12173                }
12174                // Do not allow "android" is being disabled
12175                if ("android".equals(packageName)) {
12176                    Slog.w(TAG, "Cannot hide package: android");
12177                    return false;
12178                }
12179                // Only allow protected packages to hide themselves.
12180                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12181                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12182                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12183                    return false;
12184                }
12185
12186                if (pkgSetting.getHidden(userId) != hidden) {
12187                    pkgSetting.setHidden(hidden, userId);
12188                    mSettings.writePackageRestrictionsLPr(userId);
12189                    if (hidden) {
12190                        sendRemoved = true;
12191                    } else {
12192                        sendAdded = true;
12193                    }
12194                }
12195            }
12196            if (sendAdded) {
12197                sendPackageAddedForUser(packageName, pkgSetting, userId);
12198                return true;
12199            }
12200            if (sendRemoved) {
12201                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12202                        "hiding pkg");
12203                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12204                return true;
12205            }
12206        } finally {
12207            Binder.restoreCallingIdentity(callingId);
12208        }
12209        return false;
12210    }
12211
12212    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12213            int userId) {
12214        final PackageRemovedInfo info = new PackageRemovedInfo();
12215        info.removedPackage = packageName;
12216        info.removedUsers = new int[] {userId};
12217        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12218        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12219    }
12220
12221    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12222        if (pkgList.length > 0) {
12223            Bundle extras = new Bundle(1);
12224            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12225
12226            sendPackageBroadcast(
12227                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12228                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12229                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12230                    new int[] {userId});
12231        }
12232    }
12233
12234    /**
12235     * Returns true if application is not found or there was an error. Otherwise it returns
12236     * the hidden state of the package for the given user.
12237     */
12238    @Override
12239    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12240        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12241        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12242                true /* requireFullPermission */, false /* checkShell */,
12243                "getApplicationHidden for user " + userId);
12244        PackageSetting pkgSetting;
12245        long callingId = Binder.clearCallingIdentity();
12246        try {
12247            // writer
12248            synchronized (mPackages) {
12249                pkgSetting = mSettings.mPackages.get(packageName);
12250                if (pkgSetting == null) {
12251                    return true;
12252                }
12253                return pkgSetting.getHidden(userId);
12254            }
12255        } finally {
12256            Binder.restoreCallingIdentity(callingId);
12257        }
12258    }
12259
12260    /**
12261     * @hide
12262     */
12263    @Override
12264    public int installExistingPackageAsUser(String packageName, int userId) {
12265        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12266                null);
12267        PackageSetting pkgSetting;
12268        final int uid = Binder.getCallingUid();
12269        enforceCrossUserPermission(uid, userId,
12270                true /* requireFullPermission */, true /* checkShell */,
12271                "installExistingPackage for user " + userId);
12272        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12273            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12274        }
12275
12276        long callingId = Binder.clearCallingIdentity();
12277        try {
12278            boolean installed = false;
12279
12280            // writer
12281            synchronized (mPackages) {
12282                pkgSetting = mSettings.mPackages.get(packageName);
12283                if (pkgSetting == null) {
12284                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12285                }
12286                if (!pkgSetting.getInstalled(userId)) {
12287                    pkgSetting.setInstalled(true, userId);
12288                    pkgSetting.setHidden(false, userId);
12289                    mSettings.writePackageRestrictionsLPr(userId);
12290                    installed = true;
12291                }
12292            }
12293
12294            if (installed) {
12295                if (pkgSetting.pkg != null) {
12296                    synchronized (mInstallLock) {
12297                        // We don't need to freeze for a brand new install
12298                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12299                    }
12300                }
12301                sendPackageAddedForUser(packageName, pkgSetting, userId);
12302            }
12303        } finally {
12304            Binder.restoreCallingIdentity(callingId);
12305        }
12306
12307        return PackageManager.INSTALL_SUCCEEDED;
12308    }
12309
12310    boolean isUserRestricted(int userId, String restrictionKey) {
12311        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12312        if (restrictions.getBoolean(restrictionKey, false)) {
12313            Log.w(TAG, "User is restricted: " + restrictionKey);
12314            return true;
12315        }
12316        return false;
12317    }
12318
12319    @Override
12320    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12321            int userId) {
12322        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12323        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12324                true /* requireFullPermission */, true /* checkShell */,
12325                "setPackagesSuspended for user " + userId);
12326
12327        if (ArrayUtils.isEmpty(packageNames)) {
12328            return packageNames;
12329        }
12330
12331        // List of package names for whom the suspended state has changed.
12332        List<String> changedPackages = new ArrayList<>(packageNames.length);
12333        // List of package names for whom the suspended state is not set as requested in this
12334        // method.
12335        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12336        long callingId = Binder.clearCallingIdentity();
12337        try {
12338            for (int i = 0; i < packageNames.length; i++) {
12339                String packageName = packageNames[i];
12340                boolean changed = false;
12341                final int appId;
12342                synchronized (mPackages) {
12343                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12344                    if (pkgSetting == null) {
12345                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12346                                + "\". Skipping suspending/un-suspending.");
12347                        unactionedPackages.add(packageName);
12348                        continue;
12349                    }
12350                    appId = pkgSetting.appId;
12351                    if (pkgSetting.getSuspended(userId) != suspended) {
12352                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12353                            unactionedPackages.add(packageName);
12354                            continue;
12355                        }
12356                        pkgSetting.setSuspended(suspended, userId);
12357                        mSettings.writePackageRestrictionsLPr(userId);
12358                        changed = true;
12359                        changedPackages.add(packageName);
12360                    }
12361                }
12362
12363                if (changed && suspended) {
12364                    killApplication(packageName, UserHandle.getUid(userId, appId),
12365                            "suspending package");
12366                }
12367            }
12368        } finally {
12369            Binder.restoreCallingIdentity(callingId);
12370        }
12371
12372        if (!changedPackages.isEmpty()) {
12373            sendPackagesSuspendedForUser(changedPackages.toArray(
12374                    new String[changedPackages.size()]), userId, suspended);
12375        }
12376
12377        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12378    }
12379
12380    @Override
12381    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12382        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12383                true /* requireFullPermission */, false /* checkShell */,
12384                "isPackageSuspendedForUser for user " + userId);
12385        synchronized (mPackages) {
12386            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12387            if (pkgSetting == null) {
12388                throw new IllegalArgumentException("Unknown target package: " + packageName);
12389            }
12390            return pkgSetting.getSuspended(userId);
12391        }
12392    }
12393
12394    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12395        if (isPackageDeviceAdmin(packageName, userId)) {
12396            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12397                    + "\": has an active device admin");
12398            return false;
12399        }
12400
12401        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12402        if (packageName.equals(activeLauncherPackageName)) {
12403            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12404                    + "\": contains the active launcher");
12405            return false;
12406        }
12407
12408        if (packageName.equals(mRequiredInstallerPackage)) {
12409            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12410                    + "\": required for package installation");
12411            return false;
12412        }
12413
12414        if (packageName.equals(mRequiredUninstallerPackage)) {
12415            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12416                    + "\": required for package uninstallation");
12417            return false;
12418        }
12419
12420        if (packageName.equals(mRequiredVerifierPackage)) {
12421            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12422                    + "\": required for package verification");
12423            return false;
12424        }
12425
12426        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12427            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12428                    + "\": is the default dialer");
12429            return false;
12430        }
12431
12432        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12433            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12434                    + "\": protected package");
12435            return false;
12436        }
12437
12438        return true;
12439    }
12440
12441    private String getActiveLauncherPackageName(int userId) {
12442        Intent intent = new Intent(Intent.ACTION_MAIN);
12443        intent.addCategory(Intent.CATEGORY_HOME);
12444        ResolveInfo resolveInfo = resolveIntent(
12445                intent,
12446                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12447                PackageManager.MATCH_DEFAULT_ONLY,
12448                userId);
12449
12450        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12451    }
12452
12453    private String getDefaultDialerPackageName(int userId) {
12454        synchronized (mPackages) {
12455            return mSettings.getDefaultDialerPackageNameLPw(userId);
12456        }
12457    }
12458
12459    @Override
12460    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12461        mContext.enforceCallingOrSelfPermission(
12462                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12463                "Only package verification agents can verify applications");
12464
12465        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12466        final PackageVerificationResponse response = new PackageVerificationResponse(
12467                verificationCode, Binder.getCallingUid());
12468        msg.arg1 = id;
12469        msg.obj = response;
12470        mHandler.sendMessage(msg);
12471    }
12472
12473    @Override
12474    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12475            long millisecondsToDelay) {
12476        mContext.enforceCallingOrSelfPermission(
12477                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12478                "Only package verification agents can extend verification timeouts");
12479
12480        final PackageVerificationState state = mPendingVerification.get(id);
12481        final PackageVerificationResponse response = new PackageVerificationResponse(
12482                verificationCodeAtTimeout, Binder.getCallingUid());
12483
12484        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12485            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12486        }
12487        if (millisecondsToDelay < 0) {
12488            millisecondsToDelay = 0;
12489        }
12490        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12491                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12492            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12493        }
12494
12495        if ((state != null) && !state.timeoutExtended()) {
12496            state.extendTimeout();
12497
12498            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12499            msg.arg1 = id;
12500            msg.obj = response;
12501            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12502        }
12503    }
12504
12505    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12506            int verificationCode, UserHandle user) {
12507        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12508        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12509        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12510        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12511        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12512
12513        mContext.sendBroadcastAsUser(intent, user,
12514                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12515    }
12516
12517    private ComponentName matchComponentForVerifier(String packageName,
12518            List<ResolveInfo> receivers) {
12519        ActivityInfo targetReceiver = null;
12520
12521        final int NR = receivers.size();
12522        for (int i = 0; i < NR; i++) {
12523            final ResolveInfo info = receivers.get(i);
12524            if (info.activityInfo == null) {
12525                continue;
12526            }
12527
12528            if (packageName.equals(info.activityInfo.packageName)) {
12529                targetReceiver = info.activityInfo;
12530                break;
12531            }
12532        }
12533
12534        if (targetReceiver == null) {
12535            return null;
12536        }
12537
12538        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12539    }
12540
12541    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12542            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12543        if (pkgInfo.verifiers.length == 0) {
12544            return null;
12545        }
12546
12547        final int N = pkgInfo.verifiers.length;
12548        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12549        for (int i = 0; i < N; i++) {
12550            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12551
12552            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12553                    receivers);
12554            if (comp == null) {
12555                continue;
12556            }
12557
12558            final int verifierUid = getUidForVerifier(verifierInfo);
12559            if (verifierUid == -1) {
12560                continue;
12561            }
12562
12563            if (DEBUG_VERIFY) {
12564                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12565                        + " with the correct signature");
12566            }
12567            sufficientVerifiers.add(comp);
12568            verificationState.addSufficientVerifier(verifierUid);
12569        }
12570
12571        return sufficientVerifiers;
12572    }
12573
12574    private int getUidForVerifier(VerifierInfo verifierInfo) {
12575        synchronized (mPackages) {
12576            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12577            if (pkg == null) {
12578                return -1;
12579            } else if (pkg.mSignatures.length != 1) {
12580                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12581                        + " has more than one signature; ignoring");
12582                return -1;
12583            }
12584
12585            /*
12586             * If the public key of the package's signature does not match
12587             * our expected public key, then this is a different package and
12588             * we should skip.
12589             */
12590
12591            final byte[] expectedPublicKey;
12592            try {
12593                final Signature verifierSig = pkg.mSignatures[0];
12594                final PublicKey publicKey = verifierSig.getPublicKey();
12595                expectedPublicKey = publicKey.getEncoded();
12596            } catch (CertificateException e) {
12597                return -1;
12598            }
12599
12600            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12601
12602            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12603                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12604                        + " does not have the expected public key; ignoring");
12605                return -1;
12606            }
12607
12608            return pkg.applicationInfo.uid;
12609        }
12610    }
12611
12612    @Override
12613    public void finishPackageInstall(int token, boolean didLaunch) {
12614        enforceSystemOrRoot("Only the system is allowed to finish installs");
12615
12616        if (DEBUG_INSTALL) {
12617            Slog.v(TAG, "BM finishing package install for " + token);
12618        }
12619        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12620
12621        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12622        mHandler.sendMessage(msg);
12623    }
12624
12625    /**
12626     * Get the verification agent timeout.
12627     *
12628     * @return verification timeout in milliseconds
12629     */
12630    private long getVerificationTimeout() {
12631        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12632                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12633                DEFAULT_VERIFICATION_TIMEOUT);
12634    }
12635
12636    /**
12637     * Get the default verification agent response code.
12638     *
12639     * @return default verification response code
12640     */
12641    private int getDefaultVerificationResponse() {
12642        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12643                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12644                DEFAULT_VERIFICATION_RESPONSE);
12645    }
12646
12647    /**
12648     * Check whether or not package verification has been enabled.
12649     *
12650     * @return true if verification should be performed
12651     */
12652    private boolean isVerificationEnabled(int userId, int installFlags) {
12653        if (!DEFAULT_VERIFY_ENABLE) {
12654            return false;
12655        }
12656        // Ephemeral apps don't get the full verification treatment
12657        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12658            if (DEBUG_EPHEMERAL) {
12659                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12660            }
12661            return false;
12662        }
12663
12664        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12665
12666        // Check if installing from ADB
12667        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12668            // Do not run verification in a test harness environment
12669            if (ActivityManager.isRunningInTestHarness()) {
12670                return false;
12671            }
12672            if (ensureVerifyAppsEnabled) {
12673                return true;
12674            }
12675            // Check if the developer does not want package verification for ADB installs
12676            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12677                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12678                return false;
12679            }
12680        }
12681
12682        if (ensureVerifyAppsEnabled) {
12683            return true;
12684        }
12685
12686        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12687                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12688    }
12689
12690    @Override
12691    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12692            throws RemoteException {
12693        mContext.enforceCallingOrSelfPermission(
12694                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12695                "Only intentfilter verification agents can verify applications");
12696
12697        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12698        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12699                Binder.getCallingUid(), verificationCode, failedDomains);
12700        msg.arg1 = id;
12701        msg.obj = response;
12702        mHandler.sendMessage(msg);
12703    }
12704
12705    @Override
12706    public int getIntentVerificationStatus(String packageName, int userId) {
12707        synchronized (mPackages) {
12708            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12709        }
12710    }
12711
12712    @Override
12713    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12714        mContext.enforceCallingOrSelfPermission(
12715                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12716
12717        boolean result = false;
12718        synchronized (mPackages) {
12719            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12720        }
12721        if (result) {
12722            scheduleWritePackageRestrictionsLocked(userId);
12723        }
12724        return result;
12725    }
12726
12727    @Override
12728    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12729            String packageName) {
12730        synchronized (mPackages) {
12731            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12732        }
12733    }
12734
12735    @Override
12736    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12737        if (TextUtils.isEmpty(packageName)) {
12738            return ParceledListSlice.emptyList();
12739        }
12740        synchronized (mPackages) {
12741            PackageParser.Package pkg = mPackages.get(packageName);
12742            if (pkg == null || pkg.activities == null) {
12743                return ParceledListSlice.emptyList();
12744            }
12745            final int count = pkg.activities.size();
12746            ArrayList<IntentFilter> result = new ArrayList<>();
12747            for (int n=0; n<count; n++) {
12748                PackageParser.Activity activity = pkg.activities.get(n);
12749                if (activity.intents != null && activity.intents.size() > 0) {
12750                    result.addAll(activity.intents);
12751                }
12752            }
12753            return new ParceledListSlice<>(result);
12754        }
12755    }
12756
12757    @Override
12758    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12759        mContext.enforceCallingOrSelfPermission(
12760                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12761
12762        synchronized (mPackages) {
12763            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12764            if (packageName != null) {
12765                result |= updateIntentVerificationStatus(packageName,
12766                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12767                        userId);
12768                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12769                        packageName, userId);
12770            }
12771            return result;
12772        }
12773    }
12774
12775    @Override
12776    public String getDefaultBrowserPackageName(int userId) {
12777        synchronized (mPackages) {
12778            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12779        }
12780    }
12781
12782    /**
12783     * Get the "allow unknown sources" setting.
12784     *
12785     * @return the current "allow unknown sources" setting
12786     */
12787    private int getUnknownSourcesSettings() {
12788        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12789                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12790                -1);
12791    }
12792
12793    @Override
12794    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12795        final int uid = Binder.getCallingUid();
12796        // writer
12797        synchronized (mPackages) {
12798            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12799            if (targetPackageSetting == null) {
12800                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12801            }
12802
12803            PackageSetting installerPackageSetting;
12804            if (installerPackageName != null) {
12805                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12806                if (installerPackageSetting == null) {
12807                    throw new IllegalArgumentException("Unknown installer package: "
12808                            + installerPackageName);
12809                }
12810            } else {
12811                installerPackageSetting = null;
12812            }
12813
12814            Signature[] callerSignature;
12815            Object obj = mSettings.getUserIdLPr(uid);
12816            if (obj != null) {
12817                if (obj instanceof SharedUserSetting) {
12818                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12819                } else if (obj instanceof PackageSetting) {
12820                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12821                } else {
12822                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12823                }
12824            } else {
12825                throw new SecurityException("Unknown calling UID: " + uid);
12826            }
12827
12828            // Verify: can't set installerPackageName to a package that is
12829            // not signed with the same cert as the caller.
12830            if (installerPackageSetting != null) {
12831                if (compareSignatures(callerSignature,
12832                        installerPackageSetting.signatures.mSignatures)
12833                        != PackageManager.SIGNATURE_MATCH) {
12834                    throw new SecurityException(
12835                            "Caller does not have same cert as new installer package "
12836                            + installerPackageName);
12837                }
12838            }
12839
12840            // Verify: if target already has an installer package, it must
12841            // be signed with the same cert as the caller.
12842            if (targetPackageSetting.installerPackageName != null) {
12843                PackageSetting setting = mSettings.mPackages.get(
12844                        targetPackageSetting.installerPackageName);
12845                // If the currently set package isn't valid, then it's always
12846                // okay to change it.
12847                if (setting != null) {
12848                    if (compareSignatures(callerSignature,
12849                            setting.signatures.mSignatures)
12850                            != PackageManager.SIGNATURE_MATCH) {
12851                        throw new SecurityException(
12852                                "Caller does not have same cert as old installer package "
12853                                + targetPackageSetting.installerPackageName);
12854                    }
12855                }
12856            }
12857
12858            // Okay!
12859            targetPackageSetting.installerPackageName = installerPackageName;
12860            if (installerPackageName != null) {
12861                mSettings.mInstallerPackages.add(installerPackageName);
12862            }
12863            scheduleWriteSettingsLocked();
12864        }
12865    }
12866
12867    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12868        // Queue up an async operation since the package installation may take a little while.
12869        mHandler.post(new Runnable() {
12870            public void run() {
12871                mHandler.removeCallbacks(this);
12872                 // Result object to be returned
12873                PackageInstalledInfo res = new PackageInstalledInfo();
12874                res.setReturnCode(currentStatus);
12875                res.uid = -1;
12876                res.pkg = null;
12877                res.removedInfo = null;
12878                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12879                    args.doPreInstall(res.returnCode);
12880                    synchronized (mInstallLock) {
12881                        installPackageTracedLI(args, res);
12882                    }
12883                    args.doPostInstall(res.returnCode, res.uid);
12884                }
12885
12886                // A restore should be performed at this point if (a) the install
12887                // succeeded, (b) the operation is not an update, and (c) the new
12888                // package has not opted out of backup participation.
12889                final boolean update = res.removedInfo != null
12890                        && res.removedInfo.removedPackage != null;
12891                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12892                boolean doRestore = !update
12893                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12894
12895                // Set up the post-install work request bookkeeping.  This will be used
12896                // and cleaned up by the post-install event handling regardless of whether
12897                // there's a restore pass performed.  Token values are >= 1.
12898                int token;
12899                if (mNextInstallToken < 0) mNextInstallToken = 1;
12900                token = mNextInstallToken++;
12901
12902                PostInstallData data = new PostInstallData(args, res);
12903                mRunningInstalls.put(token, data);
12904                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12905
12906                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12907                    // Pass responsibility to the Backup Manager.  It will perform a
12908                    // restore if appropriate, then pass responsibility back to the
12909                    // Package Manager to run the post-install observer callbacks
12910                    // and broadcasts.
12911                    IBackupManager bm = IBackupManager.Stub.asInterface(
12912                            ServiceManager.getService(Context.BACKUP_SERVICE));
12913                    if (bm != null) {
12914                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12915                                + " to BM for possible restore");
12916                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12917                        try {
12918                            // TODO: http://b/22388012
12919                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12920                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12921                            } else {
12922                                doRestore = false;
12923                            }
12924                        } catch (RemoteException e) {
12925                            // can't happen; the backup manager is local
12926                        } catch (Exception e) {
12927                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12928                            doRestore = false;
12929                        }
12930                    } else {
12931                        Slog.e(TAG, "Backup Manager not found!");
12932                        doRestore = false;
12933                    }
12934                }
12935
12936                if (!doRestore) {
12937                    // No restore possible, or the Backup Manager was mysteriously not
12938                    // available -- just fire the post-install work request directly.
12939                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12940
12941                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12942
12943                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12944                    mHandler.sendMessage(msg);
12945                }
12946            }
12947        });
12948    }
12949
12950    /**
12951     * Callback from PackageSettings whenever an app is first transitioned out of the
12952     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12953     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12954     * here whether the app is the target of an ongoing install, and only send the
12955     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12956     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12957     * handling.
12958     */
12959    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12960        // Serialize this with the rest of the install-process message chain.  In the
12961        // restore-at-install case, this Runnable will necessarily run before the
12962        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12963        // are coherent.  In the non-restore case, the app has already completed install
12964        // and been launched through some other means, so it is not in a problematic
12965        // state for observers to see the FIRST_LAUNCH signal.
12966        mHandler.post(new Runnable() {
12967            @Override
12968            public void run() {
12969                for (int i = 0; i < mRunningInstalls.size(); i++) {
12970                    final PostInstallData data = mRunningInstalls.valueAt(i);
12971                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12972                        continue;
12973                    }
12974                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12975                        // right package; but is it for the right user?
12976                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12977                            if (userId == data.res.newUsers[uIndex]) {
12978                                if (DEBUG_BACKUP) {
12979                                    Slog.i(TAG, "Package " + pkgName
12980                                            + " being restored so deferring FIRST_LAUNCH");
12981                                }
12982                                return;
12983                            }
12984                        }
12985                    }
12986                }
12987                // didn't find it, so not being restored
12988                if (DEBUG_BACKUP) {
12989                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12990                }
12991                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12992            }
12993        });
12994    }
12995
12996    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12997        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12998                installerPkg, null, userIds);
12999    }
13000
13001    private abstract class HandlerParams {
13002        private static final int MAX_RETRIES = 4;
13003
13004        /**
13005         * Number of times startCopy() has been attempted and had a non-fatal
13006         * error.
13007         */
13008        private int mRetries = 0;
13009
13010        /** User handle for the user requesting the information or installation. */
13011        private final UserHandle mUser;
13012        String traceMethod;
13013        int traceCookie;
13014
13015        HandlerParams(UserHandle user) {
13016            mUser = user;
13017        }
13018
13019        UserHandle getUser() {
13020            return mUser;
13021        }
13022
13023        HandlerParams setTraceMethod(String traceMethod) {
13024            this.traceMethod = traceMethod;
13025            return this;
13026        }
13027
13028        HandlerParams setTraceCookie(int traceCookie) {
13029            this.traceCookie = traceCookie;
13030            return this;
13031        }
13032
13033        final boolean startCopy() {
13034            boolean res;
13035            try {
13036                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13037
13038                if (++mRetries > MAX_RETRIES) {
13039                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13040                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13041                    handleServiceError();
13042                    return false;
13043                } else {
13044                    handleStartCopy();
13045                    res = true;
13046                }
13047            } catch (RemoteException e) {
13048                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13049                mHandler.sendEmptyMessage(MCS_RECONNECT);
13050                res = false;
13051            }
13052            handleReturnCode();
13053            return res;
13054        }
13055
13056        final void serviceError() {
13057            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13058            handleServiceError();
13059            handleReturnCode();
13060        }
13061
13062        abstract void handleStartCopy() throws RemoteException;
13063        abstract void handleServiceError();
13064        abstract void handleReturnCode();
13065    }
13066
13067    class MeasureParams extends HandlerParams {
13068        private final PackageStats mStats;
13069        private boolean mSuccess;
13070
13071        private final IPackageStatsObserver mObserver;
13072
13073        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13074            super(new UserHandle(stats.userHandle));
13075            mObserver = observer;
13076            mStats = stats;
13077        }
13078
13079        @Override
13080        public String toString() {
13081            return "MeasureParams{"
13082                + Integer.toHexString(System.identityHashCode(this))
13083                + " " + mStats.packageName + "}";
13084        }
13085
13086        @Override
13087        void handleStartCopy() throws RemoteException {
13088            synchronized (mInstallLock) {
13089                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13090            }
13091
13092            if (mSuccess) {
13093                boolean mounted = false;
13094                try {
13095                    final String status = Environment.getExternalStorageState();
13096                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13097                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13098                } catch (Exception e) {
13099                }
13100
13101                if (mounted) {
13102                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13103
13104                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13105                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13106
13107                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13108                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13109
13110                    // Always subtract cache size, since it's a subdirectory
13111                    mStats.externalDataSize -= mStats.externalCacheSize;
13112
13113                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13114                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13115
13116                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13117                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13118                }
13119            }
13120        }
13121
13122        @Override
13123        void handleReturnCode() {
13124            if (mObserver != null) {
13125                try {
13126                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13127                } catch (RemoteException e) {
13128                    Slog.i(TAG, "Observer no longer exists.");
13129                }
13130            }
13131        }
13132
13133        @Override
13134        void handleServiceError() {
13135            Slog.e(TAG, "Could not measure application " + mStats.packageName
13136                            + " external storage");
13137        }
13138    }
13139
13140    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13141            throws RemoteException {
13142        long result = 0;
13143        for (File path : paths) {
13144            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13145        }
13146        return result;
13147    }
13148
13149    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13150        for (File path : paths) {
13151            try {
13152                mcs.clearDirectory(path.getAbsolutePath());
13153            } catch (RemoteException e) {
13154            }
13155        }
13156    }
13157
13158    static class OriginInfo {
13159        /**
13160         * Location where install is coming from, before it has been
13161         * copied/renamed into place. This could be a single monolithic APK
13162         * file, or a cluster directory. This location may be untrusted.
13163         */
13164        final File file;
13165        final String cid;
13166
13167        /**
13168         * Flag indicating that {@link #file} or {@link #cid} has already been
13169         * staged, meaning downstream users don't need to defensively copy the
13170         * contents.
13171         */
13172        final boolean staged;
13173
13174        /**
13175         * Flag indicating that {@link #file} or {@link #cid} is an already
13176         * installed app that is being moved.
13177         */
13178        final boolean existing;
13179
13180        final String resolvedPath;
13181        final File resolvedFile;
13182
13183        static OriginInfo fromNothing() {
13184            return new OriginInfo(null, null, false, false);
13185        }
13186
13187        static OriginInfo fromUntrustedFile(File file) {
13188            return new OriginInfo(file, null, false, false);
13189        }
13190
13191        static OriginInfo fromExistingFile(File file) {
13192            return new OriginInfo(file, null, false, true);
13193        }
13194
13195        static OriginInfo fromStagedFile(File file) {
13196            return new OriginInfo(file, null, true, false);
13197        }
13198
13199        static OriginInfo fromStagedContainer(String cid) {
13200            return new OriginInfo(null, cid, true, false);
13201        }
13202
13203        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13204            this.file = file;
13205            this.cid = cid;
13206            this.staged = staged;
13207            this.existing = existing;
13208
13209            if (cid != null) {
13210                resolvedPath = PackageHelper.getSdDir(cid);
13211                resolvedFile = new File(resolvedPath);
13212            } else if (file != null) {
13213                resolvedPath = file.getAbsolutePath();
13214                resolvedFile = file;
13215            } else {
13216                resolvedPath = null;
13217                resolvedFile = null;
13218            }
13219        }
13220    }
13221
13222    static class MoveInfo {
13223        final int moveId;
13224        final String fromUuid;
13225        final String toUuid;
13226        final String packageName;
13227        final String dataAppName;
13228        final int appId;
13229        final String seinfo;
13230        final int targetSdkVersion;
13231
13232        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13233                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13234            this.moveId = moveId;
13235            this.fromUuid = fromUuid;
13236            this.toUuid = toUuid;
13237            this.packageName = packageName;
13238            this.dataAppName = dataAppName;
13239            this.appId = appId;
13240            this.seinfo = seinfo;
13241            this.targetSdkVersion = targetSdkVersion;
13242        }
13243    }
13244
13245    static class VerificationInfo {
13246        /** A constant used to indicate that a uid value is not present. */
13247        public static final int NO_UID = -1;
13248
13249        /** URI referencing where the package was downloaded from. */
13250        final Uri originatingUri;
13251
13252        /** HTTP referrer URI associated with the originatingURI. */
13253        final Uri referrer;
13254
13255        /** UID of the application that the install request originated from. */
13256        final int originatingUid;
13257
13258        /** UID of application requesting the install */
13259        final int installerUid;
13260
13261        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13262            this.originatingUri = originatingUri;
13263            this.referrer = referrer;
13264            this.originatingUid = originatingUid;
13265            this.installerUid = installerUid;
13266        }
13267    }
13268
13269    class InstallParams extends HandlerParams {
13270        final OriginInfo origin;
13271        final MoveInfo move;
13272        final IPackageInstallObserver2 observer;
13273        int installFlags;
13274        final String installerPackageName;
13275        final String volumeUuid;
13276        private InstallArgs mArgs;
13277        private int mRet;
13278        final String packageAbiOverride;
13279        final String[] grantedRuntimePermissions;
13280        final VerificationInfo verificationInfo;
13281        final Certificate[][] certificates;
13282
13283        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13284                int installFlags, String installerPackageName, String volumeUuid,
13285                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13286                String[] grantedPermissions, Certificate[][] certificates) {
13287            super(user);
13288            this.origin = origin;
13289            this.move = move;
13290            this.observer = observer;
13291            this.installFlags = installFlags;
13292            this.installerPackageName = installerPackageName;
13293            this.volumeUuid = volumeUuid;
13294            this.verificationInfo = verificationInfo;
13295            this.packageAbiOverride = packageAbiOverride;
13296            this.grantedRuntimePermissions = grantedPermissions;
13297            this.certificates = certificates;
13298        }
13299
13300        @Override
13301        public String toString() {
13302            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13303                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13304        }
13305
13306        private int installLocationPolicy(PackageInfoLite pkgLite) {
13307            String packageName = pkgLite.packageName;
13308            int installLocation = pkgLite.installLocation;
13309            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13310            // reader
13311            synchronized (mPackages) {
13312                // Currently installed package which the new package is attempting to replace or
13313                // null if no such package is installed.
13314                PackageParser.Package installedPkg = mPackages.get(packageName);
13315                // Package which currently owns the data which the new package will own if installed.
13316                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13317                // will be null whereas dataOwnerPkg will contain information about the package
13318                // which was uninstalled while keeping its data.
13319                PackageParser.Package dataOwnerPkg = installedPkg;
13320                if (dataOwnerPkg  == null) {
13321                    PackageSetting ps = mSettings.mPackages.get(packageName);
13322                    if (ps != null) {
13323                        dataOwnerPkg = ps.pkg;
13324                    }
13325                }
13326
13327                if (dataOwnerPkg != null) {
13328                    // If installed, the package will get access to data left on the device by its
13329                    // predecessor. As a security measure, this is permited only if this is not a
13330                    // version downgrade or if the predecessor package is marked as debuggable and
13331                    // a downgrade is explicitly requested.
13332                    //
13333                    // On debuggable platform builds, downgrades are permitted even for
13334                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13335                    // not offer security guarantees and thus it's OK to disable some security
13336                    // mechanisms to make debugging/testing easier on those builds. However, even on
13337                    // debuggable builds downgrades of packages are permitted only if requested via
13338                    // installFlags. This is because we aim to keep the behavior of debuggable
13339                    // platform builds as close as possible to the behavior of non-debuggable
13340                    // platform builds.
13341                    final boolean downgradeRequested =
13342                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13343                    final boolean packageDebuggable =
13344                                (dataOwnerPkg.applicationInfo.flags
13345                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13346                    final boolean downgradePermitted =
13347                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13348                    if (!downgradePermitted) {
13349                        try {
13350                            checkDowngrade(dataOwnerPkg, pkgLite);
13351                        } catch (PackageManagerException e) {
13352                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13353                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13354                        }
13355                    }
13356                }
13357
13358                if (installedPkg != null) {
13359                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13360                        // Check for updated system application.
13361                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13362                            if (onSd) {
13363                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13364                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13365                            }
13366                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13367                        } else {
13368                            if (onSd) {
13369                                // Install flag overrides everything.
13370                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13371                            }
13372                            // If current upgrade specifies particular preference
13373                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13374                                // Application explicitly specified internal.
13375                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13376                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13377                                // App explictly prefers external. Let policy decide
13378                            } else {
13379                                // Prefer previous location
13380                                if (isExternal(installedPkg)) {
13381                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13382                                }
13383                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13384                            }
13385                        }
13386                    } else {
13387                        // Invalid install. Return error code
13388                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13389                    }
13390                }
13391            }
13392            // All the special cases have been taken care of.
13393            // Return result based on recommended install location.
13394            if (onSd) {
13395                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13396            }
13397            return pkgLite.recommendedInstallLocation;
13398        }
13399
13400        /*
13401         * Invoke remote method to get package information and install
13402         * location values. Override install location based on default
13403         * policy if needed and then create install arguments based
13404         * on the install location.
13405         */
13406        public void handleStartCopy() throws RemoteException {
13407            int ret = PackageManager.INSTALL_SUCCEEDED;
13408
13409            // If we're already staged, we've firmly committed to an install location
13410            if (origin.staged) {
13411                if (origin.file != null) {
13412                    installFlags |= PackageManager.INSTALL_INTERNAL;
13413                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13414                } else if (origin.cid != null) {
13415                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13416                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13417                } else {
13418                    throw new IllegalStateException("Invalid stage location");
13419                }
13420            }
13421
13422            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13423            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13424            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13425            PackageInfoLite pkgLite = null;
13426
13427            if (onInt && onSd) {
13428                // Check if both bits are set.
13429                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13430                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13431            } else if (onSd && ephemeral) {
13432                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13433                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13434            } else {
13435                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13436                        packageAbiOverride);
13437
13438                if (DEBUG_EPHEMERAL && ephemeral) {
13439                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13440                }
13441
13442                /*
13443                 * If we have too little free space, try to free cache
13444                 * before giving up.
13445                 */
13446                if (!origin.staged && pkgLite.recommendedInstallLocation
13447                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13448                    // TODO: focus freeing disk space on the target device
13449                    final StorageManager storage = StorageManager.from(mContext);
13450                    final long lowThreshold = storage.getStorageLowBytes(
13451                            Environment.getDataDirectory());
13452
13453                    final long sizeBytes = mContainerService.calculateInstalledSize(
13454                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13455
13456                    try {
13457                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13458                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13459                                installFlags, packageAbiOverride);
13460                    } catch (InstallerException e) {
13461                        Slog.w(TAG, "Failed to free cache", e);
13462                    }
13463
13464                    /*
13465                     * The cache free must have deleted the file we
13466                     * downloaded to install.
13467                     *
13468                     * TODO: fix the "freeCache" call to not delete
13469                     *       the file we care about.
13470                     */
13471                    if (pkgLite.recommendedInstallLocation
13472                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13473                        pkgLite.recommendedInstallLocation
13474                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13475                    }
13476                }
13477            }
13478
13479            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13480                int loc = pkgLite.recommendedInstallLocation;
13481                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13482                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13483                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13484                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13485                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13486                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13487                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13488                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13489                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13490                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13491                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13492                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13493                } else {
13494                    // Override with defaults if needed.
13495                    loc = installLocationPolicy(pkgLite);
13496                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13497                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13498                    } else if (!onSd && !onInt) {
13499                        // Override install location with flags
13500                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13501                            // Set the flag to install on external media.
13502                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13503                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13504                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13505                            if (DEBUG_EPHEMERAL) {
13506                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13507                            }
13508                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13509                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13510                                    |PackageManager.INSTALL_INTERNAL);
13511                        } else {
13512                            // Make sure the flag for installing on external
13513                            // media is unset
13514                            installFlags |= PackageManager.INSTALL_INTERNAL;
13515                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13516                        }
13517                    }
13518                }
13519            }
13520
13521            final InstallArgs args = createInstallArgs(this);
13522            mArgs = args;
13523
13524            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13525                // TODO: http://b/22976637
13526                // Apps installed for "all" users use the device owner to verify the app
13527                UserHandle verifierUser = getUser();
13528                if (verifierUser == UserHandle.ALL) {
13529                    verifierUser = UserHandle.SYSTEM;
13530                }
13531
13532                /*
13533                 * Determine if we have any installed package verifiers. If we
13534                 * do, then we'll defer to them to verify the packages.
13535                 */
13536                final int requiredUid = mRequiredVerifierPackage == null ? -1
13537                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13538                                verifierUser.getIdentifier());
13539                if (!origin.existing && requiredUid != -1
13540                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13541                    final Intent verification = new Intent(
13542                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13543                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13544                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13545                            PACKAGE_MIME_TYPE);
13546                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13547
13548                    // Query all live verifiers based on current user state
13549                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13550                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13551
13552                    if (DEBUG_VERIFY) {
13553                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13554                                + verification.toString() + " with " + pkgLite.verifiers.length
13555                                + " optional verifiers");
13556                    }
13557
13558                    final int verificationId = mPendingVerificationToken++;
13559
13560                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13561
13562                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13563                            installerPackageName);
13564
13565                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13566                            installFlags);
13567
13568                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13569                            pkgLite.packageName);
13570
13571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13572                            pkgLite.versionCode);
13573
13574                    if (verificationInfo != null) {
13575                        if (verificationInfo.originatingUri != null) {
13576                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13577                                    verificationInfo.originatingUri);
13578                        }
13579                        if (verificationInfo.referrer != null) {
13580                            verification.putExtra(Intent.EXTRA_REFERRER,
13581                                    verificationInfo.referrer);
13582                        }
13583                        if (verificationInfo.originatingUid >= 0) {
13584                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13585                                    verificationInfo.originatingUid);
13586                        }
13587                        if (verificationInfo.installerUid >= 0) {
13588                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13589                                    verificationInfo.installerUid);
13590                        }
13591                    }
13592
13593                    final PackageVerificationState verificationState = new PackageVerificationState(
13594                            requiredUid, args);
13595
13596                    mPendingVerification.append(verificationId, verificationState);
13597
13598                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13599                            receivers, verificationState);
13600
13601                    /*
13602                     * If any sufficient verifiers were listed in the package
13603                     * manifest, attempt to ask them.
13604                     */
13605                    if (sufficientVerifiers != null) {
13606                        final int N = sufficientVerifiers.size();
13607                        if (N == 0) {
13608                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13609                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13610                        } else {
13611                            for (int i = 0; i < N; i++) {
13612                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13613
13614                                final Intent sufficientIntent = new Intent(verification);
13615                                sufficientIntent.setComponent(verifierComponent);
13616                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13617                            }
13618                        }
13619                    }
13620
13621                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13622                            mRequiredVerifierPackage, receivers);
13623                    if (ret == PackageManager.INSTALL_SUCCEEDED
13624                            && mRequiredVerifierPackage != null) {
13625                        Trace.asyncTraceBegin(
13626                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13627                        /*
13628                         * Send the intent to the required verification agent,
13629                         * but only start the verification timeout after the
13630                         * target BroadcastReceivers have run.
13631                         */
13632                        verification.setComponent(requiredVerifierComponent);
13633                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13634                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13635                                new BroadcastReceiver() {
13636                                    @Override
13637                                    public void onReceive(Context context, Intent intent) {
13638                                        final Message msg = mHandler
13639                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13640                                        msg.arg1 = verificationId;
13641                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13642                                    }
13643                                }, null, 0, null, null);
13644
13645                        /*
13646                         * We don't want the copy to proceed until verification
13647                         * succeeds, so null out this field.
13648                         */
13649                        mArgs = null;
13650                    }
13651                } else {
13652                    /*
13653                     * No package verification is enabled, so immediately start
13654                     * the remote call to initiate copy using temporary file.
13655                     */
13656                    ret = args.copyApk(mContainerService, true);
13657                }
13658            }
13659
13660            mRet = ret;
13661        }
13662
13663        @Override
13664        void handleReturnCode() {
13665            // If mArgs is null, then MCS couldn't be reached. When it
13666            // reconnects, it will try again to install. At that point, this
13667            // will succeed.
13668            if (mArgs != null) {
13669                processPendingInstall(mArgs, mRet);
13670            }
13671        }
13672
13673        @Override
13674        void handleServiceError() {
13675            mArgs = createInstallArgs(this);
13676            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13677        }
13678
13679        public boolean isForwardLocked() {
13680            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13681        }
13682    }
13683
13684    /**
13685     * Used during creation of InstallArgs
13686     *
13687     * @param installFlags package installation flags
13688     * @return true if should be installed on external storage
13689     */
13690    private static boolean installOnExternalAsec(int installFlags) {
13691        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13692            return false;
13693        }
13694        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13695            return true;
13696        }
13697        return false;
13698    }
13699
13700    /**
13701     * Used during creation of InstallArgs
13702     *
13703     * @param installFlags package installation flags
13704     * @return true if should be installed as forward locked
13705     */
13706    private static boolean installForwardLocked(int installFlags) {
13707        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13708    }
13709
13710    private InstallArgs createInstallArgs(InstallParams params) {
13711        if (params.move != null) {
13712            return new MoveInstallArgs(params);
13713        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13714            return new AsecInstallArgs(params);
13715        } else {
13716            return new FileInstallArgs(params);
13717        }
13718    }
13719
13720    /**
13721     * Create args that describe an existing installed package. Typically used
13722     * when cleaning up old installs, or used as a move source.
13723     */
13724    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13725            String resourcePath, String[] instructionSets) {
13726        final boolean isInAsec;
13727        if (installOnExternalAsec(installFlags)) {
13728            /* Apps on SD card are always in ASEC containers. */
13729            isInAsec = true;
13730        } else if (installForwardLocked(installFlags)
13731                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13732            /*
13733             * Forward-locked apps are only in ASEC containers if they're the
13734             * new style
13735             */
13736            isInAsec = true;
13737        } else {
13738            isInAsec = false;
13739        }
13740
13741        if (isInAsec) {
13742            return new AsecInstallArgs(codePath, instructionSets,
13743                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13744        } else {
13745            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13746        }
13747    }
13748
13749    static abstract class InstallArgs {
13750        /** @see InstallParams#origin */
13751        final OriginInfo origin;
13752        /** @see InstallParams#move */
13753        final MoveInfo move;
13754
13755        final IPackageInstallObserver2 observer;
13756        // Always refers to PackageManager flags only
13757        final int installFlags;
13758        final String installerPackageName;
13759        final String volumeUuid;
13760        final UserHandle user;
13761        final String abiOverride;
13762        final String[] installGrantPermissions;
13763        /** If non-null, drop an async trace when the install completes */
13764        final String traceMethod;
13765        final int traceCookie;
13766        final Certificate[][] certificates;
13767
13768        // The list of instruction sets supported by this app. This is currently
13769        // only used during the rmdex() phase to clean up resources. We can get rid of this
13770        // if we move dex files under the common app path.
13771        /* nullable */ String[] instructionSets;
13772
13773        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13774                int installFlags, String installerPackageName, String volumeUuid,
13775                UserHandle user, String[] instructionSets,
13776                String abiOverride, String[] installGrantPermissions,
13777                String traceMethod, int traceCookie, Certificate[][] certificates) {
13778            this.origin = origin;
13779            this.move = move;
13780            this.installFlags = installFlags;
13781            this.observer = observer;
13782            this.installerPackageName = installerPackageName;
13783            this.volumeUuid = volumeUuid;
13784            this.user = user;
13785            this.instructionSets = instructionSets;
13786            this.abiOverride = abiOverride;
13787            this.installGrantPermissions = installGrantPermissions;
13788            this.traceMethod = traceMethod;
13789            this.traceCookie = traceCookie;
13790            this.certificates = certificates;
13791        }
13792
13793        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13794        abstract int doPreInstall(int status);
13795
13796        /**
13797         * Rename package into final resting place. All paths on the given
13798         * scanned package should be updated to reflect the rename.
13799         */
13800        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13801        abstract int doPostInstall(int status, int uid);
13802
13803        /** @see PackageSettingBase#codePathString */
13804        abstract String getCodePath();
13805        /** @see PackageSettingBase#resourcePathString */
13806        abstract String getResourcePath();
13807
13808        // Need installer lock especially for dex file removal.
13809        abstract void cleanUpResourcesLI();
13810        abstract boolean doPostDeleteLI(boolean delete);
13811
13812        /**
13813         * Called before the source arguments are copied. This is used mostly
13814         * for MoveParams when it needs to read the source file to put it in the
13815         * destination.
13816         */
13817        int doPreCopy() {
13818            return PackageManager.INSTALL_SUCCEEDED;
13819        }
13820
13821        /**
13822         * Called after the source arguments are copied. This is used mostly for
13823         * MoveParams when it needs to read the source file to put it in the
13824         * destination.
13825         */
13826        int doPostCopy(int uid) {
13827            return PackageManager.INSTALL_SUCCEEDED;
13828        }
13829
13830        protected boolean isFwdLocked() {
13831            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13832        }
13833
13834        protected boolean isExternalAsec() {
13835            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13836        }
13837
13838        protected boolean isEphemeral() {
13839            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13840        }
13841
13842        UserHandle getUser() {
13843            return user;
13844        }
13845    }
13846
13847    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13848        if (!allCodePaths.isEmpty()) {
13849            if (instructionSets == null) {
13850                throw new IllegalStateException("instructionSet == null");
13851            }
13852            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13853            for (String codePath : allCodePaths) {
13854                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13855                    try {
13856                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13857                    } catch (InstallerException ignored) {
13858                    }
13859                }
13860            }
13861        }
13862    }
13863
13864    /**
13865     * Logic to handle installation of non-ASEC applications, including copying
13866     * and renaming logic.
13867     */
13868    class FileInstallArgs extends InstallArgs {
13869        private File codeFile;
13870        private File resourceFile;
13871
13872        // Example topology:
13873        // /data/app/com.example/base.apk
13874        // /data/app/com.example/split_foo.apk
13875        // /data/app/com.example/lib/arm/libfoo.so
13876        // /data/app/com.example/lib/arm64/libfoo.so
13877        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13878
13879        /** New install */
13880        FileInstallArgs(InstallParams params) {
13881            super(params.origin, params.move, params.observer, params.installFlags,
13882                    params.installerPackageName, params.volumeUuid,
13883                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13884                    params.grantedRuntimePermissions,
13885                    params.traceMethod, params.traceCookie, params.certificates);
13886            if (isFwdLocked()) {
13887                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13888            }
13889        }
13890
13891        /** Existing install */
13892        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13893            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13894                    null, null, null, 0, null /*certificates*/);
13895            this.codeFile = (codePath != null) ? new File(codePath) : null;
13896            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13897        }
13898
13899        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13900            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13901            try {
13902                return doCopyApk(imcs, temp);
13903            } finally {
13904                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13905            }
13906        }
13907
13908        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13909            if (origin.staged) {
13910                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13911                codeFile = origin.file;
13912                resourceFile = origin.file;
13913                return PackageManager.INSTALL_SUCCEEDED;
13914            }
13915
13916            try {
13917                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13918                final File tempDir =
13919                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13920                codeFile = tempDir;
13921                resourceFile = tempDir;
13922            } catch (IOException e) {
13923                Slog.w(TAG, "Failed to create copy file: " + e);
13924                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13925            }
13926
13927            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13928                @Override
13929                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13930                    if (!FileUtils.isValidExtFilename(name)) {
13931                        throw new IllegalArgumentException("Invalid filename: " + name);
13932                    }
13933                    try {
13934                        final File file = new File(codeFile, name);
13935                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13936                                O_RDWR | O_CREAT, 0644);
13937                        Os.chmod(file.getAbsolutePath(), 0644);
13938                        return new ParcelFileDescriptor(fd);
13939                    } catch (ErrnoException e) {
13940                        throw new RemoteException("Failed to open: " + e.getMessage());
13941                    }
13942                }
13943            };
13944
13945            int ret = PackageManager.INSTALL_SUCCEEDED;
13946            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13947            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13948                Slog.e(TAG, "Failed to copy package");
13949                return ret;
13950            }
13951
13952            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13953            NativeLibraryHelper.Handle handle = null;
13954            try {
13955                handle = NativeLibraryHelper.Handle.create(codeFile);
13956                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13957                        abiOverride);
13958            } catch (IOException e) {
13959                Slog.e(TAG, "Copying native libraries failed", e);
13960                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13961            } finally {
13962                IoUtils.closeQuietly(handle);
13963            }
13964
13965            return ret;
13966        }
13967
13968        int doPreInstall(int status) {
13969            if (status != PackageManager.INSTALL_SUCCEEDED) {
13970                cleanUp();
13971            }
13972            return status;
13973        }
13974
13975        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13976            if (status != PackageManager.INSTALL_SUCCEEDED) {
13977                cleanUp();
13978                return false;
13979            }
13980
13981            final File targetDir = codeFile.getParentFile();
13982            final File beforeCodeFile = codeFile;
13983            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13984
13985            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13986            try {
13987                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13988            } catch (ErrnoException e) {
13989                Slog.w(TAG, "Failed to rename", e);
13990                return false;
13991            }
13992
13993            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13994                Slog.w(TAG, "Failed to restorecon");
13995                return false;
13996            }
13997
13998            // Reflect the rename internally
13999            codeFile = afterCodeFile;
14000            resourceFile = afterCodeFile;
14001
14002            // Reflect the rename in scanned details
14003            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14004            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14005                    afterCodeFile, pkg.baseCodePath));
14006            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14007                    afterCodeFile, pkg.splitCodePaths));
14008
14009            // Reflect the rename in app info
14010            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14011            pkg.setApplicationInfoCodePath(pkg.codePath);
14012            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14013            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14014            pkg.setApplicationInfoResourcePath(pkg.codePath);
14015            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14016            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14017
14018            return true;
14019        }
14020
14021        int doPostInstall(int status, int uid) {
14022            if (status != PackageManager.INSTALL_SUCCEEDED) {
14023                cleanUp();
14024            }
14025            return status;
14026        }
14027
14028        @Override
14029        String getCodePath() {
14030            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14031        }
14032
14033        @Override
14034        String getResourcePath() {
14035            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14036        }
14037
14038        private boolean cleanUp() {
14039            if (codeFile == null || !codeFile.exists()) {
14040                return false;
14041            }
14042
14043            removeCodePathLI(codeFile);
14044
14045            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14046                resourceFile.delete();
14047            }
14048
14049            return true;
14050        }
14051
14052        void cleanUpResourcesLI() {
14053            // Try enumerating all code paths before deleting
14054            List<String> allCodePaths = Collections.EMPTY_LIST;
14055            if (codeFile != null && codeFile.exists()) {
14056                try {
14057                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14058                    allCodePaths = pkg.getAllCodePaths();
14059                } catch (PackageParserException e) {
14060                    // Ignored; we tried our best
14061                }
14062            }
14063
14064            cleanUp();
14065            removeDexFiles(allCodePaths, instructionSets);
14066        }
14067
14068        boolean doPostDeleteLI(boolean delete) {
14069            // XXX err, shouldn't we respect the delete flag?
14070            cleanUpResourcesLI();
14071            return true;
14072        }
14073    }
14074
14075    private boolean isAsecExternal(String cid) {
14076        final String asecPath = PackageHelper.getSdFilesystem(cid);
14077        return !asecPath.startsWith(mAsecInternalPath);
14078    }
14079
14080    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14081            PackageManagerException {
14082        if (copyRet < 0) {
14083            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14084                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14085                throw new PackageManagerException(copyRet, message);
14086            }
14087        }
14088    }
14089
14090    /**
14091     * Extract the StorageManagerService "container ID" from the full code path of an
14092     * .apk.
14093     */
14094    static String cidFromCodePath(String fullCodePath) {
14095        int eidx = fullCodePath.lastIndexOf("/");
14096        String subStr1 = fullCodePath.substring(0, eidx);
14097        int sidx = subStr1.lastIndexOf("/");
14098        return subStr1.substring(sidx+1, eidx);
14099    }
14100
14101    /**
14102     * Logic to handle installation of ASEC applications, including copying and
14103     * renaming logic.
14104     */
14105    class AsecInstallArgs extends InstallArgs {
14106        static final String RES_FILE_NAME = "pkg.apk";
14107        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14108
14109        String cid;
14110        String packagePath;
14111        String resourcePath;
14112
14113        /** New install */
14114        AsecInstallArgs(InstallParams params) {
14115            super(params.origin, params.move, params.observer, params.installFlags,
14116                    params.installerPackageName, params.volumeUuid,
14117                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14118                    params.grantedRuntimePermissions,
14119                    params.traceMethod, params.traceCookie, params.certificates);
14120        }
14121
14122        /** Existing install */
14123        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14124                        boolean isExternal, boolean isForwardLocked) {
14125            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14126              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14127                    instructionSets, null, null, null, 0, null /*certificates*/);
14128            // Hackily pretend we're still looking at a full code path
14129            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14130                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14131            }
14132
14133            // Extract cid from fullCodePath
14134            int eidx = fullCodePath.lastIndexOf("/");
14135            String subStr1 = fullCodePath.substring(0, eidx);
14136            int sidx = subStr1.lastIndexOf("/");
14137            cid = subStr1.substring(sidx+1, eidx);
14138            setMountPath(subStr1);
14139        }
14140
14141        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14142            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14143              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14144                    instructionSets, null, null, null, 0, null /*certificates*/);
14145            this.cid = cid;
14146            setMountPath(PackageHelper.getSdDir(cid));
14147        }
14148
14149        void createCopyFile() {
14150            cid = mInstallerService.allocateExternalStageCidLegacy();
14151        }
14152
14153        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14154            if (origin.staged && origin.cid != null) {
14155                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14156                cid = origin.cid;
14157                setMountPath(PackageHelper.getSdDir(cid));
14158                return PackageManager.INSTALL_SUCCEEDED;
14159            }
14160
14161            if (temp) {
14162                createCopyFile();
14163            } else {
14164                /*
14165                 * Pre-emptively destroy the container since it's destroyed if
14166                 * copying fails due to it existing anyway.
14167                 */
14168                PackageHelper.destroySdDir(cid);
14169            }
14170
14171            final String newMountPath = imcs.copyPackageToContainer(
14172                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14173                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14174
14175            if (newMountPath != null) {
14176                setMountPath(newMountPath);
14177                return PackageManager.INSTALL_SUCCEEDED;
14178            } else {
14179                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14180            }
14181        }
14182
14183        @Override
14184        String getCodePath() {
14185            return packagePath;
14186        }
14187
14188        @Override
14189        String getResourcePath() {
14190            return resourcePath;
14191        }
14192
14193        int doPreInstall(int status) {
14194            if (status != PackageManager.INSTALL_SUCCEEDED) {
14195                // Destroy container
14196                PackageHelper.destroySdDir(cid);
14197            } else {
14198                boolean mounted = PackageHelper.isContainerMounted(cid);
14199                if (!mounted) {
14200                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14201                            Process.SYSTEM_UID);
14202                    if (newMountPath != null) {
14203                        setMountPath(newMountPath);
14204                    } else {
14205                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14206                    }
14207                }
14208            }
14209            return status;
14210        }
14211
14212        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14213            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14214            String newMountPath = null;
14215            if (PackageHelper.isContainerMounted(cid)) {
14216                // Unmount the container
14217                if (!PackageHelper.unMountSdDir(cid)) {
14218                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14219                    return false;
14220                }
14221            }
14222            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14223                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14224                        " which might be stale. Will try to clean up.");
14225                // Clean up the stale container and proceed to recreate.
14226                if (!PackageHelper.destroySdDir(newCacheId)) {
14227                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14228                    return false;
14229                }
14230                // Successfully cleaned up stale container. Try to rename again.
14231                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14232                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14233                            + " inspite of cleaning it up.");
14234                    return false;
14235                }
14236            }
14237            if (!PackageHelper.isContainerMounted(newCacheId)) {
14238                Slog.w(TAG, "Mounting container " + newCacheId);
14239                newMountPath = PackageHelper.mountSdDir(newCacheId,
14240                        getEncryptKey(), Process.SYSTEM_UID);
14241            } else {
14242                newMountPath = PackageHelper.getSdDir(newCacheId);
14243            }
14244            if (newMountPath == null) {
14245                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14246                return false;
14247            }
14248            Log.i(TAG, "Succesfully renamed " + cid +
14249                    " to " + newCacheId +
14250                    " at new path: " + newMountPath);
14251            cid = newCacheId;
14252
14253            final File beforeCodeFile = new File(packagePath);
14254            setMountPath(newMountPath);
14255            final File afterCodeFile = new File(packagePath);
14256
14257            // Reflect the rename in scanned details
14258            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14259            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14260                    afterCodeFile, pkg.baseCodePath));
14261            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14262                    afterCodeFile, pkg.splitCodePaths));
14263
14264            // Reflect the rename in app info
14265            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14266            pkg.setApplicationInfoCodePath(pkg.codePath);
14267            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14268            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14269            pkg.setApplicationInfoResourcePath(pkg.codePath);
14270            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14271            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14272
14273            return true;
14274        }
14275
14276        private void setMountPath(String mountPath) {
14277            final File mountFile = new File(mountPath);
14278
14279            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14280            if (monolithicFile.exists()) {
14281                packagePath = monolithicFile.getAbsolutePath();
14282                if (isFwdLocked()) {
14283                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14284                } else {
14285                    resourcePath = packagePath;
14286                }
14287            } else {
14288                packagePath = mountFile.getAbsolutePath();
14289                resourcePath = packagePath;
14290            }
14291        }
14292
14293        int doPostInstall(int status, int uid) {
14294            if (status != PackageManager.INSTALL_SUCCEEDED) {
14295                cleanUp();
14296            } else {
14297                final int groupOwner;
14298                final String protectedFile;
14299                if (isFwdLocked()) {
14300                    groupOwner = UserHandle.getSharedAppGid(uid);
14301                    protectedFile = RES_FILE_NAME;
14302                } else {
14303                    groupOwner = -1;
14304                    protectedFile = null;
14305                }
14306
14307                if (uid < Process.FIRST_APPLICATION_UID
14308                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14309                    Slog.e(TAG, "Failed to finalize " + cid);
14310                    PackageHelper.destroySdDir(cid);
14311                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14312                }
14313
14314                boolean mounted = PackageHelper.isContainerMounted(cid);
14315                if (!mounted) {
14316                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14317                }
14318            }
14319            return status;
14320        }
14321
14322        private void cleanUp() {
14323            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14324
14325            // Destroy secure container
14326            PackageHelper.destroySdDir(cid);
14327        }
14328
14329        private List<String> getAllCodePaths() {
14330            final File codeFile = new File(getCodePath());
14331            if (codeFile != null && codeFile.exists()) {
14332                try {
14333                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14334                    return pkg.getAllCodePaths();
14335                } catch (PackageParserException e) {
14336                    // Ignored; we tried our best
14337                }
14338            }
14339            return Collections.EMPTY_LIST;
14340        }
14341
14342        void cleanUpResourcesLI() {
14343            // Enumerate all code paths before deleting
14344            cleanUpResourcesLI(getAllCodePaths());
14345        }
14346
14347        private void cleanUpResourcesLI(List<String> allCodePaths) {
14348            cleanUp();
14349            removeDexFiles(allCodePaths, instructionSets);
14350        }
14351
14352        String getPackageName() {
14353            return getAsecPackageName(cid);
14354        }
14355
14356        boolean doPostDeleteLI(boolean delete) {
14357            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14358            final List<String> allCodePaths = getAllCodePaths();
14359            boolean mounted = PackageHelper.isContainerMounted(cid);
14360            if (mounted) {
14361                // Unmount first
14362                if (PackageHelper.unMountSdDir(cid)) {
14363                    mounted = false;
14364                }
14365            }
14366            if (!mounted && delete) {
14367                cleanUpResourcesLI(allCodePaths);
14368            }
14369            return !mounted;
14370        }
14371
14372        @Override
14373        int doPreCopy() {
14374            if (isFwdLocked()) {
14375                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14376                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14377                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14378                }
14379            }
14380
14381            return PackageManager.INSTALL_SUCCEEDED;
14382        }
14383
14384        @Override
14385        int doPostCopy(int uid) {
14386            if (isFwdLocked()) {
14387                if (uid < Process.FIRST_APPLICATION_UID
14388                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14389                                RES_FILE_NAME)) {
14390                    Slog.e(TAG, "Failed to finalize " + cid);
14391                    PackageHelper.destroySdDir(cid);
14392                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14393                }
14394            }
14395
14396            return PackageManager.INSTALL_SUCCEEDED;
14397        }
14398    }
14399
14400    /**
14401     * Logic to handle movement of existing installed applications.
14402     */
14403    class MoveInstallArgs extends InstallArgs {
14404        private File codeFile;
14405        private File resourceFile;
14406
14407        /** New install */
14408        MoveInstallArgs(InstallParams params) {
14409            super(params.origin, params.move, params.observer, params.installFlags,
14410                    params.installerPackageName, params.volumeUuid,
14411                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14412                    params.grantedRuntimePermissions,
14413                    params.traceMethod, params.traceCookie, params.certificates);
14414        }
14415
14416        int copyApk(IMediaContainerService imcs, boolean temp) {
14417            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14418                    + move.fromUuid + " to " + move.toUuid);
14419            synchronized (mInstaller) {
14420                try {
14421                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14422                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14423                } catch (InstallerException e) {
14424                    Slog.w(TAG, "Failed to move app", e);
14425                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14426                }
14427            }
14428
14429            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14430            resourceFile = codeFile;
14431            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14432
14433            return PackageManager.INSTALL_SUCCEEDED;
14434        }
14435
14436        int doPreInstall(int status) {
14437            if (status != PackageManager.INSTALL_SUCCEEDED) {
14438                cleanUp(move.toUuid);
14439            }
14440            return status;
14441        }
14442
14443        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14444            if (status != PackageManager.INSTALL_SUCCEEDED) {
14445                cleanUp(move.toUuid);
14446                return false;
14447            }
14448
14449            // Reflect the move in app info
14450            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14451            pkg.setApplicationInfoCodePath(pkg.codePath);
14452            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14453            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14454            pkg.setApplicationInfoResourcePath(pkg.codePath);
14455            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14456            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14457
14458            return true;
14459        }
14460
14461        int doPostInstall(int status, int uid) {
14462            if (status == PackageManager.INSTALL_SUCCEEDED) {
14463                cleanUp(move.fromUuid);
14464            } else {
14465                cleanUp(move.toUuid);
14466            }
14467            return status;
14468        }
14469
14470        @Override
14471        String getCodePath() {
14472            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14473        }
14474
14475        @Override
14476        String getResourcePath() {
14477            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14478        }
14479
14480        private boolean cleanUp(String volumeUuid) {
14481            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14482                    move.dataAppName);
14483            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14484            final int[] userIds = sUserManager.getUserIds();
14485            synchronized (mInstallLock) {
14486                // Clean up both app data and code
14487                // All package moves are frozen until finished
14488                for (int userId : userIds) {
14489                    try {
14490                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14491                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14492                    } catch (InstallerException e) {
14493                        Slog.w(TAG, String.valueOf(e));
14494                    }
14495                }
14496                removeCodePathLI(codeFile);
14497            }
14498            return true;
14499        }
14500
14501        void cleanUpResourcesLI() {
14502            throw new UnsupportedOperationException();
14503        }
14504
14505        boolean doPostDeleteLI(boolean delete) {
14506            throw new UnsupportedOperationException();
14507        }
14508    }
14509
14510    static String getAsecPackageName(String packageCid) {
14511        int idx = packageCid.lastIndexOf("-");
14512        if (idx == -1) {
14513            return packageCid;
14514        }
14515        return packageCid.substring(0, idx);
14516    }
14517
14518    // Utility method used to create code paths based on package name and available index.
14519    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14520        String idxStr = "";
14521        int idx = 1;
14522        // Fall back to default value of idx=1 if prefix is not
14523        // part of oldCodePath
14524        if (oldCodePath != null) {
14525            String subStr = oldCodePath;
14526            // Drop the suffix right away
14527            if (suffix != null && subStr.endsWith(suffix)) {
14528                subStr = subStr.substring(0, subStr.length() - suffix.length());
14529            }
14530            // If oldCodePath already contains prefix find out the
14531            // ending index to either increment or decrement.
14532            int sidx = subStr.lastIndexOf(prefix);
14533            if (sidx != -1) {
14534                subStr = subStr.substring(sidx + prefix.length());
14535                if (subStr != null) {
14536                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14537                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14538                    }
14539                    try {
14540                        idx = Integer.parseInt(subStr);
14541                        if (idx <= 1) {
14542                            idx++;
14543                        } else {
14544                            idx--;
14545                        }
14546                    } catch(NumberFormatException e) {
14547                    }
14548                }
14549            }
14550        }
14551        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14552        return prefix + idxStr;
14553    }
14554
14555    private File getNextCodePath(File targetDir, String packageName) {
14556        File result;
14557        SecureRandom random = new SecureRandom();
14558        byte[] bytes = new byte[16];
14559        do {
14560            random.nextBytes(bytes);
14561            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14562            result = new File(targetDir, packageName + "-" + suffix);
14563        } while (result.exists());
14564        return result;
14565    }
14566
14567    // Utility method that returns the relative package path with respect
14568    // to the installation directory. Like say for /data/data/com.test-1.apk
14569    // string com.test-1 is returned.
14570    static String deriveCodePathName(String codePath) {
14571        if (codePath == null) {
14572            return null;
14573        }
14574        final File codeFile = new File(codePath);
14575        final String name = codeFile.getName();
14576        if (codeFile.isDirectory()) {
14577            return name;
14578        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14579            final int lastDot = name.lastIndexOf('.');
14580            return name.substring(0, lastDot);
14581        } else {
14582            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14583            return null;
14584        }
14585    }
14586
14587    static class PackageInstalledInfo {
14588        String name;
14589        int uid;
14590        // The set of users that originally had this package installed.
14591        int[] origUsers;
14592        // The set of users that now have this package installed.
14593        int[] newUsers;
14594        PackageParser.Package pkg;
14595        int returnCode;
14596        String returnMsg;
14597        PackageRemovedInfo removedInfo;
14598        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14599
14600        public void setError(int code, String msg) {
14601            setReturnCode(code);
14602            setReturnMessage(msg);
14603            Slog.w(TAG, msg);
14604        }
14605
14606        public void setError(String msg, PackageParserException e) {
14607            setReturnCode(e.error);
14608            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14609            Slog.w(TAG, msg, e);
14610        }
14611
14612        public void setError(String msg, PackageManagerException e) {
14613            returnCode = e.error;
14614            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14615            Slog.w(TAG, msg, e);
14616        }
14617
14618        public void setReturnCode(int returnCode) {
14619            this.returnCode = returnCode;
14620            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14621            for (int i = 0; i < childCount; i++) {
14622                addedChildPackages.valueAt(i).returnCode = returnCode;
14623            }
14624        }
14625
14626        private void setReturnMessage(String returnMsg) {
14627            this.returnMsg = returnMsg;
14628            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14629            for (int i = 0; i < childCount; i++) {
14630                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14631            }
14632        }
14633
14634        // In some error cases we want to convey more info back to the observer
14635        String origPackage;
14636        String origPermission;
14637    }
14638
14639    /*
14640     * Install a non-existing package.
14641     */
14642    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14643            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14644            PackageInstalledInfo res) {
14645        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14646
14647        // Remember this for later, in case we need to rollback this install
14648        String pkgName = pkg.packageName;
14649
14650        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14651
14652        synchronized(mPackages) {
14653            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14654            if (renamedPackage != null) {
14655                // A package with the same name is already installed, though
14656                // it has been renamed to an older name.  The package we
14657                // are trying to install should be installed as an update to
14658                // the existing one, but that has not been requested, so bail.
14659                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14660                        + " without first uninstalling package running as "
14661                        + renamedPackage);
14662                return;
14663            }
14664            if (mPackages.containsKey(pkgName)) {
14665                // Don't allow installation over an existing package with the same name.
14666                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14667                        + " without first uninstalling.");
14668                return;
14669            }
14670        }
14671
14672        try {
14673            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14674                    System.currentTimeMillis(), user);
14675
14676            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14677
14678            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14679                prepareAppDataAfterInstallLIF(newPackage);
14680
14681            } else {
14682                // Remove package from internal structures, but keep around any
14683                // data that might have already existed
14684                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14685                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14686            }
14687        } catch (PackageManagerException e) {
14688            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14689        }
14690
14691        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14692    }
14693
14694    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14695        // Can't rotate keys during boot or if sharedUser.
14696        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14697                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14698            return false;
14699        }
14700        // app is using upgradeKeySets; make sure all are valid
14701        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14702        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14703        for (int i = 0; i < upgradeKeySets.length; i++) {
14704            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14705                Slog.wtf(TAG, "Package "
14706                         + (oldPs.name != null ? oldPs.name : "<null>")
14707                         + " contains upgrade-key-set reference to unknown key-set: "
14708                         + upgradeKeySets[i]
14709                         + " reverting to signatures check.");
14710                return false;
14711            }
14712        }
14713        return true;
14714    }
14715
14716    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14717        // Upgrade keysets are being used.  Determine if new package has a superset of the
14718        // required keys.
14719        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14720        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14721        for (int i = 0; i < upgradeKeySets.length; i++) {
14722            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14723            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14724                return true;
14725            }
14726        }
14727        return false;
14728    }
14729
14730    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14731        try (DigestInputStream digestStream =
14732                new DigestInputStream(new FileInputStream(file), digest)) {
14733            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14734        }
14735    }
14736
14737    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14738            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14739        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14740
14741        final PackageParser.Package oldPackage;
14742        final String pkgName = pkg.packageName;
14743        final int[] allUsers;
14744        final int[] installedUsers;
14745
14746        synchronized(mPackages) {
14747            oldPackage = mPackages.get(pkgName);
14748            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14749
14750            // don't allow upgrade to target a release SDK from a pre-release SDK
14751            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14752                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14753            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14754                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14755            if (oldTargetsPreRelease
14756                    && !newTargetsPreRelease
14757                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14758                Slog.w(TAG, "Can't install package targeting released sdk");
14759                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14760                return;
14761            }
14762
14763            // don't allow an upgrade from full to ephemeral
14764            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14765            if (isEphemeral && !oldIsEphemeral) {
14766                // can't downgrade from full to ephemeral
14767                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14768                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14769                return;
14770            }
14771
14772            // verify signatures are valid
14773            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14774            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14775                if (!checkUpgradeKeySetLP(ps, pkg)) {
14776                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14777                            "New package not signed by keys specified by upgrade-keysets: "
14778                                    + pkgName);
14779                    return;
14780                }
14781            } else {
14782                // default to original signature matching
14783                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14784                        != PackageManager.SIGNATURE_MATCH) {
14785                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14786                            "New package has a different signature: " + pkgName);
14787                    return;
14788                }
14789            }
14790
14791            // don't allow a system upgrade unless the upgrade hash matches
14792            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14793                byte[] digestBytes = null;
14794                try {
14795                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14796                    updateDigest(digest, new File(pkg.baseCodePath));
14797                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14798                        for (String path : pkg.splitCodePaths) {
14799                            updateDigest(digest, new File(path));
14800                        }
14801                    }
14802                    digestBytes = digest.digest();
14803                } catch (NoSuchAlgorithmException | IOException e) {
14804                    res.setError(INSTALL_FAILED_INVALID_APK,
14805                            "Could not compute hash: " + pkgName);
14806                    return;
14807                }
14808                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14809                    res.setError(INSTALL_FAILED_INVALID_APK,
14810                            "New package fails restrict-update check: " + pkgName);
14811                    return;
14812                }
14813                // retain upgrade restriction
14814                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14815            }
14816
14817            // Check for shared user id changes
14818            String invalidPackageName =
14819                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14820            if (invalidPackageName != null) {
14821                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14822                        "Package " + invalidPackageName + " tried to change user "
14823                                + oldPackage.mSharedUserId);
14824                return;
14825            }
14826
14827            // In case of rollback, remember per-user/profile install state
14828            allUsers = sUserManager.getUserIds();
14829            installedUsers = ps.queryInstalledUsers(allUsers, true);
14830        }
14831
14832        // Update what is removed
14833        res.removedInfo = new PackageRemovedInfo();
14834        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14835        res.removedInfo.removedPackage = oldPackage.packageName;
14836        res.removedInfo.isUpdate = true;
14837        res.removedInfo.origUsers = installedUsers;
14838        final int childCount = (oldPackage.childPackages != null)
14839                ? oldPackage.childPackages.size() : 0;
14840        for (int i = 0; i < childCount; i++) {
14841            boolean childPackageUpdated = false;
14842            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14843            if (res.addedChildPackages != null) {
14844                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14845                if (childRes != null) {
14846                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14847                    childRes.removedInfo.removedPackage = childPkg.packageName;
14848                    childRes.removedInfo.isUpdate = true;
14849                    childPackageUpdated = true;
14850                }
14851            }
14852            if (!childPackageUpdated) {
14853                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14854                childRemovedRes.removedPackage = childPkg.packageName;
14855                childRemovedRes.isUpdate = false;
14856                childRemovedRes.dataRemoved = true;
14857                synchronized (mPackages) {
14858                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14859                    if (childPs != null) {
14860                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14861                    }
14862                }
14863                if (res.removedInfo.removedChildPackages == null) {
14864                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14865                }
14866                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14867            }
14868        }
14869
14870        boolean sysPkg = (isSystemApp(oldPackage));
14871        if (sysPkg) {
14872            // Set the system/privileged flags as needed
14873            final boolean privileged =
14874                    (oldPackage.applicationInfo.privateFlags
14875                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14876            final int systemPolicyFlags = policyFlags
14877                    | PackageParser.PARSE_IS_SYSTEM
14878                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14879
14880            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14881                    user, allUsers, installerPackageName, res);
14882        } else {
14883            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14884                    user, allUsers, installerPackageName, res);
14885        }
14886    }
14887
14888    public List<String> getPreviousCodePaths(String packageName) {
14889        final PackageSetting ps = mSettings.mPackages.get(packageName);
14890        final List<String> result = new ArrayList<String>();
14891        if (ps != null && ps.oldCodePaths != null) {
14892            result.addAll(ps.oldCodePaths);
14893        }
14894        return result;
14895    }
14896
14897    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14898            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14899            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14900        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14901                + deletedPackage);
14902
14903        String pkgName = deletedPackage.packageName;
14904        boolean deletedPkg = true;
14905        boolean addedPkg = false;
14906        boolean updatedSettings = false;
14907        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14908        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14909                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14910
14911        final long origUpdateTime = (pkg.mExtras != null)
14912                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14913
14914        // First delete the existing package while retaining the data directory
14915        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14916                res.removedInfo, true, pkg)) {
14917            // If the existing package wasn't successfully deleted
14918            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14919            deletedPkg = false;
14920        } else {
14921            // Successfully deleted the old package; proceed with replace.
14922
14923            // If deleted package lived in a container, give users a chance to
14924            // relinquish resources before killing.
14925            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14926                if (DEBUG_INSTALL) {
14927                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14928                }
14929                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14930                final ArrayList<String> pkgList = new ArrayList<String>(1);
14931                pkgList.add(deletedPackage.applicationInfo.packageName);
14932                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14933            }
14934
14935            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14936                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14937            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14938
14939            try {
14940                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14941                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14942                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14943
14944                // Update the in-memory copy of the previous code paths.
14945                PackageSetting ps = mSettings.mPackages.get(pkgName);
14946                if (!killApp) {
14947                    if (ps.oldCodePaths == null) {
14948                        ps.oldCodePaths = new ArraySet<>();
14949                    }
14950                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14951                    if (deletedPackage.splitCodePaths != null) {
14952                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14953                    }
14954                } else {
14955                    ps.oldCodePaths = null;
14956                }
14957                if (ps.childPackageNames != null) {
14958                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14959                        final String childPkgName = ps.childPackageNames.get(i);
14960                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14961                        childPs.oldCodePaths = ps.oldCodePaths;
14962                    }
14963                }
14964                prepareAppDataAfterInstallLIF(newPackage);
14965                addedPkg = true;
14966            } catch (PackageManagerException e) {
14967                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14968            }
14969        }
14970
14971        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14972            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14973
14974            // Revert all internal state mutations and added folders for the failed install
14975            if (addedPkg) {
14976                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14977                        res.removedInfo, true, null);
14978            }
14979
14980            // Restore the old package
14981            if (deletedPkg) {
14982                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14983                File restoreFile = new File(deletedPackage.codePath);
14984                // Parse old package
14985                boolean oldExternal = isExternal(deletedPackage);
14986                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14987                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14988                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14989                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14990                try {
14991                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14992                            null);
14993                } catch (PackageManagerException e) {
14994                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14995                            + e.getMessage());
14996                    return;
14997                }
14998
14999                synchronized (mPackages) {
15000                    // Ensure the installer package name up to date
15001                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15002
15003                    // Update permissions for restored package
15004                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15005
15006                    mSettings.writeLPr();
15007                }
15008
15009                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15010            }
15011        } else {
15012            synchronized (mPackages) {
15013                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15014                if (ps != null) {
15015                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15016                    if (res.removedInfo.removedChildPackages != null) {
15017                        final int childCount = res.removedInfo.removedChildPackages.size();
15018                        // Iterate in reverse as we may modify the collection
15019                        for (int i = childCount - 1; i >= 0; i--) {
15020                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15021                            if (res.addedChildPackages.containsKey(childPackageName)) {
15022                                res.removedInfo.removedChildPackages.removeAt(i);
15023                            } else {
15024                                PackageRemovedInfo childInfo = res.removedInfo
15025                                        .removedChildPackages.valueAt(i);
15026                                childInfo.removedForAllUsers = mPackages.get(
15027                                        childInfo.removedPackage) == null;
15028                            }
15029                        }
15030                    }
15031                }
15032            }
15033        }
15034    }
15035
15036    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15037            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15038            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
15039        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15040                + ", old=" + deletedPackage);
15041
15042        final boolean disabledSystem;
15043
15044        // Remove existing system package
15045        removePackageLI(deletedPackage, true);
15046
15047        synchronized (mPackages) {
15048            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15049        }
15050        if (!disabledSystem) {
15051            // We didn't need to disable the .apk as a current system package,
15052            // which means we are replacing another update that is already
15053            // installed.  We need to make sure to delete the older one's .apk.
15054            res.removedInfo.args = createInstallArgsForExisting(0,
15055                    deletedPackage.applicationInfo.getCodePath(),
15056                    deletedPackage.applicationInfo.getResourcePath(),
15057                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15058        } else {
15059            res.removedInfo.args = null;
15060        }
15061
15062        // Successfully disabled the old package. Now proceed with re-installation
15063        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15064                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15065        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15066
15067        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15068        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15069                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15070
15071        PackageParser.Package newPackage = null;
15072        try {
15073            // Add the package to the internal data structures
15074            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15075
15076            // Set the update and install times
15077            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15078            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15079                    System.currentTimeMillis());
15080
15081            // Update the package dynamic state if succeeded
15082            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15083                // Now that the install succeeded make sure we remove data
15084                // directories for any child package the update removed.
15085                final int deletedChildCount = (deletedPackage.childPackages != null)
15086                        ? deletedPackage.childPackages.size() : 0;
15087                final int newChildCount = (newPackage.childPackages != null)
15088                        ? newPackage.childPackages.size() : 0;
15089                for (int i = 0; i < deletedChildCount; i++) {
15090                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15091                    boolean childPackageDeleted = true;
15092                    for (int j = 0; j < newChildCount; j++) {
15093                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15094                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15095                            childPackageDeleted = false;
15096                            break;
15097                        }
15098                    }
15099                    if (childPackageDeleted) {
15100                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15101                                deletedChildPkg.packageName);
15102                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15103                            PackageRemovedInfo removedChildRes = res.removedInfo
15104                                    .removedChildPackages.get(deletedChildPkg.packageName);
15105                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15106                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15107                        }
15108                    }
15109                }
15110
15111                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
15112                prepareAppDataAfterInstallLIF(newPackage);
15113            }
15114        } catch (PackageManagerException e) {
15115            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15116            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15117        }
15118
15119        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15120            // Re installation failed. Restore old information
15121            // Remove new pkg information
15122            if (newPackage != null) {
15123                removeInstalledPackageLI(newPackage, true);
15124            }
15125            // Add back the old system package
15126            try {
15127                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15128            } catch (PackageManagerException e) {
15129                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15130            }
15131
15132            synchronized (mPackages) {
15133                if (disabledSystem) {
15134                    enableSystemPackageLPw(deletedPackage);
15135                }
15136
15137                // Ensure the installer package name up to date
15138                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15139
15140                // Update permissions for restored package
15141                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15142
15143                mSettings.writeLPr();
15144            }
15145
15146            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15147                    + " after failed upgrade");
15148        }
15149    }
15150
15151    /**
15152     * Checks whether the parent or any of the child packages have a change shared
15153     * user. For a package to be a valid update the shred users of the parent and
15154     * the children should match. We may later support changing child shared users.
15155     * @param oldPkg The updated package.
15156     * @param newPkg The update package.
15157     * @return The shared user that change between the versions.
15158     */
15159    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15160            PackageParser.Package newPkg) {
15161        // Check parent shared user
15162        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15163            return newPkg.packageName;
15164        }
15165        // Check child shared users
15166        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15167        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15168        for (int i = 0; i < newChildCount; i++) {
15169            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15170            // If this child was present, did it have the same shared user?
15171            for (int j = 0; j < oldChildCount; j++) {
15172                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15173                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15174                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15175                    return newChildPkg.packageName;
15176                }
15177            }
15178        }
15179        return null;
15180    }
15181
15182    private void removeNativeBinariesLI(PackageSetting ps) {
15183        // Remove the lib path for the parent package
15184        if (ps != null) {
15185            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15186            // Remove the lib path for the child packages
15187            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15188            for (int i = 0; i < childCount; i++) {
15189                PackageSetting childPs = null;
15190                synchronized (mPackages) {
15191                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15192                }
15193                if (childPs != null) {
15194                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15195                            .legacyNativeLibraryPathString);
15196                }
15197            }
15198        }
15199    }
15200
15201    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15202        // Enable the parent package
15203        mSettings.enableSystemPackageLPw(pkg.packageName);
15204        // Enable the child packages
15205        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15206        for (int i = 0; i < childCount; i++) {
15207            PackageParser.Package childPkg = pkg.childPackages.get(i);
15208            mSettings.enableSystemPackageLPw(childPkg.packageName);
15209        }
15210    }
15211
15212    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15213            PackageParser.Package newPkg) {
15214        // Disable the parent package (parent always replaced)
15215        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15216        // Disable the child packages
15217        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15218        for (int i = 0; i < childCount; i++) {
15219            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15220            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15221            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15222        }
15223        return disabled;
15224    }
15225
15226    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15227            String installerPackageName) {
15228        // Enable the parent package
15229        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15230        // Enable the child packages
15231        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15232        for (int i = 0; i < childCount; i++) {
15233            PackageParser.Package childPkg = pkg.childPackages.get(i);
15234            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15235        }
15236    }
15237
15238    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15239        // Collect all used permissions in the UID
15240        ArraySet<String> usedPermissions = new ArraySet<>();
15241        final int packageCount = su.packages.size();
15242        for (int i = 0; i < packageCount; i++) {
15243            PackageSetting ps = su.packages.valueAt(i);
15244            if (ps.pkg == null) {
15245                continue;
15246            }
15247            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15248            for (int j = 0; j < requestedPermCount; j++) {
15249                String permission = ps.pkg.requestedPermissions.get(j);
15250                BasePermission bp = mSettings.mPermissions.get(permission);
15251                if (bp != null) {
15252                    usedPermissions.add(permission);
15253                }
15254            }
15255        }
15256
15257        PermissionsState permissionsState = su.getPermissionsState();
15258        // Prune install permissions
15259        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15260        final int installPermCount = installPermStates.size();
15261        for (int i = installPermCount - 1; i >= 0;  i--) {
15262            PermissionState permissionState = installPermStates.get(i);
15263            if (!usedPermissions.contains(permissionState.getName())) {
15264                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15265                if (bp != null) {
15266                    permissionsState.revokeInstallPermission(bp);
15267                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15268                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15269                }
15270            }
15271        }
15272
15273        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15274
15275        // Prune runtime permissions
15276        for (int userId : allUserIds) {
15277            List<PermissionState> runtimePermStates = permissionsState
15278                    .getRuntimePermissionStates(userId);
15279            final int runtimePermCount = runtimePermStates.size();
15280            for (int i = runtimePermCount - 1; i >= 0; i--) {
15281                PermissionState permissionState = runtimePermStates.get(i);
15282                if (!usedPermissions.contains(permissionState.getName())) {
15283                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15284                    if (bp != null) {
15285                        permissionsState.revokeRuntimePermission(bp, userId);
15286                        permissionsState.updatePermissionFlags(bp, userId,
15287                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15288                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15289                                runtimePermissionChangedUserIds, userId);
15290                    }
15291                }
15292            }
15293        }
15294
15295        return runtimePermissionChangedUserIds;
15296    }
15297
15298    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15299            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
15300        // Update the parent package setting
15301        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15302                res, user);
15303        // Update the child packages setting
15304        final int childCount = (newPackage.childPackages != null)
15305                ? newPackage.childPackages.size() : 0;
15306        for (int i = 0; i < childCount; i++) {
15307            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15308            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15309            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15310                    childRes.origUsers, childRes, user);
15311        }
15312    }
15313
15314    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15315            String installerPackageName, int[] allUsers, int[] installedForUsers,
15316            PackageInstalledInfo res, UserHandle user) {
15317        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15318
15319        String pkgName = newPackage.packageName;
15320        synchronized (mPackages) {
15321            //write settings. the installStatus will be incomplete at this stage.
15322            //note that the new package setting would have already been
15323            //added to mPackages. It hasn't been persisted yet.
15324            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15325            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15326            mSettings.writeLPr();
15327            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15328        }
15329
15330        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15331        synchronized (mPackages) {
15332            updatePermissionsLPw(newPackage.packageName, newPackage,
15333                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15334                            ? UPDATE_PERMISSIONS_ALL : 0));
15335            // For system-bundled packages, we assume that installing an upgraded version
15336            // of the package implies that the user actually wants to run that new code,
15337            // so we enable the package.
15338            PackageSetting ps = mSettings.mPackages.get(pkgName);
15339            final int userId = user.getIdentifier();
15340            if (ps != null) {
15341                if (isSystemApp(newPackage)) {
15342                    if (DEBUG_INSTALL) {
15343                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15344                    }
15345                    // Enable system package for requested users
15346                    if (res.origUsers != null) {
15347                        for (int origUserId : res.origUsers) {
15348                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15349                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15350                                        origUserId, installerPackageName);
15351                            }
15352                        }
15353                    }
15354                    // Also convey the prior install/uninstall state
15355                    if (allUsers != null && installedForUsers != null) {
15356                        for (int currentUserId : allUsers) {
15357                            final boolean installed = ArrayUtils.contains(
15358                                    installedForUsers, currentUserId);
15359                            if (DEBUG_INSTALL) {
15360                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15361                            }
15362                            ps.setInstalled(installed, currentUserId);
15363                        }
15364                        // these install state changes will be persisted in the
15365                        // upcoming call to mSettings.writeLPr().
15366                    }
15367                }
15368                // It's implied that when a user requests installation, they want the app to be
15369                // installed and enabled.
15370                if (userId != UserHandle.USER_ALL) {
15371                    ps.setInstalled(true, userId);
15372                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15373                }
15374            }
15375            res.name = pkgName;
15376            res.uid = newPackage.applicationInfo.uid;
15377            res.pkg = newPackage;
15378            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15379            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15380            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15381            //to update install status
15382            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15383            mSettings.writeLPr();
15384            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15385        }
15386
15387        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15388    }
15389
15390    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15391        try {
15392            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15393            installPackageLI(args, res);
15394        } finally {
15395            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15396        }
15397    }
15398
15399    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15400        final int installFlags = args.installFlags;
15401        final String installerPackageName = args.installerPackageName;
15402        final String volumeUuid = args.volumeUuid;
15403        final File tmpPackageFile = new File(args.getCodePath());
15404        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15405        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15406                || (args.volumeUuid != null));
15407        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15408        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15409        boolean replace = false;
15410        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15411        if (args.move != null) {
15412            // moving a complete application; perform an initial scan on the new install location
15413            scanFlags |= SCAN_INITIAL;
15414        }
15415        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15416            scanFlags |= SCAN_DONT_KILL_APP;
15417        }
15418
15419        // Result object to be returned
15420        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15421
15422        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15423
15424        // Sanity check
15425        if (ephemeral && (forwardLocked || onExternal)) {
15426            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15427                    + " external=" + onExternal);
15428            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15429            return;
15430        }
15431
15432        // Retrieve PackageSettings and parse package
15433        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15434                | PackageParser.PARSE_ENFORCE_CODE
15435                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15436                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15437                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15438                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15439        PackageParser pp = new PackageParser();
15440        pp.setSeparateProcesses(mSeparateProcesses);
15441        pp.setDisplayMetrics(mMetrics);
15442
15443        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15444        final PackageParser.Package pkg;
15445        try {
15446            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15447        } catch (PackageParserException e) {
15448            res.setError("Failed parse during installPackageLI", e);
15449            return;
15450        } finally {
15451            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15452        }
15453
15454        // If we are installing a clustered package add results for the children
15455        if (pkg.childPackages != null) {
15456            synchronized (mPackages) {
15457                final int childCount = pkg.childPackages.size();
15458                for (int i = 0; i < childCount; i++) {
15459                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15460                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15461                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15462                    childRes.pkg = childPkg;
15463                    childRes.name = childPkg.packageName;
15464                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15465                    if (childPs != null) {
15466                        childRes.origUsers = childPs.queryInstalledUsers(
15467                                sUserManager.getUserIds(), true);
15468                    }
15469                    if ((mPackages.containsKey(childPkg.packageName))) {
15470                        childRes.removedInfo = new PackageRemovedInfo();
15471                        childRes.removedInfo.removedPackage = childPkg.packageName;
15472                    }
15473                    if (res.addedChildPackages == null) {
15474                        res.addedChildPackages = new ArrayMap<>();
15475                    }
15476                    res.addedChildPackages.put(childPkg.packageName, childRes);
15477                }
15478            }
15479        }
15480
15481        // If package doesn't declare API override, mark that we have an install
15482        // time CPU ABI override.
15483        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15484            pkg.cpuAbiOverride = args.abiOverride;
15485        }
15486
15487        String pkgName = res.name = pkg.packageName;
15488        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15489            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15490                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15491                return;
15492            }
15493        }
15494
15495        try {
15496            // either use what we've been given or parse directly from the APK
15497            if (args.certificates != null) {
15498                try {
15499                    PackageParser.populateCertificates(pkg, args.certificates);
15500                } catch (PackageParserException e) {
15501                    // there was something wrong with the certificates we were given;
15502                    // try to pull them from the APK
15503                    PackageParser.collectCertificates(pkg, parseFlags);
15504                }
15505            } else {
15506                PackageParser.collectCertificates(pkg, parseFlags);
15507            }
15508        } catch (PackageParserException e) {
15509            res.setError("Failed collect during installPackageLI", e);
15510            return;
15511        }
15512
15513        // Get rid of all references to package scan path via parser.
15514        pp = null;
15515        String oldCodePath = null;
15516        boolean systemApp = false;
15517        synchronized (mPackages) {
15518            // Check if installing already existing package
15519            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15520                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15521                if (pkg.mOriginalPackages != null
15522                        && pkg.mOriginalPackages.contains(oldName)
15523                        && mPackages.containsKey(oldName)) {
15524                    // This package is derived from an original package,
15525                    // and this device has been updating from that original
15526                    // name.  We must continue using the original name, so
15527                    // rename the new package here.
15528                    pkg.setPackageName(oldName);
15529                    pkgName = pkg.packageName;
15530                    replace = true;
15531                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15532                            + oldName + " pkgName=" + pkgName);
15533                } else if (mPackages.containsKey(pkgName)) {
15534                    // This package, under its official name, already exists
15535                    // on the device; we should replace it.
15536                    replace = true;
15537                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15538                }
15539
15540                // Child packages are installed through the parent package
15541                if (pkg.parentPackage != null) {
15542                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15543                            "Package " + pkg.packageName + " is child of package "
15544                                    + pkg.parentPackage.parentPackage + ". Child packages "
15545                                    + "can be updated only through the parent package.");
15546                    return;
15547                }
15548
15549                if (replace) {
15550                    // Prevent apps opting out from runtime permissions
15551                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15552                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15553                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15554                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15555                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15556                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15557                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15558                                        + " doesn't support runtime permissions but the old"
15559                                        + " target SDK " + oldTargetSdk + " does.");
15560                        return;
15561                    }
15562
15563                    // Prevent installing of child packages
15564                    if (oldPackage.parentPackage != null) {
15565                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15566                                "Package " + pkg.packageName + " is child of package "
15567                                        + oldPackage.parentPackage + ". Child packages "
15568                                        + "can be updated only through the parent package.");
15569                        return;
15570                    }
15571                }
15572            }
15573
15574            PackageSetting ps = mSettings.mPackages.get(pkgName);
15575            if (ps != null) {
15576                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15577
15578                // Quick sanity check that we're signed correctly if updating;
15579                // we'll check this again later when scanning, but we want to
15580                // bail early here before tripping over redefined permissions.
15581                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15582                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15583                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15584                                + pkg.packageName + " upgrade keys do not match the "
15585                                + "previously installed version");
15586                        return;
15587                    }
15588                } else {
15589                    try {
15590                        verifySignaturesLP(ps, pkg);
15591                    } catch (PackageManagerException e) {
15592                        res.setError(e.error, e.getMessage());
15593                        return;
15594                    }
15595                }
15596
15597                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15598                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15599                    systemApp = (ps.pkg.applicationInfo.flags &
15600                            ApplicationInfo.FLAG_SYSTEM) != 0;
15601                }
15602                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15603            }
15604
15605            // Check whether the newly-scanned package wants to define an already-defined perm
15606            int N = pkg.permissions.size();
15607            for (int i = N-1; i >= 0; i--) {
15608                PackageParser.Permission perm = pkg.permissions.get(i);
15609                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15610                if (bp != null) {
15611                    // If the defining package is signed with our cert, it's okay.  This
15612                    // also includes the "updating the same package" case, of course.
15613                    // "updating same package" could also involve key-rotation.
15614                    final boolean sigsOk;
15615                    if (bp.sourcePackage.equals(pkg.packageName)
15616                            && (bp.packageSetting instanceof PackageSetting)
15617                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15618                                    scanFlags))) {
15619                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15620                    } else {
15621                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15622                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15623                    }
15624                    if (!sigsOk) {
15625                        // If the owning package is the system itself, we log but allow
15626                        // install to proceed; we fail the install on all other permission
15627                        // redefinitions.
15628                        if (!bp.sourcePackage.equals("android")) {
15629                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15630                                    + pkg.packageName + " attempting to redeclare permission "
15631                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15632                            res.origPermission = perm.info.name;
15633                            res.origPackage = bp.sourcePackage;
15634                            return;
15635                        } else {
15636                            Slog.w(TAG, "Package " + pkg.packageName
15637                                    + " attempting to redeclare system permission "
15638                                    + perm.info.name + "; ignoring new declaration");
15639                            pkg.permissions.remove(i);
15640                        }
15641                    }
15642                }
15643            }
15644        }
15645
15646        if (systemApp) {
15647            if (onExternal) {
15648                // Abort update; system app can't be replaced with app on sdcard
15649                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15650                        "Cannot install updates to system apps on sdcard");
15651                return;
15652            } else if (ephemeral) {
15653                // Abort update; system app can't be replaced with an ephemeral app
15654                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15655                        "Cannot update a system app with an ephemeral app");
15656                return;
15657            }
15658        }
15659
15660        if (args.move != null) {
15661            // We did an in-place move, so dex is ready to roll
15662            scanFlags |= SCAN_NO_DEX;
15663            scanFlags |= SCAN_MOVE;
15664
15665            synchronized (mPackages) {
15666                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15667                if (ps == null) {
15668                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15669                            "Missing settings for moved package " + pkgName);
15670                }
15671
15672                // We moved the entire application as-is, so bring over the
15673                // previously derived ABI information.
15674                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15675                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15676            }
15677
15678        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15679            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15680            scanFlags |= SCAN_NO_DEX;
15681
15682            try {
15683                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15684                    args.abiOverride : pkg.cpuAbiOverride);
15685                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15686                        true /*extractLibs*/, mAppLib32InstallDir);
15687            } catch (PackageManagerException pme) {
15688                Slog.e(TAG, "Error deriving application ABI", pme);
15689                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15690                return;
15691            }
15692
15693            // Shared libraries for the package need to be updated.
15694            synchronized (mPackages) {
15695                try {
15696                    updateSharedLibrariesLPr(pkg, null);
15697                } catch (PackageManagerException e) {
15698                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15699                }
15700            }
15701            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15702            // Do not run PackageDexOptimizer through the local performDexOpt
15703            // method because `pkg` may not be in `mPackages` yet.
15704            //
15705            // Also, don't fail application installs if the dexopt step fails.
15706            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15707                    null /* instructionSets */, false /* checkProfiles */,
15708                    getCompilerFilterForReason(REASON_INSTALL),
15709                    getOrCreateCompilerPackageStats(pkg));
15710            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15711
15712            // Notify BackgroundDexOptService that the package has been changed.
15713            // If this is an update of a package which used to fail to compile,
15714            // BDOS will remove it from its blacklist.
15715            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15716        }
15717
15718        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15719            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15720            return;
15721        }
15722
15723        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15724
15725        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15726                "installPackageLI")) {
15727            if (replace) {
15728                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15729                        installerPackageName, res);
15730            } else {
15731                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15732                        args.user, installerPackageName, volumeUuid, res);
15733            }
15734        }
15735        synchronized (mPackages) {
15736            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15737            if (ps != null) {
15738                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15739            }
15740
15741            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15742            for (int i = 0; i < childCount; i++) {
15743                PackageParser.Package childPkg = pkg.childPackages.get(i);
15744                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15745                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15746                if (childPs != null) {
15747                    childRes.newUsers = childPs.queryInstalledUsers(
15748                            sUserManager.getUserIds(), true);
15749                }
15750            }
15751        }
15752    }
15753
15754    private void startIntentFilterVerifications(int userId, boolean replacing,
15755            PackageParser.Package pkg) {
15756        if (mIntentFilterVerifierComponent == null) {
15757            Slog.w(TAG, "No IntentFilter verification will not be done as "
15758                    + "there is no IntentFilterVerifier available!");
15759            return;
15760        }
15761
15762        final int verifierUid = getPackageUid(
15763                mIntentFilterVerifierComponent.getPackageName(),
15764                MATCH_DEBUG_TRIAGED_MISSING,
15765                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15766
15767        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15768        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15769        mHandler.sendMessage(msg);
15770
15771        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15772        for (int i = 0; i < childCount; i++) {
15773            PackageParser.Package childPkg = pkg.childPackages.get(i);
15774            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15775            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15776            mHandler.sendMessage(msg);
15777        }
15778    }
15779
15780    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15781            PackageParser.Package pkg) {
15782        int size = pkg.activities.size();
15783        if (size == 0) {
15784            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15785                    "No activity, so no need to verify any IntentFilter!");
15786            return;
15787        }
15788
15789        final boolean hasDomainURLs = hasDomainURLs(pkg);
15790        if (!hasDomainURLs) {
15791            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15792                    "No domain URLs, so no need to verify any IntentFilter!");
15793            return;
15794        }
15795
15796        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15797                + " if any IntentFilter from the " + size
15798                + " Activities needs verification ...");
15799
15800        int count = 0;
15801        final String packageName = pkg.packageName;
15802
15803        synchronized (mPackages) {
15804            // If this is a new install and we see that we've already run verification for this
15805            // package, we have nothing to do: it means the state was restored from backup.
15806            if (!replacing) {
15807                IntentFilterVerificationInfo ivi =
15808                        mSettings.getIntentFilterVerificationLPr(packageName);
15809                if (ivi != null) {
15810                    if (DEBUG_DOMAIN_VERIFICATION) {
15811                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15812                                + ivi.getStatusString());
15813                    }
15814                    return;
15815                }
15816            }
15817
15818            // If any filters need to be verified, then all need to be.
15819            boolean needToVerify = false;
15820            for (PackageParser.Activity a : pkg.activities) {
15821                for (ActivityIntentInfo filter : a.intents) {
15822                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15823                        if (DEBUG_DOMAIN_VERIFICATION) {
15824                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15825                        }
15826                        needToVerify = true;
15827                        break;
15828                    }
15829                }
15830            }
15831
15832            if (needToVerify) {
15833                final int verificationId = mIntentFilterVerificationToken++;
15834                for (PackageParser.Activity a : pkg.activities) {
15835                    for (ActivityIntentInfo filter : a.intents) {
15836                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15837                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15838                                    "Verification needed for IntentFilter:" + filter.toString());
15839                            mIntentFilterVerifier.addOneIntentFilterVerification(
15840                                    verifierUid, userId, verificationId, filter, packageName);
15841                            count++;
15842                        }
15843                    }
15844                }
15845            }
15846        }
15847
15848        if (count > 0) {
15849            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15850                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15851                    +  " for userId:" + userId);
15852            mIntentFilterVerifier.startVerifications(userId);
15853        } else {
15854            if (DEBUG_DOMAIN_VERIFICATION) {
15855                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15856            }
15857        }
15858    }
15859
15860    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15861        final ComponentName cn  = filter.activity.getComponentName();
15862        final String packageName = cn.getPackageName();
15863
15864        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15865                packageName);
15866        if (ivi == null) {
15867            return true;
15868        }
15869        int status = ivi.getStatus();
15870        switch (status) {
15871            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15872            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15873                return true;
15874
15875            default:
15876                // Nothing to do
15877                return false;
15878        }
15879    }
15880
15881    private static boolean isMultiArch(ApplicationInfo info) {
15882        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15883    }
15884
15885    private static boolean isExternal(PackageParser.Package pkg) {
15886        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15887    }
15888
15889    private static boolean isExternal(PackageSetting ps) {
15890        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15891    }
15892
15893    private static boolean isEphemeral(PackageParser.Package pkg) {
15894        return pkg.applicationInfo.isEphemeralApp();
15895    }
15896
15897    private static boolean isEphemeral(PackageSetting ps) {
15898        return ps.pkg != null && isEphemeral(ps.pkg);
15899    }
15900
15901    private static boolean isSystemApp(PackageParser.Package pkg) {
15902        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15903    }
15904
15905    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15906        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15907    }
15908
15909    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15910        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15911    }
15912
15913    private static boolean isSystemApp(PackageSetting ps) {
15914        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15915    }
15916
15917    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15918        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15919    }
15920
15921    private int packageFlagsToInstallFlags(PackageSetting ps) {
15922        int installFlags = 0;
15923        if (isEphemeral(ps)) {
15924            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15925        }
15926        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15927            // This existing package was an external ASEC install when we have
15928            // the external flag without a UUID
15929            installFlags |= PackageManager.INSTALL_EXTERNAL;
15930        }
15931        if (ps.isForwardLocked()) {
15932            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15933        }
15934        return installFlags;
15935    }
15936
15937    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15938        if (isExternal(pkg)) {
15939            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15940                return StorageManager.UUID_PRIMARY_PHYSICAL;
15941            } else {
15942                return pkg.volumeUuid;
15943            }
15944        } else {
15945            return StorageManager.UUID_PRIVATE_INTERNAL;
15946        }
15947    }
15948
15949    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15950        if (isExternal(pkg)) {
15951            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15952                return mSettings.getExternalVersion();
15953            } else {
15954                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15955            }
15956        } else {
15957            return mSettings.getInternalVersion();
15958        }
15959    }
15960
15961    private void deleteTempPackageFiles() {
15962        final FilenameFilter filter = new FilenameFilter() {
15963            public boolean accept(File dir, String name) {
15964                return name.startsWith("vmdl") && name.endsWith(".tmp");
15965            }
15966        };
15967        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15968            file.delete();
15969        }
15970    }
15971
15972    @Override
15973    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15974            int flags) {
15975        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15976                flags);
15977    }
15978
15979    @Override
15980    public void deletePackage(final String packageName,
15981            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15982        mContext.enforceCallingOrSelfPermission(
15983                android.Manifest.permission.DELETE_PACKAGES, null);
15984        Preconditions.checkNotNull(packageName);
15985        Preconditions.checkNotNull(observer);
15986        final int uid = Binder.getCallingUid();
15987        if (!isOrphaned(packageName)
15988                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15989            try {
15990                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15991                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15992                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15993                observer.onUserActionRequired(intent);
15994            } catch (RemoteException re) {
15995            }
15996            return;
15997        }
15998        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15999        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16000        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16001            mContext.enforceCallingOrSelfPermission(
16002                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16003                    "deletePackage for user " + userId);
16004        }
16005
16006        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16007            try {
16008                observer.onPackageDeleted(packageName,
16009                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16010            } catch (RemoteException re) {
16011            }
16012            return;
16013        }
16014
16015        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16016            try {
16017                observer.onPackageDeleted(packageName,
16018                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16019            } catch (RemoteException re) {
16020            }
16021            return;
16022        }
16023
16024        if (DEBUG_REMOVE) {
16025            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16026                    + " deleteAllUsers: " + deleteAllUsers );
16027        }
16028        // Queue up an async operation since the package deletion may take a little while.
16029        mHandler.post(new Runnable() {
16030            public void run() {
16031                mHandler.removeCallbacks(this);
16032                int returnCode;
16033                if (!deleteAllUsers) {
16034                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16035                } else {
16036                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16037                    // If nobody is blocking uninstall, proceed with delete for all users
16038                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16039                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16040                    } else {
16041                        // Otherwise uninstall individually for users with blockUninstalls=false
16042                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16043                        for (int userId : users) {
16044                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16045                                returnCode = deletePackageX(packageName, userId, userFlags);
16046                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16047                                    Slog.w(TAG, "Package delete failed for user " + userId
16048                                            + ", returnCode " + returnCode);
16049                                }
16050                            }
16051                        }
16052                        // The app has only been marked uninstalled for certain users.
16053                        // We still need to report that delete was blocked
16054                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16055                    }
16056                }
16057                try {
16058                    observer.onPackageDeleted(packageName, returnCode, null);
16059                } catch (RemoteException e) {
16060                    Log.i(TAG, "Observer no longer exists.");
16061                } //end catch
16062            } //end run
16063        });
16064    }
16065
16066    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16067        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16068              || callingUid == Process.SYSTEM_UID) {
16069            return true;
16070        }
16071        final int callingUserId = UserHandle.getUserId(callingUid);
16072        // If the caller installed the pkgName, then allow it to silently uninstall.
16073        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16074            return true;
16075        }
16076
16077        // Allow package verifier to silently uninstall.
16078        if (mRequiredVerifierPackage != null &&
16079                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16080            return true;
16081        }
16082
16083        // Allow package uninstaller to silently uninstall.
16084        if (mRequiredUninstallerPackage != null &&
16085                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16086            return true;
16087        }
16088
16089        // Allow storage manager to silently uninstall.
16090        if (mStorageManagerPackage != null &&
16091                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16092            return true;
16093        }
16094        return false;
16095    }
16096
16097    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16098        int[] result = EMPTY_INT_ARRAY;
16099        for (int userId : userIds) {
16100            if (getBlockUninstallForUser(packageName, userId)) {
16101                result = ArrayUtils.appendInt(result, userId);
16102            }
16103        }
16104        return result;
16105    }
16106
16107    @Override
16108    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16109        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16110    }
16111
16112    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16113        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16114                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16115        try {
16116            if (dpm != null) {
16117                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16118                        /* callingUserOnly =*/ false);
16119                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16120                        : deviceOwnerComponentName.getPackageName();
16121                // Does the package contains the device owner?
16122                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16123                // this check is probably not needed, since DO should be registered as a device
16124                // admin on some user too. (Original bug for this: b/17657954)
16125                if (packageName.equals(deviceOwnerPackageName)) {
16126                    return true;
16127                }
16128                // Does it contain a device admin for any user?
16129                int[] users;
16130                if (userId == UserHandle.USER_ALL) {
16131                    users = sUserManager.getUserIds();
16132                } else {
16133                    users = new int[]{userId};
16134                }
16135                for (int i = 0; i < users.length; ++i) {
16136                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16137                        return true;
16138                    }
16139                }
16140            }
16141        } catch (RemoteException e) {
16142        }
16143        return false;
16144    }
16145
16146    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16147        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16148    }
16149
16150    /**
16151     *  This method is an internal method that could be get invoked either
16152     *  to delete an installed package or to clean up a failed installation.
16153     *  After deleting an installed package, a broadcast is sent to notify any
16154     *  listeners that the package has been removed. For cleaning up a failed
16155     *  installation, the broadcast is not necessary since the package's
16156     *  installation wouldn't have sent the initial broadcast either
16157     *  The key steps in deleting a package are
16158     *  deleting the package information in internal structures like mPackages,
16159     *  deleting the packages base directories through installd
16160     *  updating mSettings to reflect current status
16161     *  persisting settings for later use
16162     *  sending a broadcast if necessary
16163     */
16164    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16165        final PackageRemovedInfo info = new PackageRemovedInfo();
16166        final boolean res;
16167
16168        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16169                ? UserHandle.USER_ALL : userId;
16170
16171        if (isPackageDeviceAdmin(packageName, removeUser)) {
16172            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16173            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16174        }
16175
16176        PackageSetting uninstalledPs = null;
16177
16178        // for the uninstall-updates case and restricted profiles, remember the per-
16179        // user handle installed state
16180        int[] allUsers;
16181        synchronized (mPackages) {
16182            uninstalledPs = mSettings.mPackages.get(packageName);
16183            if (uninstalledPs == null) {
16184                Slog.w(TAG, "Not removing non-existent package " + packageName);
16185                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16186            }
16187            allUsers = sUserManager.getUserIds();
16188            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16189        }
16190
16191        final int freezeUser;
16192        if (isUpdatedSystemApp(uninstalledPs)
16193                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16194            // We're downgrading a system app, which will apply to all users, so
16195            // freeze them all during the downgrade
16196            freezeUser = UserHandle.USER_ALL;
16197        } else {
16198            freezeUser = removeUser;
16199        }
16200
16201        synchronized (mInstallLock) {
16202            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16203            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16204                    deleteFlags, "deletePackageX")) {
16205                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16206                        deleteFlags | REMOVE_CHATTY, info, true, null);
16207            }
16208            synchronized (mPackages) {
16209                if (res) {
16210                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16211                }
16212            }
16213        }
16214
16215        if (res) {
16216            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16217            info.sendPackageRemovedBroadcasts(killApp);
16218            info.sendSystemPackageUpdatedBroadcasts();
16219            info.sendSystemPackageAppearedBroadcasts();
16220        }
16221        // Force a gc here.
16222        Runtime.getRuntime().gc();
16223        // Delete the resources here after sending the broadcast to let
16224        // other processes clean up before deleting resources.
16225        if (info.args != null) {
16226            synchronized (mInstallLock) {
16227                info.args.doPostDeleteLI(true);
16228            }
16229        }
16230
16231        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16232    }
16233
16234    class PackageRemovedInfo {
16235        String removedPackage;
16236        int uid = -1;
16237        int removedAppId = -1;
16238        int[] origUsers;
16239        int[] removedUsers = null;
16240        boolean isRemovedPackageSystemUpdate = false;
16241        boolean isUpdate;
16242        boolean dataRemoved;
16243        boolean removedForAllUsers;
16244        // Clean up resources deleted packages.
16245        InstallArgs args = null;
16246        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16247        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16248
16249        void sendPackageRemovedBroadcasts(boolean killApp) {
16250            sendPackageRemovedBroadcastInternal(killApp);
16251            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16252            for (int i = 0; i < childCount; i++) {
16253                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16254                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16255            }
16256        }
16257
16258        void sendSystemPackageUpdatedBroadcasts() {
16259            if (isRemovedPackageSystemUpdate) {
16260                sendSystemPackageUpdatedBroadcastsInternal();
16261                final int childCount = (removedChildPackages != null)
16262                        ? removedChildPackages.size() : 0;
16263                for (int i = 0; i < childCount; i++) {
16264                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16265                    if (childInfo.isRemovedPackageSystemUpdate) {
16266                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16267                    }
16268                }
16269            }
16270        }
16271
16272        void sendSystemPackageAppearedBroadcasts() {
16273            final int packageCount = (appearedChildPackages != null)
16274                    ? appearedChildPackages.size() : 0;
16275            for (int i = 0; i < packageCount; i++) {
16276                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16277                sendPackageAddedForNewUsers(installedInfo.name, true,
16278                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16279            }
16280        }
16281
16282        private void sendSystemPackageUpdatedBroadcastsInternal() {
16283            Bundle extras = new Bundle(2);
16284            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16285            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16286            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16287                    extras, 0, null, null, null);
16288            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16289                    extras, 0, null, null, null);
16290            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16291                    null, 0, removedPackage, null, null);
16292        }
16293
16294        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16295            Bundle extras = new Bundle(2);
16296            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16297            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16298            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16299            if (isUpdate || isRemovedPackageSystemUpdate) {
16300                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16301            }
16302            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16303            if (removedPackage != null) {
16304                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16305                        extras, 0, null, null, removedUsers);
16306                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16307                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16308                            removedPackage, extras, 0, null, null, removedUsers);
16309                }
16310            }
16311            if (removedAppId >= 0) {
16312                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16313                        removedUsers);
16314            }
16315        }
16316    }
16317
16318    /*
16319     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16320     * flag is not set, the data directory is removed as well.
16321     * make sure this flag is set for partially installed apps. If not its meaningless to
16322     * delete a partially installed application.
16323     */
16324    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16325            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16326        String packageName = ps.name;
16327        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16328        // Retrieve object to delete permissions for shared user later on
16329        final PackageParser.Package deletedPkg;
16330        final PackageSetting deletedPs;
16331        // reader
16332        synchronized (mPackages) {
16333            deletedPkg = mPackages.get(packageName);
16334            deletedPs = mSettings.mPackages.get(packageName);
16335            if (outInfo != null) {
16336                outInfo.removedPackage = packageName;
16337                outInfo.removedUsers = deletedPs != null
16338                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16339                        : null;
16340            }
16341        }
16342
16343        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16344
16345        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16346            final PackageParser.Package resolvedPkg;
16347            if (deletedPkg != null) {
16348                resolvedPkg = deletedPkg;
16349            } else {
16350                // We don't have a parsed package when it lives on an ejected
16351                // adopted storage device, so fake something together
16352                resolvedPkg = new PackageParser.Package(ps.name);
16353                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16354            }
16355            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16356                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16357            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16358            if (outInfo != null) {
16359                outInfo.dataRemoved = true;
16360            }
16361            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16362        }
16363
16364        // writer
16365        synchronized (mPackages) {
16366            if (deletedPs != null) {
16367                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16368                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16369                    clearDefaultBrowserIfNeeded(packageName);
16370                    if (outInfo != null) {
16371                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16372                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16373                    }
16374                    updatePermissionsLPw(deletedPs.name, null, 0);
16375                    if (deletedPs.sharedUser != null) {
16376                        // Remove permissions associated with package. Since runtime
16377                        // permissions are per user we have to kill the removed package
16378                        // or packages running under the shared user of the removed
16379                        // package if revoking the permissions requested only by the removed
16380                        // package is successful and this causes a change in gids.
16381                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16382                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16383                                    userId);
16384                            if (userIdToKill == UserHandle.USER_ALL
16385                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16386                                // If gids changed for this user, kill all affected packages.
16387                                mHandler.post(new Runnable() {
16388                                    @Override
16389                                    public void run() {
16390                                        // This has to happen with no lock held.
16391                                        killApplication(deletedPs.name, deletedPs.appId,
16392                                                KILL_APP_REASON_GIDS_CHANGED);
16393                                    }
16394                                });
16395                                break;
16396                            }
16397                        }
16398                    }
16399                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16400                }
16401                // make sure to preserve per-user disabled state if this removal was just
16402                // a downgrade of a system app to the factory package
16403                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16404                    if (DEBUG_REMOVE) {
16405                        Slog.d(TAG, "Propagating install state across downgrade");
16406                    }
16407                    for (int userId : allUserHandles) {
16408                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16409                        if (DEBUG_REMOVE) {
16410                            Slog.d(TAG, "    user " + userId + " => " + installed);
16411                        }
16412                        ps.setInstalled(installed, userId);
16413                    }
16414                }
16415            }
16416            // can downgrade to reader
16417            if (writeSettings) {
16418                // Save settings now
16419                mSettings.writeLPr();
16420            }
16421        }
16422        if (outInfo != null) {
16423            // A user ID was deleted here. Go through all users and remove it
16424            // from KeyStore.
16425            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16426        }
16427    }
16428
16429    static boolean locationIsPrivileged(File path) {
16430        try {
16431            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16432                    .getCanonicalPath();
16433            return path.getCanonicalPath().startsWith(privilegedAppDir);
16434        } catch (IOException e) {
16435            Slog.e(TAG, "Unable to access code path " + path);
16436        }
16437        return false;
16438    }
16439
16440    /*
16441     * Tries to delete system package.
16442     */
16443    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16444            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16445            boolean writeSettings) {
16446        if (deletedPs.parentPackageName != null) {
16447            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16448            return false;
16449        }
16450
16451        final boolean applyUserRestrictions
16452                = (allUserHandles != null) && (outInfo.origUsers != null);
16453        final PackageSetting disabledPs;
16454        // Confirm if the system package has been updated
16455        // An updated system app can be deleted. This will also have to restore
16456        // the system pkg from system partition
16457        // reader
16458        synchronized (mPackages) {
16459            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16460        }
16461
16462        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16463                + " disabledPs=" + disabledPs);
16464
16465        if (disabledPs == null) {
16466            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16467            return false;
16468        } else if (DEBUG_REMOVE) {
16469            Slog.d(TAG, "Deleting system pkg from data partition");
16470        }
16471
16472        if (DEBUG_REMOVE) {
16473            if (applyUserRestrictions) {
16474                Slog.d(TAG, "Remembering install states:");
16475                for (int userId : allUserHandles) {
16476                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16477                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16478                }
16479            }
16480        }
16481
16482        // Delete the updated package
16483        outInfo.isRemovedPackageSystemUpdate = true;
16484        if (outInfo.removedChildPackages != null) {
16485            final int childCount = (deletedPs.childPackageNames != null)
16486                    ? deletedPs.childPackageNames.size() : 0;
16487            for (int i = 0; i < childCount; i++) {
16488                String childPackageName = deletedPs.childPackageNames.get(i);
16489                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16490                        .contains(childPackageName)) {
16491                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16492                            childPackageName);
16493                    if (childInfo != null) {
16494                        childInfo.isRemovedPackageSystemUpdate = true;
16495                    }
16496                }
16497            }
16498        }
16499
16500        if (disabledPs.versionCode < deletedPs.versionCode) {
16501            // Delete data for downgrades
16502            flags &= ~PackageManager.DELETE_KEEP_DATA;
16503        } else {
16504            // Preserve data by setting flag
16505            flags |= PackageManager.DELETE_KEEP_DATA;
16506        }
16507
16508        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16509                outInfo, writeSettings, disabledPs.pkg);
16510        if (!ret) {
16511            return false;
16512        }
16513
16514        // writer
16515        synchronized (mPackages) {
16516            // Reinstate the old system package
16517            enableSystemPackageLPw(disabledPs.pkg);
16518            // Remove any native libraries from the upgraded package.
16519            removeNativeBinariesLI(deletedPs);
16520        }
16521
16522        // Install the system package
16523        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16524        int parseFlags = mDefParseFlags
16525                | PackageParser.PARSE_MUST_BE_APK
16526                | PackageParser.PARSE_IS_SYSTEM
16527                | PackageParser.PARSE_IS_SYSTEM_DIR;
16528        if (locationIsPrivileged(disabledPs.codePath)) {
16529            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16530        }
16531
16532        final PackageParser.Package newPkg;
16533        try {
16534            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16535                0 /* currentTime */, null);
16536        } catch (PackageManagerException e) {
16537            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16538                    + e.getMessage());
16539            return false;
16540        }
16541        try {
16542            // update shared libraries for the newly re-installed system package
16543            updateSharedLibrariesLPr(newPkg, null);
16544        } catch (PackageManagerException e) {
16545            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16546        }
16547
16548        prepareAppDataAfterInstallLIF(newPkg);
16549
16550        // writer
16551        synchronized (mPackages) {
16552            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16553
16554            // Propagate the permissions state as we do not want to drop on the floor
16555            // runtime permissions. The update permissions method below will take
16556            // care of removing obsolete permissions and grant install permissions.
16557            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16558            updatePermissionsLPw(newPkg.packageName, newPkg,
16559                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16560
16561            if (applyUserRestrictions) {
16562                if (DEBUG_REMOVE) {
16563                    Slog.d(TAG, "Propagating install state across reinstall");
16564                }
16565                for (int userId : allUserHandles) {
16566                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16567                    if (DEBUG_REMOVE) {
16568                        Slog.d(TAG, "    user " + userId + " => " + installed);
16569                    }
16570                    ps.setInstalled(installed, userId);
16571
16572                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16573                }
16574                // Regardless of writeSettings we need to ensure that this restriction
16575                // state propagation is persisted
16576                mSettings.writeAllUsersPackageRestrictionsLPr();
16577            }
16578            // can downgrade to reader here
16579            if (writeSettings) {
16580                mSettings.writeLPr();
16581            }
16582        }
16583        return true;
16584    }
16585
16586    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16587            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16588            PackageRemovedInfo outInfo, boolean writeSettings,
16589            PackageParser.Package replacingPackage) {
16590        synchronized (mPackages) {
16591            if (outInfo != null) {
16592                outInfo.uid = ps.appId;
16593            }
16594
16595            if (outInfo != null && outInfo.removedChildPackages != null) {
16596                final int childCount = (ps.childPackageNames != null)
16597                        ? ps.childPackageNames.size() : 0;
16598                for (int i = 0; i < childCount; i++) {
16599                    String childPackageName = ps.childPackageNames.get(i);
16600                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16601                    if (childPs == null) {
16602                        return false;
16603                    }
16604                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16605                            childPackageName);
16606                    if (childInfo != null) {
16607                        childInfo.uid = childPs.appId;
16608                    }
16609                }
16610            }
16611        }
16612
16613        // Delete package data from internal structures and also remove data if flag is set
16614        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16615
16616        // Delete the child packages data
16617        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16618        for (int i = 0; i < childCount; i++) {
16619            PackageSetting childPs;
16620            synchronized (mPackages) {
16621                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16622            }
16623            if (childPs != null) {
16624                PackageRemovedInfo childOutInfo = (outInfo != null
16625                        && outInfo.removedChildPackages != null)
16626                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16627                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16628                        && (replacingPackage != null
16629                        && !replacingPackage.hasChildPackage(childPs.name))
16630                        ? flags & ~DELETE_KEEP_DATA : flags;
16631                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16632                        deleteFlags, writeSettings);
16633            }
16634        }
16635
16636        // Delete application code and resources only for parent packages
16637        if (ps.parentPackageName == null) {
16638            if (deleteCodeAndResources && (outInfo != null)) {
16639                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16640                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16641                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16642            }
16643        }
16644
16645        return true;
16646    }
16647
16648    @Override
16649    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16650            int userId) {
16651        mContext.enforceCallingOrSelfPermission(
16652                android.Manifest.permission.DELETE_PACKAGES, null);
16653        synchronized (mPackages) {
16654            PackageSetting ps = mSettings.mPackages.get(packageName);
16655            if (ps == null) {
16656                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16657                return false;
16658            }
16659            if (!ps.getInstalled(userId)) {
16660                // Can't block uninstall for an app that is not installed or enabled.
16661                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16662                return false;
16663            }
16664            ps.setBlockUninstall(blockUninstall, userId);
16665            mSettings.writePackageRestrictionsLPr(userId);
16666        }
16667        return true;
16668    }
16669
16670    @Override
16671    public boolean getBlockUninstallForUser(String packageName, int userId) {
16672        synchronized (mPackages) {
16673            PackageSetting ps = mSettings.mPackages.get(packageName);
16674            if (ps == null) {
16675                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16676                return false;
16677            }
16678            return ps.getBlockUninstall(userId);
16679        }
16680    }
16681
16682    @Override
16683    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16684        int callingUid = Binder.getCallingUid();
16685        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16686            throw new SecurityException(
16687                    "setRequiredForSystemUser can only be run by the system or root");
16688        }
16689        synchronized (mPackages) {
16690            PackageSetting ps = mSettings.mPackages.get(packageName);
16691            if (ps == null) {
16692                Log.w(TAG, "Package doesn't exist: " + packageName);
16693                return false;
16694            }
16695            if (systemUserApp) {
16696                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16697            } else {
16698                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16699            }
16700            mSettings.writeLPr();
16701        }
16702        return true;
16703    }
16704
16705    /*
16706     * This method handles package deletion in general
16707     */
16708    private boolean deletePackageLIF(String packageName, UserHandle user,
16709            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16710            PackageRemovedInfo outInfo, boolean writeSettings,
16711            PackageParser.Package replacingPackage) {
16712        if (packageName == null) {
16713            Slog.w(TAG, "Attempt to delete null packageName.");
16714            return false;
16715        }
16716
16717        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16718
16719        PackageSetting ps;
16720
16721        synchronized (mPackages) {
16722            ps = mSettings.mPackages.get(packageName);
16723            if (ps == null) {
16724                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16725                return false;
16726            }
16727
16728            if (ps.parentPackageName != null && (!isSystemApp(ps)
16729                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16730                if (DEBUG_REMOVE) {
16731                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16732                            + ((user == null) ? UserHandle.USER_ALL : user));
16733                }
16734                final int removedUserId = (user != null) ? user.getIdentifier()
16735                        : UserHandle.USER_ALL;
16736                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16737                    return false;
16738                }
16739                markPackageUninstalledForUserLPw(ps, user);
16740                scheduleWritePackageRestrictionsLocked(user);
16741                return true;
16742            }
16743        }
16744
16745        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16746                && user.getIdentifier() != UserHandle.USER_ALL)) {
16747            // The caller is asking that the package only be deleted for a single
16748            // user.  To do this, we just mark its uninstalled state and delete
16749            // its data. If this is a system app, we only allow this to happen if
16750            // they have set the special DELETE_SYSTEM_APP which requests different
16751            // semantics than normal for uninstalling system apps.
16752            markPackageUninstalledForUserLPw(ps, user);
16753
16754            if (!isSystemApp(ps)) {
16755                // Do not uninstall the APK if an app should be cached
16756                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16757                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16758                    // Other user still have this package installed, so all
16759                    // we need to do is clear this user's data and save that
16760                    // it is uninstalled.
16761                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16762                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16763                        return false;
16764                    }
16765                    scheduleWritePackageRestrictionsLocked(user);
16766                    return true;
16767                } else {
16768                    // We need to set it back to 'installed' so the uninstall
16769                    // broadcasts will be sent correctly.
16770                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16771                    ps.setInstalled(true, user.getIdentifier());
16772                }
16773            } else {
16774                // This is a system app, so we assume that the
16775                // other users still have this package installed, so all
16776                // we need to do is clear this user's data and save that
16777                // it is uninstalled.
16778                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16779                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16780                    return false;
16781                }
16782                scheduleWritePackageRestrictionsLocked(user);
16783                return true;
16784            }
16785        }
16786
16787        // If we are deleting a composite package for all users, keep track
16788        // of result for each child.
16789        if (ps.childPackageNames != null && outInfo != null) {
16790            synchronized (mPackages) {
16791                final int childCount = ps.childPackageNames.size();
16792                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16793                for (int i = 0; i < childCount; i++) {
16794                    String childPackageName = ps.childPackageNames.get(i);
16795                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16796                    childInfo.removedPackage = childPackageName;
16797                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16798                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16799                    if (childPs != null) {
16800                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16801                    }
16802                }
16803            }
16804        }
16805
16806        boolean ret = false;
16807        if (isSystemApp(ps)) {
16808            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16809            // When an updated system application is deleted we delete the existing resources
16810            // as well and fall back to existing code in system partition
16811            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16812        } else {
16813            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16814            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16815                    outInfo, writeSettings, replacingPackage);
16816        }
16817
16818        // Take a note whether we deleted the package for all users
16819        if (outInfo != null) {
16820            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16821            if (outInfo.removedChildPackages != null) {
16822                synchronized (mPackages) {
16823                    final int childCount = outInfo.removedChildPackages.size();
16824                    for (int i = 0; i < childCount; i++) {
16825                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16826                        if (childInfo != null) {
16827                            childInfo.removedForAllUsers = mPackages.get(
16828                                    childInfo.removedPackage) == null;
16829                        }
16830                    }
16831                }
16832            }
16833            // If we uninstalled an update to a system app there may be some
16834            // child packages that appeared as they are declared in the system
16835            // app but were not declared in the update.
16836            if (isSystemApp(ps)) {
16837                synchronized (mPackages) {
16838                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16839                    final int childCount = (updatedPs.childPackageNames != null)
16840                            ? updatedPs.childPackageNames.size() : 0;
16841                    for (int i = 0; i < childCount; i++) {
16842                        String childPackageName = updatedPs.childPackageNames.get(i);
16843                        if (outInfo.removedChildPackages == null
16844                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16845                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16846                            if (childPs == null) {
16847                                continue;
16848                            }
16849                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16850                            installRes.name = childPackageName;
16851                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16852                            installRes.pkg = mPackages.get(childPackageName);
16853                            installRes.uid = childPs.pkg.applicationInfo.uid;
16854                            if (outInfo.appearedChildPackages == null) {
16855                                outInfo.appearedChildPackages = new ArrayMap<>();
16856                            }
16857                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16858                        }
16859                    }
16860                }
16861            }
16862        }
16863
16864        return ret;
16865    }
16866
16867    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16868        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16869                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16870        for (int nextUserId : userIds) {
16871            if (DEBUG_REMOVE) {
16872                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16873            }
16874            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16875                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16876                    false /*hidden*/, false /*suspended*/, null, null, null,
16877                    false /*blockUninstall*/,
16878                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16879        }
16880    }
16881
16882    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16883            PackageRemovedInfo outInfo) {
16884        final PackageParser.Package pkg;
16885        synchronized (mPackages) {
16886            pkg = mPackages.get(ps.name);
16887        }
16888
16889        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16890                : new int[] {userId};
16891        for (int nextUserId : userIds) {
16892            if (DEBUG_REMOVE) {
16893                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16894                        + nextUserId);
16895            }
16896
16897            destroyAppDataLIF(pkg, userId,
16898                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16899            destroyAppProfilesLIF(pkg, userId);
16900            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16901            schedulePackageCleaning(ps.name, nextUserId, false);
16902            synchronized (mPackages) {
16903                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16904                    scheduleWritePackageRestrictionsLocked(nextUserId);
16905                }
16906                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16907            }
16908        }
16909
16910        if (outInfo != null) {
16911            outInfo.removedPackage = ps.name;
16912            outInfo.removedAppId = ps.appId;
16913            outInfo.removedUsers = userIds;
16914        }
16915
16916        return true;
16917    }
16918
16919    private final class ClearStorageConnection implements ServiceConnection {
16920        IMediaContainerService mContainerService;
16921
16922        @Override
16923        public void onServiceConnected(ComponentName name, IBinder service) {
16924            synchronized (this) {
16925                mContainerService = IMediaContainerService.Stub
16926                        .asInterface(Binder.allowBlocking(service));
16927                notifyAll();
16928            }
16929        }
16930
16931        @Override
16932        public void onServiceDisconnected(ComponentName name) {
16933        }
16934    }
16935
16936    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16937        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16938
16939        final boolean mounted;
16940        if (Environment.isExternalStorageEmulated()) {
16941            mounted = true;
16942        } else {
16943            final String status = Environment.getExternalStorageState();
16944
16945            mounted = status.equals(Environment.MEDIA_MOUNTED)
16946                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16947        }
16948
16949        if (!mounted) {
16950            return;
16951        }
16952
16953        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16954        int[] users;
16955        if (userId == UserHandle.USER_ALL) {
16956            users = sUserManager.getUserIds();
16957        } else {
16958            users = new int[] { userId };
16959        }
16960        final ClearStorageConnection conn = new ClearStorageConnection();
16961        if (mContext.bindServiceAsUser(
16962                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16963            try {
16964                for (int curUser : users) {
16965                    long timeout = SystemClock.uptimeMillis() + 5000;
16966                    synchronized (conn) {
16967                        long now;
16968                        while (conn.mContainerService == null &&
16969                                (now = SystemClock.uptimeMillis()) < timeout) {
16970                            try {
16971                                conn.wait(timeout - now);
16972                            } catch (InterruptedException e) {
16973                            }
16974                        }
16975                    }
16976                    if (conn.mContainerService == null) {
16977                        return;
16978                    }
16979
16980                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16981                    clearDirectory(conn.mContainerService,
16982                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16983                    if (allData) {
16984                        clearDirectory(conn.mContainerService,
16985                                userEnv.buildExternalStorageAppDataDirs(packageName));
16986                        clearDirectory(conn.mContainerService,
16987                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16988                    }
16989                }
16990            } finally {
16991                mContext.unbindService(conn);
16992            }
16993        }
16994    }
16995
16996    @Override
16997    public void clearApplicationProfileData(String packageName) {
16998        enforceSystemOrRoot("Only the system can clear all profile data");
16999
17000        final PackageParser.Package pkg;
17001        synchronized (mPackages) {
17002            pkg = mPackages.get(packageName);
17003        }
17004
17005        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17006            synchronized (mInstallLock) {
17007                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17008                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17009                        true /* removeBaseMarker */);
17010            }
17011        }
17012    }
17013
17014    @Override
17015    public void clearApplicationUserData(final String packageName,
17016            final IPackageDataObserver observer, final int userId) {
17017        mContext.enforceCallingOrSelfPermission(
17018                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17019
17020        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17021                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17022
17023        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17024            throw new SecurityException("Cannot clear data for a protected package: "
17025                    + packageName);
17026        }
17027        // Queue up an async operation since the package deletion may take a little while.
17028        mHandler.post(new Runnable() {
17029            public void run() {
17030                mHandler.removeCallbacks(this);
17031                final boolean succeeded;
17032                try (PackageFreezer freezer = freezePackage(packageName,
17033                        "clearApplicationUserData")) {
17034                    synchronized (mInstallLock) {
17035                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17036                    }
17037                    clearExternalStorageDataSync(packageName, userId, true);
17038                }
17039                if (succeeded) {
17040                    // invoke DeviceStorageMonitor's update method to clear any notifications
17041                    DeviceStorageMonitorInternal dsm = LocalServices
17042                            .getService(DeviceStorageMonitorInternal.class);
17043                    if (dsm != null) {
17044                        dsm.checkMemory();
17045                    }
17046                }
17047                if(observer != null) {
17048                    try {
17049                        observer.onRemoveCompleted(packageName, succeeded);
17050                    } catch (RemoteException e) {
17051                        Log.i(TAG, "Observer no longer exists.");
17052                    }
17053                } //end if observer
17054            } //end run
17055        });
17056    }
17057
17058    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17059        if (packageName == null) {
17060            Slog.w(TAG, "Attempt to delete null packageName.");
17061            return false;
17062        }
17063
17064        // Try finding details about the requested package
17065        PackageParser.Package pkg;
17066        synchronized (mPackages) {
17067            pkg = mPackages.get(packageName);
17068            if (pkg == null) {
17069                final PackageSetting ps = mSettings.mPackages.get(packageName);
17070                if (ps != null) {
17071                    pkg = ps.pkg;
17072                }
17073            }
17074
17075            if (pkg == null) {
17076                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17077                return false;
17078            }
17079
17080            PackageSetting ps = (PackageSetting) pkg.mExtras;
17081            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17082        }
17083
17084        clearAppDataLIF(pkg, userId,
17085                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17086
17087        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17088        removeKeystoreDataIfNeeded(userId, appId);
17089
17090        UserManagerInternal umInternal = getUserManagerInternal();
17091        final int flags;
17092        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17093            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17094        } else if (umInternal.isUserRunning(userId)) {
17095            flags = StorageManager.FLAG_STORAGE_DE;
17096        } else {
17097            flags = 0;
17098        }
17099        prepareAppDataContentsLIF(pkg, userId, flags);
17100
17101        return true;
17102    }
17103
17104    /**
17105     * Reverts user permission state changes (permissions and flags) in
17106     * all packages for a given user.
17107     *
17108     * @param userId The device user for which to do a reset.
17109     */
17110    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17111        final int packageCount = mPackages.size();
17112        for (int i = 0; i < packageCount; i++) {
17113            PackageParser.Package pkg = mPackages.valueAt(i);
17114            PackageSetting ps = (PackageSetting) pkg.mExtras;
17115            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17116        }
17117    }
17118
17119    private void resetNetworkPolicies(int userId) {
17120        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17121    }
17122
17123    /**
17124     * Reverts user permission state changes (permissions and flags).
17125     *
17126     * @param ps The package for which to reset.
17127     * @param userId The device user for which to do a reset.
17128     */
17129    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17130            final PackageSetting ps, final int userId) {
17131        if (ps.pkg == null) {
17132            return;
17133        }
17134
17135        // These are flags that can change base on user actions.
17136        final int userSettableMask = FLAG_PERMISSION_USER_SET
17137                | FLAG_PERMISSION_USER_FIXED
17138                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17139                | FLAG_PERMISSION_REVIEW_REQUIRED;
17140
17141        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17142                | FLAG_PERMISSION_POLICY_FIXED;
17143
17144        boolean writeInstallPermissions = false;
17145        boolean writeRuntimePermissions = false;
17146
17147        final int permissionCount = ps.pkg.requestedPermissions.size();
17148        for (int i = 0; i < permissionCount; i++) {
17149            String permission = ps.pkg.requestedPermissions.get(i);
17150
17151            BasePermission bp = mSettings.mPermissions.get(permission);
17152            if (bp == null) {
17153                continue;
17154            }
17155
17156            // If shared user we just reset the state to which only this app contributed.
17157            if (ps.sharedUser != null) {
17158                boolean used = false;
17159                final int packageCount = ps.sharedUser.packages.size();
17160                for (int j = 0; j < packageCount; j++) {
17161                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17162                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17163                            && pkg.pkg.requestedPermissions.contains(permission)) {
17164                        used = true;
17165                        break;
17166                    }
17167                }
17168                if (used) {
17169                    continue;
17170                }
17171            }
17172
17173            PermissionsState permissionsState = ps.getPermissionsState();
17174
17175            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17176
17177            // Always clear the user settable flags.
17178            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17179                    bp.name) != null;
17180            // If permission review is enabled and this is a legacy app, mark the
17181            // permission as requiring a review as this is the initial state.
17182            int flags = 0;
17183            if (mPermissionReviewRequired
17184                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17185                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17186            }
17187            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17188                if (hasInstallState) {
17189                    writeInstallPermissions = true;
17190                } else {
17191                    writeRuntimePermissions = true;
17192                }
17193            }
17194
17195            // Below is only runtime permission handling.
17196            if (!bp.isRuntime()) {
17197                continue;
17198            }
17199
17200            // Never clobber system or policy.
17201            if ((oldFlags & policyOrSystemFlags) != 0) {
17202                continue;
17203            }
17204
17205            // If this permission was granted by default, make sure it is.
17206            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17207                if (permissionsState.grantRuntimePermission(bp, userId)
17208                        != PERMISSION_OPERATION_FAILURE) {
17209                    writeRuntimePermissions = true;
17210                }
17211            // If permission review is enabled the permissions for a legacy apps
17212            // are represented as constantly granted runtime ones, so don't revoke.
17213            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17214                // Otherwise, reset the permission.
17215                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17216                switch (revokeResult) {
17217                    case PERMISSION_OPERATION_SUCCESS:
17218                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17219                        writeRuntimePermissions = true;
17220                        final int appId = ps.appId;
17221                        mHandler.post(new Runnable() {
17222                            @Override
17223                            public void run() {
17224                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17225                            }
17226                        });
17227                    } break;
17228                }
17229            }
17230        }
17231
17232        // Synchronously write as we are taking permissions away.
17233        if (writeRuntimePermissions) {
17234            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17235        }
17236
17237        // Synchronously write as we are taking permissions away.
17238        if (writeInstallPermissions) {
17239            mSettings.writeLPr();
17240        }
17241    }
17242
17243    /**
17244     * Remove entries from the keystore daemon. Will only remove it if the
17245     * {@code appId} is valid.
17246     */
17247    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17248        if (appId < 0) {
17249            return;
17250        }
17251
17252        final KeyStore keyStore = KeyStore.getInstance();
17253        if (keyStore != null) {
17254            if (userId == UserHandle.USER_ALL) {
17255                for (final int individual : sUserManager.getUserIds()) {
17256                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17257                }
17258            } else {
17259                keyStore.clearUid(UserHandle.getUid(userId, appId));
17260            }
17261        } else {
17262            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17263        }
17264    }
17265
17266    @Override
17267    public void deleteApplicationCacheFiles(final String packageName,
17268            final IPackageDataObserver observer) {
17269        final int userId = UserHandle.getCallingUserId();
17270        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17271    }
17272
17273    @Override
17274    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17275            final IPackageDataObserver observer) {
17276        mContext.enforceCallingOrSelfPermission(
17277                android.Manifest.permission.DELETE_CACHE_FILES, null);
17278        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17279                /* requireFullPermission= */ true, /* checkShell= */ false,
17280                "delete application cache files");
17281
17282        final PackageParser.Package pkg;
17283        synchronized (mPackages) {
17284            pkg = mPackages.get(packageName);
17285        }
17286
17287        // Queue up an async operation since the package deletion may take a little while.
17288        mHandler.post(new Runnable() {
17289            public void run() {
17290                synchronized (mInstallLock) {
17291                    final int flags = StorageManager.FLAG_STORAGE_DE
17292                            | StorageManager.FLAG_STORAGE_CE;
17293                    // We're only clearing cache files, so we don't care if the
17294                    // app is unfrozen and still able to run
17295                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17296                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17297                }
17298                clearExternalStorageDataSync(packageName, userId, false);
17299                if (observer != null) {
17300                    try {
17301                        observer.onRemoveCompleted(packageName, true);
17302                    } catch (RemoteException e) {
17303                        Log.i(TAG, "Observer no longer exists.");
17304                    }
17305                }
17306            }
17307        });
17308    }
17309
17310    @Override
17311    public void getPackageSizeInfo(final String packageName, int userHandle,
17312            final IPackageStatsObserver observer) {
17313        mContext.enforceCallingOrSelfPermission(
17314                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17315        if (packageName == null) {
17316            throw new IllegalArgumentException("Attempt to get size of null packageName");
17317        }
17318
17319        PackageStats stats = new PackageStats(packageName, userHandle);
17320
17321        /*
17322         * Queue up an async operation since the package measurement may take a
17323         * little while.
17324         */
17325        Message msg = mHandler.obtainMessage(INIT_COPY);
17326        msg.obj = new MeasureParams(stats, observer);
17327        mHandler.sendMessage(msg);
17328    }
17329
17330    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17331        final PackageSetting ps;
17332        synchronized (mPackages) {
17333            ps = mSettings.mPackages.get(packageName);
17334            if (ps == null) {
17335                Slog.w(TAG, "Failed to find settings for " + packageName);
17336                return false;
17337            }
17338        }
17339        try {
17340            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17341                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17342                    ps.getCeDataInode(userId), ps.codePathString, stats);
17343        } catch (InstallerException e) {
17344            Slog.w(TAG, String.valueOf(e));
17345            return false;
17346        }
17347
17348        // For now, ignore code size of packages on system partition
17349        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17350            stats.codeSize = 0;
17351        }
17352
17353        return true;
17354    }
17355
17356    private int getUidTargetSdkVersionLockedLPr(int uid) {
17357        Object obj = mSettings.getUserIdLPr(uid);
17358        if (obj instanceof SharedUserSetting) {
17359            final SharedUserSetting sus = (SharedUserSetting) obj;
17360            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17361            final Iterator<PackageSetting> it = sus.packages.iterator();
17362            while (it.hasNext()) {
17363                final PackageSetting ps = it.next();
17364                if (ps.pkg != null) {
17365                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17366                    if (v < vers) vers = v;
17367                }
17368            }
17369            return vers;
17370        } else if (obj instanceof PackageSetting) {
17371            final PackageSetting ps = (PackageSetting) obj;
17372            if (ps.pkg != null) {
17373                return ps.pkg.applicationInfo.targetSdkVersion;
17374            }
17375        }
17376        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17377    }
17378
17379    @Override
17380    public void addPreferredActivity(IntentFilter filter, int match,
17381            ComponentName[] set, ComponentName activity, int userId) {
17382        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17383                "Adding preferred");
17384    }
17385
17386    private void addPreferredActivityInternal(IntentFilter filter, int match,
17387            ComponentName[] set, ComponentName activity, boolean always, int userId,
17388            String opname) {
17389        // writer
17390        int callingUid = Binder.getCallingUid();
17391        enforceCrossUserPermission(callingUid, userId,
17392                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17393        if (filter.countActions() == 0) {
17394            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17395            return;
17396        }
17397        synchronized (mPackages) {
17398            if (mContext.checkCallingOrSelfPermission(
17399                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17400                    != PackageManager.PERMISSION_GRANTED) {
17401                if (getUidTargetSdkVersionLockedLPr(callingUid)
17402                        < Build.VERSION_CODES.FROYO) {
17403                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17404                            + callingUid);
17405                    return;
17406                }
17407                mContext.enforceCallingOrSelfPermission(
17408                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17409            }
17410
17411            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17412            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17413                    + userId + ":");
17414            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17415            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17416            scheduleWritePackageRestrictionsLocked(userId);
17417            postPreferredActivityChangedBroadcast(userId);
17418        }
17419    }
17420
17421    private void postPreferredActivityChangedBroadcast(int userId) {
17422        mHandler.post(() -> {
17423            final IActivityManager am = ActivityManager.getService();
17424            if (am == null) {
17425                return;
17426            }
17427
17428            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17429            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17430            try {
17431                am.broadcastIntent(null, intent, null, null,
17432                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17433                        null, false, false, userId);
17434            } catch (RemoteException e) {
17435            }
17436        });
17437    }
17438
17439    @Override
17440    public void replacePreferredActivity(IntentFilter filter, int match,
17441            ComponentName[] set, ComponentName activity, int userId) {
17442        if (filter.countActions() != 1) {
17443            throw new IllegalArgumentException(
17444                    "replacePreferredActivity expects filter to have only 1 action.");
17445        }
17446        if (filter.countDataAuthorities() != 0
17447                || filter.countDataPaths() != 0
17448                || filter.countDataSchemes() > 1
17449                || filter.countDataTypes() != 0) {
17450            throw new IllegalArgumentException(
17451                    "replacePreferredActivity expects filter to have no data authorities, " +
17452                    "paths, or types; and at most one scheme.");
17453        }
17454
17455        final int callingUid = Binder.getCallingUid();
17456        enforceCrossUserPermission(callingUid, userId,
17457                true /* requireFullPermission */, false /* checkShell */,
17458                "replace preferred activity");
17459        synchronized (mPackages) {
17460            if (mContext.checkCallingOrSelfPermission(
17461                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17462                    != PackageManager.PERMISSION_GRANTED) {
17463                if (getUidTargetSdkVersionLockedLPr(callingUid)
17464                        < Build.VERSION_CODES.FROYO) {
17465                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17466                            + Binder.getCallingUid());
17467                    return;
17468                }
17469                mContext.enforceCallingOrSelfPermission(
17470                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17471            }
17472
17473            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17474            if (pir != null) {
17475                // Get all of the existing entries that exactly match this filter.
17476                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17477                if (existing != null && existing.size() == 1) {
17478                    PreferredActivity cur = existing.get(0);
17479                    if (DEBUG_PREFERRED) {
17480                        Slog.i(TAG, "Checking replace of preferred:");
17481                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17482                        if (!cur.mPref.mAlways) {
17483                            Slog.i(TAG, "  -- CUR; not mAlways!");
17484                        } else {
17485                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17486                            Slog.i(TAG, "  -- CUR: mSet="
17487                                    + Arrays.toString(cur.mPref.mSetComponents));
17488                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17489                            Slog.i(TAG, "  -- NEW: mMatch="
17490                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17491                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17492                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17493                        }
17494                    }
17495                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17496                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17497                            && cur.mPref.sameSet(set)) {
17498                        // Setting the preferred activity to what it happens to be already
17499                        if (DEBUG_PREFERRED) {
17500                            Slog.i(TAG, "Replacing with same preferred activity "
17501                                    + cur.mPref.mShortComponent + " for user "
17502                                    + userId + ":");
17503                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17504                        }
17505                        return;
17506                    }
17507                }
17508
17509                if (existing != null) {
17510                    if (DEBUG_PREFERRED) {
17511                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17512                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17513                    }
17514                    for (int i = 0; i < existing.size(); i++) {
17515                        PreferredActivity pa = existing.get(i);
17516                        if (DEBUG_PREFERRED) {
17517                            Slog.i(TAG, "Removing existing preferred activity "
17518                                    + pa.mPref.mComponent + ":");
17519                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17520                        }
17521                        pir.removeFilter(pa);
17522                    }
17523                }
17524            }
17525            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17526                    "Replacing preferred");
17527        }
17528    }
17529
17530    @Override
17531    public void clearPackagePreferredActivities(String packageName) {
17532        final int uid = Binder.getCallingUid();
17533        // writer
17534        synchronized (mPackages) {
17535            PackageParser.Package pkg = mPackages.get(packageName);
17536            if (pkg == null || pkg.applicationInfo.uid != uid) {
17537                if (mContext.checkCallingOrSelfPermission(
17538                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17539                        != PackageManager.PERMISSION_GRANTED) {
17540                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17541                            < Build.VERSION_CODES.FROYO) {
17542                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17543                                + Binder.getCallingUid());
17544                        return;
17545                    }
17546                    mContext.enforceCallingOrSelfPermission(
17547                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17548                }
17549            }
17550
17551            int user = UserHandle.getCallingUserId();
17552            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17553                scheduleWritePackageRestrictionsLocked(user);
17554            }
17555        }
17556    }
17557
17558    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17559    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17560        ArrayList<PreferredActivity> removed = null;
17561        boolean changed = false;
17562        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17563            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17564            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17565            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17566                continue;
17567            }
17568            Iterator<PreferredActivity> it = pir.filterIterator();
17569            while (it.hasNext()) {
17570                PreferredActivity pa = it.next();
17571                // Mark entry for removal only if it matches the package name
17572                // and the entry is of type "always".
17573                if (packageName == null ||
17574                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17575                                && pa.mPref.mAlways)) {
17576                    if (removed == null) {
17577                        removed = new ArrayList<PreferredActivity>();
17578                    }
17579                    removed.add(pa);
17580                }
17581            }
17582            if (removed != null) {
17583                for (int j=0; j<removed.size(); j++) {
17584                    PreferredActivity pa = removed.get(j);
17585                    pir.removeFilter(pa);
17586                }
17587                changed = true;
17588            }
17589        }
17590        if (changed) {
17591            postPreferredActivityChangedBroadcast(userId);
17592        }
17593        return changed;
17594    }
17595
17596    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17597    private void clearIntentFilterVerificationsLPw(int userId) {
17598        final int packageCount = mPackages.size();
17599        for (int i = 0; i < packageCount; i++) {
17600            PackageParser.Package pkg = mPackages.valueAt(i);
17601            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17602        }
17603    }
17604
17605    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17606    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17607        if (userId == UserHandle.USER_ALL) {
17608            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17609                    sUserManager.getUserIds())) {
17610                for (int oneUserId : sUserManager.getUserIds()) {
17611                    scheduleWritePackageRestrictionsLocked(oneUserId);
17612                }
17613            }
17614        } else {
17615            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17616                scheduleWritePackageRestrictionsLocked(userId);
17617            }
17618        }
17619    }
17620
17621    void clearDefaultBrowserIfNeeded(String packageName) {
17622        for (int oneUserId : sUserManager.getUserIds()) {
17623            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17624            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17625            if (packageName.equals(defaultBrowserPackageName)) {
17626                setDefaultBrowserPackageName(null, oneUserId);
17627            }
17628        }
17629    }
17630
17631    @Override
17632    public void resetApplicationPreferences(int userId) {
17633        mContext.enforceCallingOrSelfPermission(
17634                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17635        final long identity = Binder.clearCallingIdentity();
17636        // writer
17637        try {
17638            synchronized (mPackages) {
17639                clearPackagePreferredActivitiesLPw(null, userId);
17640                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17641                // TODO: We have to reset the default SMS and Phone. This requires
17642                // significant refactoring to keep all default apps in the package
17643                // manager (cleaner but more work) or have the services provide
17644                // callbacks to the package manager to request a default app reset.
17645                applyFactoryDefaultBrowserLPw(userId);
17646                clearIntentFilterVerificationsLPw(userId);
17647                primeDomainVerificationsLPw(userId);
17648                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17649                scheduleWritePackageRestrictionsLocked(userId);
17650            }
17651            resetNetworkPolicies(userId);
17652        } finally {
17653            Binder.restoreCallingIdentity(identity);
17654        }
17655    }
17656
17657    @Override
17658    public int getPreferredActivities(List<IntentFilter> outFilters,
17659            List<ComponentName> outActivities, String packageName) {
17660
17661        int num = 0;
17662        final int userId = UserHandle.getCallingUserId();
17663        // reader
17664        synchronized (mPackages) {
17665            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17666            if (pir != null) {
17667                final Iterator<PreferredActivity> it = pir.filterIterator();
17668                while (it.hasNext()) {
17669                    final PreferredActivity pa = it.next();
17670                    if (packageName == null
17671                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17672                                    && pa.mPref.mAlways)) {
17673                        if (outFilters != null) {
17674                            outFilters.add(new IntentFilter(pa));
17675                        }
17676                        if (outActivities != null) {
17677                            outActivities.add(pa.mPref.mComponent);
17678                        }
17679                    }
17680                }
17681            }
17682        }
17683
17684        return num;
17685    }
17686
17687    @Override
17688    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17689            int userId) {
17690        int callingUid = Binder.getCallingUid();
17691        if (callingUid != Process.SYSTEM_UID) {
17692            throw new SecurityException(
17693                    "addPersistentPreferredActivity can only be run by the system");
17694        }
17695        if (filter.countActions() == 0) {
17696            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17697            return;
17698        }
17699        synchronized (mPackages) {
17700            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17701                    ":");
17702            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17703            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17704                    new PersistentPreferredActivity(filter, activity));
17705            scheduleWritePackageRestrictionsLocked(userId);
17706            postPreferredActivityChangedBroadcast(userId);
17707        }
17708    }
17709
17710    @Override
17711    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17712        int callingUid = Binder.getCallingUid();
17713        if (callingUid != Process.SYSTEM_UID) {
17714            throw new SecurityException(
17715                    "clearPackagePersistentPreferredActivities can only be run by the system");
17716        }
17717        ArrayList<PersistentPreferredActivity> removed = null;
17718        boolean changed = false;
17719        synchronized (mPackages) {
17720            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17721                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17722                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17723                        .valueAt(i);
17724                if (userId != thisUserId) {
17725                    continue;
17726                }
17727                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17728                while (it.hasNext()) {
17729                    PersistentPreferredActivity ppa = it.next();
17730                    // Mark entry for removal only if it matches the package name.
17731                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17732                        if (removed == null) {
17733                            removed = new ArrayList<PersistentPreferredActivity>();
17734                        }
17735                        removed.add(ppa);
17736                    }
17737                }
17738                if (removed != null) {
17739                    for (int j=0; j<removed.size(); j++) {
17740                        PersistentPreferredActivity ppa = removed.get(j);
17741                        ppir.removeFilter(ppa);
17742                    }
17743                    changed = true;
17744                }
17745            }
17746
17747            if (changed) {
17748                scheduleWritePackageRestrictionsLocked(userId);
17749                postPreferredActivityChangedBroadcast(userId);
17750            }
17751        }
17752    }
17753
17754    /**
17755     * Common machinery for picking apart a restored XML blob and passing
17756     * it to a caller-supplied functor to be applied to the running system.
17757     */
17758    private void restoreFromXml(XmlPullParser parser, int userId,
17759            String expectedStartTag, BlobXmlRestorer functor)
17760            throws IOException, XmlPullParserException {
17761        int type;
17762        while ((type = parser.next()) != XmlPullParser.START_TAG
17763                && type != XmlPullParser.END_DOCUMENT) {
17764        }
17765        if (type != XmlPullParser.START_TAG) {
17766            // oops didn't find a start tag?!
17767            if (DEBUG_BACKUP) {
17768                Slog.e(TAG, "Didn't find start tag during restore");
17769            }
17770            return;
17771        }
17772Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17773        // this is supposed to be TAG_PREFERRED_BACKUP
17774        if (!expectedStartTag.equals(parser.getName())) {
17775            if (DEBUG_BACKUP) {
17776                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17777            }
17778            return;
17779        }
17780
17781        // skip interfering stuff, then we're aligned with the backing implementation
17782        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17783Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17784        functor.apply(parser, userId);
17785    }
17786
17787    private interface BlobXmlRestorer {
17788        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17789    }
17790
17791    /**
17792     * Non-Binder method, support for the backup/restore mechanism: write the
17793     * full set of preferred activities in its canonical XML format.  Returns the
17794     * XML output as a byte array, or null if there is none.
17795     */
17796    @Override
17797    public byte[] getPreferredActivityBackup(int userId) {
17798        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17799            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17800        }
17801
17802        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17803        try {
17804            final XmlSerializer serializer = new FastXmlSerializer();
17805            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17806            serializer.startDocument(null, true);
17807            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17808
17809            synchronized (mPackages) {
17810                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17811            }
17812
17813            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17814            serializer.endDocument();
17815            serializer.flush();
17816        } catch (Exception e) {
17817            if (DEBUG_BACKUP) {
17818                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17819            }
17820            return null;
17821        }
17822
17823        return dataStream.toByteArray();
17824    }
17825
17826    @Override
17827    public void restorePreferredActivities(byte[] backup, int userId) {
17828        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17829            throw new SecurityException("Only the system may call restorePreferredActivities()");
17830        }
17831
17832        try {
17833            final XmlPullParser parser = Xml.newPullParser();
17834            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17835            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17836                    new BlobXmlRestorer() {
17837                        @Override
17838                        public void apply(XmlPullParser parser, int userId)
17839                                throws XmlPullParserException, IOException {
17840                            synchronized (mPackages) {
17841                                mSettings.readPreferredActivitiesLPw(parser, userId);
17842                            }
17843                        }
17844                    } );
17845        } catch (Exception e) {
17846            if (DEBUG_BACKUP) {
17847                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17848            }
17849        }
17850    }
17851
17852    /**
17853     * Non-Binder method, support for the backup/restore mechanism: write the
17854     * default browser (etc) settings in its canonical XML format.  Returns the default
17855     * browser XML representation as a byte array, or null if there is none.
17856     */
17857    @Override
17858    public byte[] getDefaultAppsBackup(int userId) {
17859        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17860            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17861        }
17862
17863        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17864        try {
17865            final XmlSerializer serializer = new FastXmlSerializer();
17866            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17867            serializer.startDocument(null, true);
17868            serializer.startTag(null, TAG_DEFAULT_APPS);
17869
17870            synchronized (mPackages) {
17871                mSettings.writeDefaultAppsLPr(serializer, userId);
17872            }
17873
17874            serializer.endTag(null, TAG_DEFAULT_APPS);
17875            serializer.endDocument();
17876            serializer.flush();
17877        } catch (Exception e) {
17878            if (DEBUG_BACKUP) {
17879                Slog.e(TAG, "Unable to write default apps for backup", e);
17880            }
17881            return null;
17882        }
17883
17884        return dataStream.toByteArray();
17885    }
17886
17887    @Override
17888    public void restoreDefaultApps(byte[] backup, int userId) {
17889        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17890            throw new SecurityException("Only the system may call restoreDefaultApps()");
17891        }
17892
17893        try {
17894            final XmlPullParser parser = Xml.newPullParser();
17895            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17896            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17897                    new BlobXmlRestorer() {
17898                        @Override
17899                        public void apply(XmlPullParser parser, int userId)
17900                                throws XmlPullParserException, IOException {
17901                            synchronized (mPackages) {
17902                                mSettings.readDefaultAppsLPw(parser, userId);
17903                            }
17904                        }
17905                    } );
17906        } catch (Exception e) {
17907            if (DEBUG_BACKUP) {
17908                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17909            }
17910        }
17911    }
17912
17913    @Override
17914    public byte[] getIntentFilterVerificationBackup(int userId) {
17915        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17916            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17917        }
17918
17919        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17920        try {
17921            final XmlSerializer serializer = new FastXmlSerializer();
17922            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17923            serializer.startDocument(null, true);
17924            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17925
17926            synchronized (mPackages) {
17927                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17928            }
17929
17930            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17931            serializer.endDocument();
17932            serializer.flush();
17933        } catch (Exception e) {
17934            if (DEBUG_BACKUP) {
17935                Slog.e(TAG, "Unable to write default apps for backup", e);
17936            }
17937            return null;
17938        }
17939
17940        return dataStream.toByteArray();
17941    }
17942
17943    @Override
17944    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17945        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17946            throw new SecurityException("Only the system may call restorePreferredActivities()");
17947        }
17948
17949        try {
17950            final XmlPullParser parser = Xml.newPullParser();
17951            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17952            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17953                    new BlobXmlRestorer() {
17954                        @Override
17955                        public void apply(XmlPullParser parser, int userId)
17956                                throws XmlPullParserException, IOException {
17957                            synchronized (mPackages) {
17958                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17959                                mSettings.writeLPr();
17960                            }
17961                        }
17962                    } );
17963        } catch (Exception e) {
17964            if (DEBUG_BACKUP) {
17965                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17966            }
17967        }
17968    }
17969
17970    @Override
17971    public byte[] getPermissionGrantBackup(int userId) {
17972        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17973            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17974        }
17975
17976        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17977        try {
17978            final XmlSerializer serializer = new FastXmlSerializer();
17979            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17980            serializer.startDocument(null, true);
17981            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17982
17983            synchronized (mPackages) {
17984                serializeRuntimePermissionGrantsLPr(serializer, userId);
17985            }
17986
17987            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17988            serializer.endDocument();
17989            serializer.flush();
17990        } catch (Exception e) {
17991            if (DEBUG_BACKUP) {
17992                Slog.e(TAG, "Unable to write default apps for backup", e);
17993            }
17994            return null;
17995        }
17996
17997        return dataStream.toByteArray();
17998    }
17999
18000    @Override
18001    public void restorePermissionGrants(byte[] backup, int userId) {
18002        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18003            throw new SecurityException("Only the system may call restorePermissionGrants()");
18004        }
18005
18006        try {
18007            final XmlPullParser parser = Xml.newPullParser();
18008            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18009            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18010                    new BlobXmlRestorer() {
18011                        @Override
18012                        public void apply(XmlPullParser parser, int userId)
18013                                throws XmlPullParserException, IOException {
18014                            synchronized (mPackages) {
18015                                processRestoredPermissionGrantsLPr(parser, userId);
18016                            }
18017                        }
18018                    } );
18019        } catch (Exception e) {
18020            if (DEBUG_BACKUP) {
18021                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18022            }
18023        }
18024    }
18025
18026    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18027            throws IOException {
18028        serializer.startTag(null, TAG_ALL_GRANTS);
18029
18030        final int N = mSettings.mPackages.size();
18031        for (int i = 0; i < N; i++) {
18032            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18033            boolean pkgGrantsKnown = false;
18034
18035            PermissionsState packagePerms = ps.getPermissionsState();
18036
18037            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18038                final int grantFlags = state.getFlags();
18039                // only look at grants that are not system/policy fixed
18040                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18041                    final boolean isGranted = state.isGranted();
18042                    // And only back up the user-twiddled state bits
18043                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18044                        final String packageName = mSettings.mPackages.keyAt(i);
18045                        if (!pkgGrantsKnown) {
18046                            serializer.startTag(null, TAG_GRANT);
18047                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18048                            pkgGrantsKnown = true;
18049                        }
18050
18051                        final boolean userSet =
18052                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18053                        final boolean userFixed =
18054                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18055                        final boolean revoke =
18056                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18057
18058                        serializer.startTag(null, TAG_PERMISSION);
18059                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18060                        if (isGranted) {
18061                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18062                        }
18063                        if (userSet) {
18064                            serializer.attribute(null, ATTR_USER_SET, "true");
18065                        }
18066                        if (userFixed) {
18067                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18068                        }
18069                        if (revoke) {
18070                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18071                        }
18072                        serializer.endTag(null, TAG_PERMISSION);
18073                    }
18074                }
18075            }
18076
18077            if (pkgGrantsKnown) {
18078                serializer.endTag(null, TAG_GRANT);
18079            }
18080        }
18081
18082        serializer.endTag(null, TAG_ALL_GRANTS);
18083    }
18084
18085    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18086            throws XmlPullParserException, IOException {
18087        String pkgName = null;
18088        int outerDepth = parser.getDepth();
18089        int type;
18090        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18091                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18092            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18093                continue;
18094            }
18095
18096            final String tagName = parser.getName();
18097            if (tagName.equals(TAG_GRANT)) {
18098                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18099                if (DEBUG_BACKUP) {
18100                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18101                }
18102            } else if (tagName.equals(TAG_PERMISSION)) {
18103
18104                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18105                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18106
18107                int newFlagSet = 0;
18108                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18109                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18110                }
18111                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18112                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18113                }
18114                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18115                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18116                }
18117                if (DEBUG_BACKUP) {
18118                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18119                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18120                }
18121                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18122                if (ps != null) {
18123                    // Already installed so we apply the grant immediately
18124                    if (DEBUG_BACKUP) {
18125                        Slog.v(TAG, "        + already installed; applying");
18126                    }
18127                    PermissionsState perms = ps.getPermissionsState();
18128                    BasePermission bp = mSettings.mPermissions.get(permName);
18129                    if (bp != null) {
18130                        if (isGranted) {
18131                            perms.grantRuntimePermission(bp, userId);
18132                        }
18133                        if (newFlagSet != 0) {
18134                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18135                        }
18136                    }
18137                } else {
18138                    // Need to wait for post-restore install to apply the grant
18139                    if (DEBUG_BACKUP) {
18140                        Slog.v(TAG, "        - not yet installed; saving for later");
18141                    }
18142                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18143                            isGranted, newFlagSet, userId);
18144                }
18145            } else {
18146                PackageManagerService.reportSettingsProblem(Log.WARN,
18147                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18148                XmlUtils.skipCurrentTag(parser);
18149            }
18150        }
18151
18152        scheduleWriteSettingsLocked();
18153        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18154    }
18155
18156    @Override
18157    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18158            int sourceUserId, int targetUserId, int flags) {
18159        mContext.enforceCallingOrSelfPermission(
18160                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18161        int callingUid = Binder.getCallingUid();
18162        enforceOwnerRights(ownerPackage, callingUid);
18163        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18164        if (intentFilter.countActions() == 0) {
18165            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18166            return;
18167        }
18168        synchronized (mPackages) {
18169            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18170                    ownerPackage, targetUserId, flags);
18171            CrossProfileIntentResolver resolver =
18172                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18173            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18174            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18175            if (existing != null) {
18176                int size = existing.size();
18177                for (int i = 0; i < size; i++) {
18178                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18179                        return;
18180                    }
18181                }
18182            }
18183            resolver.addFilter(newFilter);
18184            scheduleWritePackageRestrictionsLocked(sourceUserId);
18185        }
18186    }
18187
18188    @Override
18189    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18190        mContext.enforceCallingOrSelfPermission(
18191                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18192        int callingUid = Binder.getCallingUid();
18193        enforceOwnerRights(ownerPackage, callingUid);
18194        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18195        synchronized (mPackages) {
18196            CrossProfileIntentResolver resolver =
18197                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18198            ArraySet<CrossProfileIntentFilter> set =
18199                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18200            for (CrossProfileIntentFilter filter : set) {
18201                if (filter.getOwnerPackage().equals(ownerPackage)) {
18202                    resolver.removeFilter(filter);
18203                }
18204            }
18205            scheduleWritePackageRestrictionsLocked(sourceUserId);
18206        }
18207    }
18208
18209    // Enforcing that callingUid is owning pkg on userId
18210    private void enforceOwnerRights(String pkg, int callingUid) {
18211        // The system owns everything.
18212        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18213            return;
18214        }
18215        int callingUserId = UserHandle.getUserId(callingUid);
18216        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18217        if (pi == null) {
18218            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18219                    + callingUserId);
18220        }
18221        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18222            throw new SecurityException("Calling uid " + callingUid
18223                    + " does not own package " + pkg);
18224        }
18225    }
18226
18227    @Override
18228    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18229        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18230    }
18231
18232    private Intent getHomeIntent() {
18233        Intent intent = new Intent(Intent.ACTION_MAIN);
18234        intent.addCategory(Intent.CATEGORY_HOME);
18235        intent.addCategory(Intent.CATEGORY_DEFAULT);
18236        return intent;
18237    }
18238
18239    private IntentFilter getHomeFilter() {
18240        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18241        filter.addCategory(Intent.CATEGORY_HOME);
18242        filter.addCategory(Intent.CATEGORY_DEFAULT);
18243        return filter;
18244    }
18245
18246    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18247            int userId) {
18248        Intent intent  = getHomeIntent();
18249        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18250                PackageManager.GET_META_DATA, userId);
18251        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18252                true, false, false, userId);
18253
18254        allHomeCandidates.clear();
18255        if (list != null) {
18256            for (ResolveInfo ri : list) {
18257                allHomeCandidates.add(ri);
18258            }
18259        }
18260        return (preferred == null || preferred.activityInfo == null)
18261                ? null
18262                : new ComponentName(preferred.activityInfo.packageName,
18263                        preferred.activityInfo.name);
18264    }
18265
18266    @Override
18267    public void setHomeActivity(ComponentName comp, int userId) {
18268        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18269        getHomeActivitiesAsUser(homeActivities, userId);
18270
18271        boolean found = false;
18272
18273        final int size = homeActivities.size();
18274        final ComponentName[] set = new ComponentName[size];
18275        for (int i = 0; i < size; i++) {
18276            final ResolveInfo candidate = homeActivities.get(i);
18277            final ActivityInfo info = candidate.activityInfo;
18278            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18279            set[i] = activityName;
18280            if (!found && activityName.equals(comp)) {
18281                found = true;
18282            }
18283        }
18284        if (!found) {
18285            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18286                    + userId);
18287        }
18288        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18289                set, comp, userId);
18290    }
18291
18292    private @Nullable String getSetupWizardPackageName() {
18293        final Intent intent = new Intent(Intent.ACTION_MAIN);
18294        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18295
18296        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18297                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18298                        | MATCH_DISABLED_COMPONENTS,
18299                UserHandle.myUserId());
18300        if (matches.size() == 1) {
18301            return matches.get(0).getComponentInfo().packageName;
18302        } else {
18303            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18304                    + ": matches=" + matches);
18305            return null;
18306        }
18307    }
18308
18309    private @Nullable String getStorageManagerPackageName() {
18310        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18311
18312        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18313                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18314                        | MATCH_DISABLED_COMPONENTS,
18315                UserHandle.myUserId());
18316        if (matches.size() == 1) {
18317            return matches.get(0).getComponentInfo().packageName;
18318        } else {
18319            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18320                    + matches.size() + ": matches=" + matches);
18321            return null;
18322        }
18323    }
18324
18325    @Override
18326    public void setApplicationEnabledSetting(String appPackageName,
18327            int newState, int flags, int userId, String callingPackage) {
18328        if (!sUserManager.exists(userId)) return;
18329        if (callingPackage == null) {
18330            callingPackage = Integer.toString(Binder.getCallingUid());
18331        }
18332        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18333    }
18334
18335    @Override
18336    public void setComponentEnabledSetting(ComponentName componentName,
18337            int newState, int flags, int userId) {
18338        if (!sUserManager.exists(userId)) return;
18339        setEnabledSetting(componentName.getPackageName(),
18340                componentName.getClassName(), newState, flags, userId, null);
18341    }
18342
18343    private void setEnabledSetting(final String packageName, String className, int newState,
18344            final int flags, int userId, String callingPackage) {
18345        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18346              || newState == COMPONENT_ENABLED_STATE_ENABLED
18347              || newState == COMPONENT_ENABLED_STATE_DISABLED
18348              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18349              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18350            throw new IllegalArgumentException("Invalid new component state: "
18351                    + newState);
18352        }
18353        PackageSetting pkgSetting;
18354        final int uid = Binder.getCallingUid();
18355        final int permission;
18356        if (uid == Process.SYSTEM_UID) {
18357            permission = PackageManager.PERMISSION_GRANTED;
18358        } else {
18359            permission = mContext.checkCallingOrSelfPermission(
18360                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18361        }
18362        enforceCrossUserPermission(uid, userId,
18363                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18364        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18365        boolean sendNow = false;
18366        boolean isApp = (className == null);
18367        String componentName = isApp ? packageName : className;
18368        int packageUid = -1;
18369        ArrayList<String> components;
18370
18371        // writer
18372        synchronized (mPackages) {
18373            pkgSetting = mSettings.mPackages.get(packageName);
18374            if (pkgSetting == null) {
18375                if (className == null) {
18376                    throw new IllegalArgumentException("Unknown package: " + packageName);
18377                }
18378                throw new IllegalArgumentException(
18379                        "Unknown component: " + packageName + "/" + className);
18380            }
18381        }
18382
18383        // Limit who can change which apps
18384        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18385            // Don't allow apps that don't have permission to modify other apps
18386            if (!allowedByPermission) {
18387                throw new SecurityException(
18388                        "Permission Denial: attempt to change component state from pid="
18389                        + Binder.getCallingPid()
18390                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18391            }
18392            // Don't allow changing protected packages.
18393            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18394                throw new SecurityException("Cannot disable a protected package: " + packageName);
18395            }
18396        }
18397
18398        synchronized (mPackages) {
18399            if (uid == Process.SHELL_UID
18400                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18401                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18402                // unless it is a test package.
18403                int oldState = pkgSetting.getEnabled(userId);
18404                if (className == null
18405                    &&
18406                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18407                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18408                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18409                    &&
18410                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18411                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18412                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18413                    // ok
18414                } else {
18415                    throw new SecurityException(
18416                            "Shell cannot change component state for " + packageName + "/"
18417                            + className + " to " + newState);
18418                }
18419            }
18420            if (className == null) {
18421                // We're dealing with an application/package level state change
18422                if (pkgSetting.getEnabled(userId) == newState) {
18423                    // Nothing to do
18424                    return;
18425                }
18426                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18427                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18428                    // Don't care about who enables an app.
18429                    callingPackage = null;
18430                }
18431                pkgSetting.setEnabled(newState, userId, callingPackage);
18432                // pkgSetting.pkg.mSetEnabled = newState;
18433            } else {
18434                // We're dealing with a component level state change
18435                // First, verify that this is a valid class name.
18436                PackageParser.Package pkg = pkgSetting.pkg;
18437                if (pkg == null || !pkg.hasComponentClassName(className)) {
18438                    if (pkg != null &&
18439                            pkg.applicationInfo.targetSdkVersion >=
18440                                    Build.VERSION_CODES.JELLY_BEAN) {
18441                        throw new IllegalArgumentException("Component class " + className
18442                                + " does not exist in " + packageName);
18443                    } else {
18444                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18445                                + className + " does not exist in " + packageName);
18446                    }
18447                }
18448                switch (newState) {
18449                case COMPONENT_ENABLED_STATE_ENABLED:
18450                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18451                        return;
18452                    }
18453                    break;
18454                case COMPONENT_ENABLED_STATE_DISABLED:
18455                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18456                        return;
18457                    }
18458                    break;
18459                case COMPONENT_ENABLED_STATE_DEFAULT:
18460                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18461                        return;
18462                    }
18463                    break;
18464                default:
18465                    Slog.e(TAG, "Invalid new component state: " + newState);
18466                    return;
18467                }
18468            }
18469            scheduleWritePackageRestrictionsLocked(userId);
18470            components = mPendingBroadcasts.get(userId, packageName);
18471            final boolean newPackage = components == null;
18472            if (newPackage) {
18473                components = new ArrayList<String>();
18474            }
18475            if (!components.contains(componentName)) {
18476                components.add(componentName);
18477            }
18478            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18479                sendNow = true;
18480                // Purge entry from pending broadcast list if another one exists already
18481                // since we are sending one right away.
18482                mPendingBroadcasts.remove(userId, packageName);
18483            } else {
18484                if (newPackage) {
18485                    mPendingBroadcasts.put(userId, packageName, components);
18486                }
18487                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18488                    // Schedule a message
18489                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18490                }
18491            }
18492        }
18493
18494        long callingId = Binder.clearCallingIdentity();
18495        try {
18496            if (sendNow) {
18497                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18498                sendPackageChangedBroadcast(packageName,
18499                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18500            }
18501        } finally {
18502            Binder.restoreCallingIdentity(callingId);
18503        }
18504    }
18505
18506    @Override
18507    public void flushPackageRestrictionsAsUser(int userId) {
18508        if (!sUserManager.exists(userId)) {
18509            return;
18510        }
18511        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18512                false /* checkShell */, "flushPackageRestrictions");
18513        synchronized (mPackages) {
18514            mSettings.writePackageRestrictionsLPr(userId);
18515            mDirtyUsers.remove(userId);
18516            if (mDirtyUsers.isEmpty()) {
18517                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18518            }
18519        }
18520    }
18521
18522    private void sendPackageChangedBroadcast(String packageName,
18523            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18524        if (DEBUG_INSTALL)
18525            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18526                    + componentNames);
18527        Bundle extras = new Bundle(4);
18528        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18529        String nameList[] = new String[componentNames.size()];
18530        componentNames.toArray(nameList);
18531        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18532        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18533        extras.putInt(Intent.EXTRA_UID, packageUid);
18534        // If this is not reporting a change of the overall package, then only send it
18535        // to registered receivers.  We don't want to launch a swath of apps for every
18536        // little component state change.
18537        final int flags = !componentNames.contains(packageName)
18538                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18539        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18540                new int[] {UserHandle.getUserId(packageUid)});
18541    }
18542
18543    @Override
18544    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18545        if (!sUserManager.exists(userId)) return;
18546        final int uid = Binder.getCallingUid();
18547        final int permission = mContext.checkCallingOrSelfPermission(
18548                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18549        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18550        enforceCrossUserPermission(uid, userId,
18551                true /* requireFullPermission */, true /* checkShell */, "stop package");
18552        // writer
18553        synchronized (mPackages) {
18554            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18555                    allowedByPermission, uid, userId)) {
18556                scheduleWritePackageRestrictionsLocked(userId);
18557            }
18558        }
18559    }
18560
18561    @Override
18562    public String getInstallerPackageName(String packageName) {
18563        // reader
18564        synchronized (mPackages) {
18565            return mSettings.getInstallerPackageNameLPr(packageName);
18566        }
18567    }
18568
18569    public boolean isOrphaned(String packageName) {
18570        // reader
18571        synchronized (mPackages) {
18572            return mSettings.isOrphaned(packageName);
18573        }
18574    }
18575
18576    @Override
18577    public int getApplicationEnabledSetting(String packageName, int userId) {
18578        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18579        int uid = Binder.getCallingUid();
18580        enforceCrossUserPermission(uid, userId,
18581                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18582        // reader
18583        synchronized (mPackages) {
18584            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18585        }
18586    }
18587
18588    @Override
18589    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18590        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18591        int uid = Binder.getCallingUid();
18592        enforceCrossUserPermission(uid, userId,
18593                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18594        // reader
18595        synchronized (mPackages) {
18596            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18597        }
18598    }
18599
18600    @Override
18601    public void enterSafeMode() {
18602        enforceSystemOrRoot("Only the system can request entering safe mode");
18603
18604        if (!mSystemReady) {
18605            mSafeMode = true;
18606        }
18607    }
18608
18609    @Override
18610    public void systemReady() {
18611        mSystemReady = true;
18612
18613        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18614        // disabled after already being started.
18615        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18616                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18617
18618        // Read the compatibilty setting when the system is ready.
18619        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18620                mContext.getContentResolver(),
18621                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18622        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18623        if (DEBUG_SETTINGS) {
18624            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18625        }
18626
18627        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18628
18629        synchronized (mPackages) {
18630            // Verify that all of the preferred activity components actually
18631            // exist.  It is possible for applications to be updated and at
18632            // that point remove a previously declared activity component that
18633            // had been set as a preferred activity.  We try to clean this up
18634            // the next time we encounter that preferred activity, but it is
18635            // possible for the user flow to never be able to return to that
18636            // situation so here we do a sanity check to make sure we haven't
18637            // left any junk around.
18638            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18639            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18640                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18641                removed.clear();
18642                for (PreferredActivity pa : pir.filterSet()) {
18643                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18644                        removed.add(pa);
18645                    }
18646                }
18647                if (removed.size() > 0) {
18648                    for (int r=0; r<removed.size(); r++) {
18649                        PreferredActivity pa = removed.get(r);
18650                        Slog.w(TAG, "Removing dangling preferred activity: "
18651                                + pa.mPref.mComponent);
18652                        pir.removeFilter(pa);
18653                    }
18654                    mSettings.writePackageRestrictionsLPr(
18655                            mSettings.mPreferredActivities.keyAt(i));
18656                }
18657            }
18658
18659            for (int userId : UserManagerService.getInstance().getUserIds()) {
18660                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18661                    grantPermissionsUserIds = ArrayUtils.appendInt(
18662                            grantPermissionsUserIds, userId);
18663                }
18664            }
18665        }
18666        sUserManager.systemReady();
18667
18668        // If we upgraded grant all default permissions before kicking off.
18669        for (int userId : grantPermissionsUserIds) {
18670            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18671        }
18672
18673        // If we did not grant default permissions, we preload from this the
18674        // default permission exceptions lazily to ensure we don't hit the
18675        // disk on a new user creation.
18676        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18677            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18678        }
18679
18680        // Kick off any messages waiting for system ready
18681        if (mPostSystemReadyMessages != null) {
18682            for (Message msg : mPostSystemReadyMessages) {
18683                msg.sendToTarget();
18684            }
18685            mPostSystemReadyMessages = null;
18686        }
18687
18688        // Watch for external volumes that come and go over time
18689        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18690        storage.registerListener(mStorageListener);
18691
18692        mInstallerService.systemReady();
18693        mPackageDexOptimizer.systemReady();
18694
18695        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18696                StorageManagerInternal.class);
18697        StorageManagerInternal.addExternalStoragePolicy(
18698                new StorageManagerInternal.ExternalStorageMountPolicy() {
18699            @Override
18700            public int getMountMode(int uid, String packageName) {
18701                if (Process.isIsolated(uid)) {
18702                    return Zygote.MOUNT_EXTERNAL_NONE;
18703                }
18704                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18705                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18706                }
18707                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18708                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18709                }
18710                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18711                    return Zygote.MOUNT_EXTERNAL_READ;
18712                }
18713                return Zygote.MOUNT_EXTERNAL_WRITE;
18714            }
18715
18716            @Override
18717            public boolean hasExternalStorage(int uid, String packageName) {
18718                return true;
18719            }
18720        });
18721
18722        // Now that we're mostly running, clean up stale users and apps
18723        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18724        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18725    }
18726
18727    @Override
18728    public boolean isSafeMode() {
18729        return mSafeMode;
18730    }
18731
18732    @Override
18733    public boolean hasSystemUidErrors() {
18734        return mHasSystemUidErrors;
18735    }
18736
18737    static String arrayToString(int[] array) {
18738        StringBuffer buf = new StringBuffer(128);
18739        buf.append('[');
18740        if (array != null) {
18741            for (int i=0; i<array.length; i++) {
18742                if (i > 0) buf.append(", ");
18743                buf.append(array[i]);
18744            }
18745        }
18746        buf.append(']');
18747        return buf.toString();
18748    }
18749
18750    static class DumpState {
18751        public static final int DUMP_LIBS = 1 << 0;
18752        public static final int DUMP_FEATURES = 1 << 1;
18753        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18754        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18755        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18756        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18757        public static final int DUMP_PERMISSIONS = 1 << 6;
18758        public static final int DUMP_PACKAGES = 1 << 7;
18759        public static final int DUMP_SHARED_USERS = 1 << 8;
18760        public static final int DUMP_MESSAGES = 1 << 9;
18761        public static final int DUMP_PROVIDERS = 1 << 10;
18762        public static final int DUMP_VERIFIERS = 1 << 11;
18763        public static final int DUMP_PREFERRED = 1 << 12;
18764        public static final int DUMP_PREFERRED_XML = 1 << 13;
18765        public static final int DUMP_KEYSETS = 1 << 14;
18766        public static final int DUMP_VERSION = 1 << 15;
18767        public static final int DUMP_INSTALLS = 1 << 16;
18768        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18769        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18770        public static final int DUMP_FROZEN = 1 << 19;
18771        public static final int DUMP_DEXOPT = 1 << 20;
18772        public static final int DUMP_COMPILER_STATS = 1 << 21;
18773
18774        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18775
18776        private int mTypes;
18777
18778        private int mOptions;
18779
18780        private boolean mTitlePrinted;
18781
18782        private SharedUserSetting mSharedUser;
18783
18784        public boolean isDumping(int type) {
18785            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18786                return true;
18787            }
18788
18789            return (mTypes & type) != 0;
18790        }
18791
18792        public void setDump(int type) {
18793            mTypes |= type;
18794        }
18795
18796        public boolean isOptionEnabled(int option) {
18797            return (mOptions & option) != 0;
18798        }
18799
18800        public void setOptionEnabled(int option) {
18801            mOptions |= option;
18802        }
18803
18804        public boolean onTitlePrinted() {
18805            final boolean printed = mTitlePrinted;
18806            mTitlePrinted = true;
18807            return printed;
18808        }
18809
18810        public boolean getTitlePrinted() {
18811            return mTitlePrinted;
18812        }
18813
18814        public void setTitlePrinted(boolean enabled) {
18815            mTitlePrinted = enabled;
18816        }
18817
18818        public SharedUserSetting getSharedUser() {
18819            return mSharedUser;
18820        }
18821
18822        public void setSharedUser(SharedUserSetting user) {
18823            mSharedUser = user;
18824        }
18825    }
18826
18827    @Override
18828    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18829            FileDescriptor err, String[] args, ShellCallback callback,
18830            ResultReceiver resultReceiver) {
18831        (new PackageManagerShellCommand(this)).exec(
18832                this, in, out, err, args, callback, resultReceiver);
18833    }
18834
18835    @Override
18836    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18837        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18838                != PackageManager.PERMISSION_GRANTED) {
18839            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18840                    + Binder.getCallingPid()
18841                    + ", uid=" + Binder.getCallingUid()
18842                    + " without permission "
18843                    + android.Manifest.permission.DUMP);
18844            return;
18845        }
18846
18847        DumpState dumpState = new DumpState();
18848        boolean fullPreferred = false;
18849        boolean checkin = false;
18850
18851        String packageName = null;
18852        ArraySet<String> permissionNames = null;
18853
18854        int opti = 0;
18855        while (opti < args.length) {
18856            String opt = args[opti];
18857            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18858                break;
18859            }
18860            opti++;
18861
18862            if ("-a".equals(opt)) {
18863                // Right now we only know how to print all.
18864            } else if ("-h".equals(opt)) {
18865                pw.println("Package manager dump options:");
18866                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18867                pw.println("    --checkin: dump for a checkin");
18868                pw.println("    -f: print details of intent filters");
18869                pw.println("    -h: print this help");
18870                pw.println("  cmd may be one of:");
18871                pw.println("    l[ibraries]: list known shared libraries");
18872                pw.println("    f[eatures]: list device features");
18873                pw.println("    k[eysets]: print known keysets");
18874                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18875                pw.println("    perm[issions]: dump permissions");
18876                pw.println("    permission [name ...]: dump declaration and use of given permission");
18877                pw.println("    pref[erred]: print preferred package settings");
18878                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18879                pw.println("    prov[iders]: dump content providers");
18880                pw.println("    p[ackages]: dump installed packages");
18881                pw.println("    s[hared-users]: dump shared user IDs");
18882                pw.println("    m[essages]: print collected runtime messages");
18883                pw.println("    v[erifiers]: print package verifier info");
18884                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18885                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18886                pw.println("    version: print database version info");
18887                pw.println("    write: write current settings now");
18888                pw.println("    installs: details about install sessions");
18889                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18890                pw.println("    dexopt: dump dexopt state");
18891                pw.println("    compiler-stats: dump compiler statistics");
18892                pw.println("    <package.name>: info about given package");
18893                return;
18894            } else if ("--checkin".equals(opt)) {
18895                checkin = true;
18896            } else if ("-f".equals(opt)) {
18897                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18898            } else {
18899                pw.println("Unknown argument: " + opt + "; use -h for help");
18900            }
18901        }
18902
18903        // Is the caller requesting to dump a particular piece of data?
18904        if (opti < args.length) {
18905            String cmd = args[opti];
18906            opti++;
18907            // Is this a package name?
18908            if ("android".equals(cmd) || cmd.contains(".")) {
18909                packageName = cmd;
18910                // When dumping a single package, we always dump all of its
18911                // filter information since the amount of data will be reasonable.
18912                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18913            } else if ("check-permission".equals(cmd)) {
18914                if (opti >= args.length) {
18915                    pw.println("Error: check-permission missing permission argument");
18916                    return;
18917                }
18918                String perm = args[opti];
18919                opti++;
18920                if (opti >= args.length) {
18921                    pw.println("Error: check-permission missing package argument");
18922                    return;
18923                }
18924                String pkg = args[opti];
18925                opti++;
18926                int user = UserHandle.getUserId(Binder.getCallingUid());
18927                if (opti < args.length) {
18928                    try {
18929                        user = Integer.parseInt(args[opti]);
18930                    } catch (NumberFormatException e) {
18931                        pw.println("Error: check-permission user argument is not a number: "
18932                                + args[opti]);
18933                        return;
18934                    }
18935                }
18936                pw.println(checkPermission(perm, pkg, user));
18937                return;
18938            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18939                dumpState.setDump(DumpState.DUMP_LIBS);
18940            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18941                dumpState.setDump(DumpState.DUMP_FEATURES);
18942            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18943                if (opti >= args.length) {
18944                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18945                            | DumpState.DUMP_SERVICE_RESOLVERS
18946                            | DumpState.DUMP_RECEIVER_RESOLVERS
18947                            | DumpState.DUMP_CONTENT_RESOLVERS);
18948                } else {
18949                    while (opti < args.length) {
18950                        String name = args[opti];
18951                        if ("a".equals(name) || "activity".equals(name)) {
18952                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18953                        } else if ("s".equals(name) || "service".equals(name)) {
18954                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18955                        } else if ("r".equals(name) || "receiver".equals(name)) {
18956                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18957                        } else if ("c".equals(name) || "content".equals(name)) {
18958                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18959                        } else {
18960                            pw.println("Error: unknown resolver table type: " + name);
18961                            return;
18962                        }
18963                        opti++;
18964                    }
18965                }
18966            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18967                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18968            } else if ("permission".equals(cmd)) {
18969                if (opti >= args.length) {
18970                    pw.println("Error: permission requires permission name");
18971                    return;
18972                }
18973                permissionNames = new ArraySet<>();
18974                while (opti < args.length) {
18975                    permissionNames.add(args[opti]);
18976                    opti++;
18977                }
18978                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18979                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18980            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18981                dumpState.setDump(DumpState.DUMP_PREFERRED);
18982            } else if ("preferred-xml".equals(cmd)) {
18983                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18984                if (opti < args.length && "--full".equals(args[opti])) {
18985                    fullPreferred = true;
18986                    opti++;
18987                }
18988            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18989                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18990            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18991                dumpState.setDump(DumpState.DUMP_PACKAGES);
18992            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18993                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18994            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18995                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18996            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18997                dumpState.setDump(DumpState.DUMP_MESSAGES);
18998            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18999                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19000            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19001                    || "intent-filter-verifiers".equals(cmd)) {
19002                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19003            } else if ("version".equals(cmd)) {
19004                dumpState.setDump(DumpState.DUMP_VERSION);
19005            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19006                dumpState.setDump(DumpState.DUMP_KEYSETS);
19007            } else if ("installs".equals(cmd)) {
19008                dumpState.setDump(DumpState.DUMP_INSTALLS);
19009            } else if ("frozen".equals(cmd)) {
19010                dumpState.setDump(DumpState.DUMP_FROZEN);
19011            } else if ("dexopt".equals(cmd)) {
19012                dumpState.setDump(DumpState.DUMP_DEXOPT);
19013            } else if ("compiler-stats".equals(cmd)) {
19014                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19015            } else if ("write".equals(cmd)) {
19016                synchronized (mPackages) {
19017                    mSettings.writeLPr();
19018                    pw.println("Settings written.");
19019                    return;
19020                }
19021            }
19022        }
19023
19024        if (checkin) {
19025            pw.println("vers,1");
19026        }
19027
19028        // reader
19029        synchronized (mPackages) {
19030            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19031                if (!checkin) {
19032                    if (dumpState.onTitlePrinted())
19033                        pw.println();
19034                    pw.println("Database versions:");
19035                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19036                }
19037            }
19038
19039            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19040                if (!checkin) {
19041                    if (dumpState.onTitlePrinted())
19042                        pw.println();
19043                    pw.println("Verifiers:");
19044                    pw.print("  Required: ");
19045                    pw.print(mRequiredVerifierPackage);
19046                    pw.print(" (uid=");
19047                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19048                            UserHandle.USER_SYSTEM));
19049                    pw.println(")");
19050                } else if (mRequiredVerifierPackage != null) {
19051                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19052                    pw.print(",");
19053                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19054                            UserHandle.USER_SYSTEM));
19055                }
19056            }
19057
19058            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19059                    packageName == null) {
19060                if (mIntentFilterVerifierComponent != null) {
19061                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19062                    if (!checkin) {
19063                        if (dumpState.onTitlePrinted())
19064                            pw.println();
19065                        pw.println("Intent Filter Verifier:");
19066                        pw.print("  Using: ");
19067                        pw.print(verifierPackageName);
19068                        pw.print(" (uid=");
19069                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19070                                UserHandle.USER_SYSTEM));
19071                        pw.println(")");
19072                    } else if (verifierPackageName != null) {
19073                        pw.print("ifv,"); pw.print(verifierPackageName);
19074                        pw.print(",");
19075                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19076                                UserHandle.USER_SYSTEM));
19077                    }
19078                } else {
19079                    pw.println();
19080                    pw.println("No Intent Filter Verifier available!");
19081                }
19082            }
19083
19084            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19085                boolean printedHeader = false;
19086                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19087                while (it.hasNext()) {
19088                    String name = it.next();
19089                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19090                    if (!checkin) {
19091                        if (!printedHeader) {
19092                            if (dumpState.onTitlePrinted())
19093                                pw.println();
19094                            pw.println("Libraries:");
19095                            printedHeader = true;
19096                        }
19097                        pw.print("  ");
19098                    } else {
19099                        pw.print("lib,");
19100                    }
19101                    pw.print(name);
19102                    if (!checkin) {
19103                        pw.print(" -> ");
19104                    }
19105                    if (ent.path != null) {
19106                        if (!checkin) {
19107                            pw.print("(jar) ");
19108                            pw.print(ent.path);
19109                        } else {
19110                            pw.print(",jar,");
19111                            pw.print(ent.path);
19112                        }
19113                    } else {
19114                        if (!checkin) {
19115                            pw.print("(apk) ");
19116                            pw.print(ent.apk);
19117                        } else {
19118                            pw.print(",apk,");
19119                            pw.print(ent.apk);
19120                        }
19121                    }
19122                    pw.println();
19123                }
19124            }
19125
19126            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19127                if (dumpState.onTitlePrinted())
19128                    pw.println();
19129                if (!checkin) {
19130                    pw.println("Features:");
19131                }
19132
19133                for (FeatureInfo feat : mAvailableFeatures.values()) {
19134                    if (checkin) {
19135                        pw.print("feat,");
19136                        pw.print(feat.name);
19137                        pw.print(",");
19138                        pw.println(feat.version);
19139                    } else {
19140                        pw.print("  ");
19141                        pw.print(feat.name);
19142                        if (feat.version > 0) {
19143                            pw.print(" version=");
19144                            pw.print(feat.version);
19145                        }
19146                        pw.println();
19147                    }
19148                }
19149            }
19150
19151            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19152                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19153                        : "Activity Resolver Table:", "  ", packageName,
19154                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19155                    dumpState.setTitlePrinted(true);
19156                }
19157            }
19158            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19159                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19160                        : "Receiver Resolver Table:", "  ", packageName,
19161                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19162                    dumpState.setTitlePrinted(true);
19163                }
19164            }
19165            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19166                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19167                        : "Service Resolver Table:", "  ", packageName,
19168                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19169                    dumpState.setTitlePrinted(true);
19170                }
19171            }
19172            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19173                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19174                        : "Provider Resolver Table:", "  ", packageName,
19175                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19176                    dumpState.setTitlePrinted(true);
19177                }
19178            }
19179
19180            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19181                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19182                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19183                    int user = mSettings.mPreferredActivities.keyAt(i);
19184                    if (pir.dump(pw,
19185                            dumpState.getTitlePrinted()
19186                                ? "\nPreferred Activities User " + user + ":"
19187                                : "Preferred Activities User " + user + ":", "  ",
19188                            packageName, true, false)) {
19189                        dumpState.setTitlePrinted(true);
19190                    }
19191                }
19192            }
19193
19194            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19195                pw.flush();
19196                FileOutputStream fout = new FileOutputStream(fd);
19197                BufferedOutputStream str = new BufferedOutputStream(fout);
19198                XmlSerializer serializer = new FastXmlSerializer();
19199                try {
19200                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19201                    serializer.startDocument(null, true);
19202                    serializer.setFeature(
19203                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19204                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19205                    serializer.endDocument();
19206                    serializer.flush();
19207                } catch (IllegalArgumentException e) {
19208                    pw.println("Failed writing: " + e);
19209                } catch (IllegalStateException e) {
19210                    pw.println("Failed writing: " + e);
19211                } catch (IOException e) {
19212                    pw.println("Failed writing: " + e);
19213                }
19214            }
19215
19216            if (!checkin
19217                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19218                    && packageName == null) {
19219                pw.println();
19220                int count = mSettings.mPackages.size();
19221                if (count == 0) {
19222                    pw.println("No applications!");
19223                    pw.println();
19224                } else {
19225                    final String prefix = "  ";
19226                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19227                    if (allPackageSettings.size() == 0) {
19228                        pw.println("No domain preferred apps!");
19229                        pw.println();
19230                    } else {
19231                        pw.println("App verification status:");
19232                        pw.println();
19233                        count = 0;
19234                        for (PackageSetting ps : allPackageSettings) {
19235                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19236                            if (ivi == null || ivi.getPackageName() == null) continue;
19237                            pw.println(prefix + "Package: " + ivi.getPackageName());
19238                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19239                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19240                            pw.println();
19241                            count++;
19242                        }
19243                        if (count == 0) {
19244                            pw.println(prefix + "No app verification established.");
19245                            pw.println();
19246                        }
19247                        for (int userId : sUserManager.getUserIds()) {
19248                            pw.println("App linkages for user " + userId + ":");
19249                            pw.println();
19250                            count = 0;
19251                            for (PackageSetting ps : allPackageSettings) {
19252                                final long status = ps.getDomainVerificationStatusForUser(userId);
19253                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19254                                    continue;
19255                                }
19256                                pw.println(prefix + "Package: " + ps.name);
19257                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19258                                String statusStr = IntentFilterVerificationInfo.
19259                                        getStatusStringFromValue(status);
19260                                pw.println(prefix + "Status:  " + statusStr);
19261                                pw.println();
19262                                count++;
19263                            }
19264                            if (count == 0) {
19265                                pw.println(prefix + "No configured app linkages.");
19266                                pw.println();
19267                            }
19268                        }
19269                    }
19270                }
19271            }
19272
19273            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19274                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19275                if (packageName == null && permissionNames == null) {
19276                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19277                        if (iperm == 0) {
19278                            if (dumpState.onTitlePrinted())
19279                                pw.println();
19280                            pw.println("AppOp Permissions:");
19281                        }
19282                        pw.print("  AppOp Permission ");
19283                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19284                        pw.println(":");
19285                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19286                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19287                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19288                        }
19289                    }
19290                }
19291            }
19292
19293            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19294                boolean printedSomething = false;
19295                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19296                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19297                        continue;
19298                    }
19299                    if (!printedSomething) {
19300                        if (dumpState.onTitlePrinted())
19301                            pw.println();
19302                        pw.println("Registered ContentProviders:");
19303                        printedSomething = true;
19304                    }
19305                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19306                    pw.print("    "); pw.println(p.toString());
19307                }
19308                printedSomething = false;
19309                for (Map.Entry<String, PackageParser.Provider> entry :
19310                        mProvidersByAuthority.entrySet()) {
19311                    PackageParser.Provider p = entry.getValue();
19312                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19313                        continue;
19314                    }
19315                    if (!printedSomething) {
19316                        if (dumpState.onTitlePrinted())
19317                            pw.println();
19318                        pw.println("ContentProvider Authorities:");
19319                        printedSomething = true;
19320                    }
19321                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19322                    pw.print("    "); pw.println(p.toString());
19323                    if (p.info != null && p.info.applicationInfo != null) {
19324                        final String appInfo = p.info.applicationInfo.toString();
19325                        pw.print("      applicationInfo="); pw.println(appInfo);
19326                    }
19327                }
19328            }
19329
19330            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19331                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19332            }
19333
19334            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19335                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19336            }
19337
19338            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19339                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19340            }
19341
19342            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19343                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19344            }
19345
19346            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19347                // XXX should handle packageName != null by dumping only install data that
19348                // the given package is involved with.
19349                if (dumpState.onTitlePrinted()) pw.println();
19350                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19351            }
19352
19353            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19354                // XXX should handle packageName != null by dumping only install data that
19355                // the given package is involved with.
19356                if (dumpState.onTitlePrinted()) pw.println();
19357
19358                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19359                ipw.println();
19360                ipw.println("Frozen packages:");
19361                ipw.increaseIndent();
19362                if (mFrozenPackages.size() == 0) {
19363                    ipw.println("(none)");
19364                } else {
19365                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19366                        ipw.println(mFrozenPackages.valueAt(i));
19367                    }
19368                }
19369                ipw.decreaseIndent();
19370            }
19371
19372            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19373                if (dumpState.onTitlePrinted()) pw.println();
19374                dumpDexoptStateLPr(pw, packageName);
19375            }
19376
19377            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19378                if (dumpState.onTitlePrinted()) pw.println();
19379                dumpCompilerStatsLPr(pw, packageName);
19380            }
19381
19382            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19383                if (dumpState.onTitlePrinted()) pw.println();
19384                mSettings.dumpReadMessagesLPr(pw, dumpState);
19385
19386                pw.println();
19387                pw.println("Package warning messages:");
19388                BufferedReader in = null;
19389                String line = null;
19390                try {
19391                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19392                    while ((line = in.readLine()) != null) {
19393                        if (line.contains("ignored: updated version")) continue;
19394                        pw.println(line);
19395                    }
19396                } catch (IOException ignored) {
19397                } finally {
19398                    IoUtils.closeQuietly(in);
19399                }
19400            }
19401
19402            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19403                BufferedReader in = null;
19404                String line = null;
19405                try {
19406                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19407                    while ((line = in.readLine()) != null) {
19408                        if (line.contains("ignored: updated version")) continue;
19409                        pw.print("msg,");
19410                        pw.println(line);
19411                    }
19412                } catch (IOException ignored) {
19413                } finally {
19414                    IoUtils.closeQuietly(in);
19415                }
19416            }
19417        }
19418    }
19419
19420    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19421        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19422        ipw.println();
19423        ipw.println("Dexopt state:");
19424        ipw.increaseIndent();
19425        Collection<PackageParser.Package> packages = null;
19426        if (packageName != null) {
19427            PackageParser.Package targetPackage = mPackages.get(packageName);
19428            if (targetPackage != null) {
19429                packages = Collections.singletonList(targetPackage);
19430            } else {
19431                ipw.println("Unable to find package: " + packageName);
19432                return;
19433            }
19434        } else {
19435            packages = mPackages.values();
19436        }
19437
19438        for (PackageParser.Package pkg : packages) {
19439            ipw.println("[" + pkg.packageName + "]");
19440            ipw.increaseIndent();
19441            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19442            ipw.decreaseIndent();
19443        }
19444    }
19445
19446    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19447        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19448        ipw.println();
19449        ipw.println("Compiler stats:");
19450        ipw.increaseIndent();
19451        Collection<PackageParser.Package> packages = null;
19452        if (packageName != null) {
19453            PackageParser.Package targetPackage = mPackages.get(packageName);
19454            if (targetPackage != null) {
19455                packages = Collections.singletonList(targetPackage);
19456            } else {
19457                ipw.println("Unable to find package: " + packageName);
19458                return;
19459            }
19460        } else {
19461            packages = mPackages.values();
19462        }
19463
19464        for (PackageParser.Package pkg : packages) {
19465            ipw.println("[" + pkg.packageName + "]");
19466            ipw.increaseIndent();
19467
19468            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19469            if (stats == null) {
19470                ipw.println("(No recorded stats)");
19471            } else {
19472                stats.dump(ipw);
19473            }
19474            ipw.decreaseIndent();
19475        }
19476    }
19477
19478    private String dumpDomainString(String packageName) {
19479        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19480                .getList();
19481        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19482
19483        ArraySet<String> result = new ArraySet<>();
19484        if (iviList.size() > 0) {
19485            for (IntentFilterVerificationInfo ivi : iviList) {
19486                for (String host : ivi.getDomains()) {
19487                    result.add(host);
19488                }
19489            }
19490        }
19491        if (filters != null && filters.size() > 0) {
19492            for (IntentFilter filter : filters) {
19493                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19494                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19495                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19496                    result.addAll(filter.getHostsList());
19497                }
19498            }
19499        }
19500
19501        StringBuilder sb = new StringBuilder(result.size() * 16);
19502        for (String domain : result) {
19503            if (sb.length() > 0) sb.append(" ");
19504            sb.append(domain);
19505        }
19506        return sb.toString();
19507    }
19508
19509    // ------- apps on sdcard specific code -------
19510    static final boolean DEBUG_SD_INSTALL = false;
19511
19512    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19513
19514    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19515
19516    private boolean mMediaMounted = false;
19517
19518    static String getEncryptKey() {
19519        try {
19520            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19521                    SD_ENCRYPTION_KEYSTORE_NAME);
19522            if (sdEncKey == null) {
19523                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19524                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19525                if (sdEncKey == null) {
19526                    Slog.e(TAG, "Failed to create encryption keys");
19527                    return null;
19528                }
19529            }
19530            return sdEncKey;
19531        } catch (NoSuchAlgorithmException nsae) {
19532            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19533            return null;
19534        } catch (IOException ioe) {
19535            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19536            return null;
19537        }
19538    }
19539
19540    /*
19541     * Update media status on PackageManager.
19542     */
19543    @Override
19544    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19545        int callingUid = Binder.getCallingUid();
19546        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19547            throw new SecurityException("Media status can only be updated by the system");
19548        }
19549        // reader; this apparently protects mMediaMounted, but should probably
19550        // be a different lock in that case.
19551        synchronized (mPackages) {
19552            Log.i(TAG, "Updating external media status from "
19553                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19554                    + (mediaStatus ? "mounted" : "unmounted"));
19555            if (DEBUG_SD_INSTALL)
19556                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19557                        + ", mMediaMounted=" + mMediaMounted);
19558            if (mediaStatus == mMediaMounted) {
19559                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19560                        : 0, -1);
19561                mHandler.sendMessage(msg);
19562                return;
19563            }
19564            mMediaMounted = mediaStatus;
19565        }
19566        // Queue up an async operation since the package installation may take a
19567        // little while.
19568        mHandler.post(new Runnable() {
19569            public void run() {
19570                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19571            }
19572        });
19573    }
19574
19575    /**
19576     * Called by StorageManagerService when the initial ASECs to scan are available.
19577     * Should block until all the ASEC containers are finished being scanned.
19578     */
19579    public void scanAvailableAsecs() {
19580        updateExternalMediaStatusInner(true, false, false);
19581    }
19582
19583    /*
19584     * Collect information of applications on external media, map them against
19585     * existing containers and update information based on current mount status.
19586     * Please note that we always have to report status if reportStatus has been
19587     * set to true especially when unloading packages.
19588     */
19589    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19590            boolean externalStorage) {
19591        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19592        int[] uidArr = EmptyArray.INT;
19593
19594        final String[] list = PackageHelper.getSecureContainerList();
19595        if (ArrayUtils.isEmpty(list)) {
19596            Log.i(TAG, "No secure containers found");
19597        } else {
19598            // Process list of secure containers and categorize them
19599            // as active or stale based on their package internal state.
19600
19601            // reader
19602            synchronized (mPackages) {
19603                for (String cid : list) {
19604                    // Leave stages untouched for now; installer service owns them
19605                    if (PackageInstallerService.isStageName(cid)) continue;
19606
19607                    if (DEBUG_SD_INSTALL)
19608                        Log.i(TAG, "Processing container " + cid);
19609                    String pkgName = getAsecPackageName(cid);
19610                    if (pkgName == null) {
19611                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19612                        continue;
19613                    }
19614                    if (DEBUG_SD_INSTALL)
19615                        Log.i(TAG, "Looking for pkg : " + pkgName);
19616
19617                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19618                    if (ps == null) {
19619                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19620                        continue;
19621                    }
19622
19623                    /*
19624                     * Skip packages that are not external if we're unmounting
19625                     * external storage.
19626                     */
19627                    if (externalStorage && !isMounted && !isExternal(ps)) {
19628                        continue;
19629                    }
19630
19631                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19632                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19633                    // The package status is changed only if the code path
19634                    // matches between settings and the container id.
19635                    if (ps.codePathString != null
19636                            && ps.codePathString.startsWith(args.getCodePath())) {
19637                        if (DEBUG_SD_INSTALL) {
19638                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19639                                    + " at code path: " + ps.codePathString);
19640                        }
19641
19642                        // We do have a valid package installed on sdcard
19643                        processCids.put(args, ps.codePathString);
19644                        final int uid = ps.appId;
19645                        if (uid != -1) {
19646                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19647                        }
19648                    } else {
19649                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19650                                + ps.codePathString);
19651                    }
19652                }
19653            }
19654
19655            Arrays.sort(uidArr);
19656        }
19657
19658        // Process packages with valid entries.
19659        if (isMounted) {
19660            if (DEBUG_SD_INSTALL)
19661                Log.i(TAG, "Loading packages");
19662            loadMediaPackages(processCids, uidArr, externalStorage);
19663            startCleaningPackages();
19664            mInstallerService.onSecureContainersAvailable();
19665        } else {
19666            if (DEBUG_SD_INSTALL)
19667                Log.i(TAG, "Unloading packages");
19668            unloadMediaPackages(processCids, uidArr, reportStatus);
19669        }
19670    }
19671
19672    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19673            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19674        final int size = infos.size();
19675        final String[] packageNames = new String[size];
19676        final int[] packageUids = new int[size];
19677        for (int i = 0; i < size; i++) {
19678            final ApplicationInfo info = infos.get(i);
19679            packageNames[i] = info.packageName;
19680            packageUids[i] = info.uid;
19681        }
19682        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19683                finishedReceiver);
19684    }
19685
19686    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19687            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19688        sendResourcesChangedBroadcast(mediaStatus, replacing,
19689                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19690    }
19691
19692    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19693            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19694        int size = pkgList.length;
19695        if (size > 0) {
19696            // Send broadcasts here
19697            Bundle extras = new Bundle();
19698            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19699            if (uidArr != null) {
19700                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19701            }
19702            if (replacing) {
19703                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19704            }
19705            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19706                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19707            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19708        }
19709    }
19710
19711   /*
19712     * Look at potentially valid container ids from processCids If package
19713     * information doesn't match the one on record or package scanning fails,
19714     * the cid is added to list of removeCids. We currently don't delete stale
19715     * containers.
19716     */
19717    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19718            boolean externalStorage) {
19719        ArrayList<String> pkgList = new ArrayList<String>();
19720        Set<AsecInstallArgs> keys = processCids.keySet();
19721
19722        for (AsecInstallArgs args : keys) {
19723            String codePath = processCids.get(args);
19724            if (DEBUG_SD_INSTALL)
19725                Log.i(TAG, "Loading container : " + args.cid);
19726            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19727            try {
19728                // Make sure there are no container errors first.
19729                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19730                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19731                            + " when installing from sdcard");
19732                    continue;
19733                }
19734                // Check code path here.
19735                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19736                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19737                            + " does not match one in settings " + codePath);
19738                    continue;
19739                }
19740                // Parse package
19741                int parseFlags = mDefParseFlags;
19742                if (args.isExternalAsec()) {
19743                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19744                }
19745                if (args.isFwdLocked()) {
19746                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19747                }
19748
19749                synchronized (mInstallLock) {
19750                    PackageParser.Package pkg = null;
19751                    try {
19752                        // Sadly we don't know the package name yet to freeze it
19753                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19754                                SCAN_IGNORE_FROZEN, 0, null);
19755                    } catch (PackageManagerException e) {
19756                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19757                    }
19758                    // Scan the package
19759                    if (pkg != null) {
19760                        /*
19761                         * TODO why is the lock being held? doPostInstall is
19762                         * called in other places without the lock. This needs
19763                         * to be straightened out.
19764                         */
19765                        // writer
19766                        synchronized (mPackages) {
19767                            retCode = PackageManager.INSTALL_SUCCEEDED;
19768                            pkgList.add(pkg.packageName);
19769                            // Post process args
19770                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19771                                    pkg.applicationInfo.uid);
19772                        }
19773                    } else {
19774                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19775                    }
19776                }
19777
19778            } finally {
19779                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19780                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19781                }
19782            }
19783        }
19784        // writer
19785        synchronized (mPackages) {
19786            // If the platform SDK has changed since the last time we booted,
19787            // we need to re-grant app permission to catch any new ones that
19788            // appear. This is really a hack, and means that apps can in some
19789            // cases get permissions that the user didn't initially explicitly
19790            // allow... it would be nice to have some better way to handle
19791            // this situation.
19792            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19793                    : mSettings.getInternalVersion();
19794            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19795                    : StorageManager.UUID_PRIVATE_INTERNAL;
19796
19797            int updateFlags = UPDATE_PERMISSIONS_ALL;
19798            if (ver.sdkVersion != mSdkVersion) {
19799                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19800                        + mSdkVersion + "; regranting permissions for external");
19801                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19802            }
19803            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19804
19805            // Yay, everything is now upgraded
19806            ver.forceCurrent();
19807
19808            // can downgrade to reader
19809            // Persist settings
19810            mSettings.writeLPr();
19811        }
19812        // Send a broadcast to let everyone know we are done processing
19813        if (pkgList.size() > 0) {
19814            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19815        }
19816    }
19817
19818   /*
19819     * Utility method to unload a list of specified containers
19820     */
19821    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19822        // Just unmount all valid containers.
19823        for (AsecInstallArgs arg : cidArgs) {
19824            synchronized (mInstallLock) {
19825                arg.doPostDeleteLI(false);
19826           }
19827       }
19828   }
19829
19830    /*
19831     * Unload packages mounted on external media. This involves deleting package
19832     * data from internal structures, sending broadcasts about disabled packages,
19833     * gc'ing to free up references, unmounting all secure containers
19834     * corresponding to packages on external media, and posting a
19835     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19836     * that we always have to post this message if status has been requested no
19837     * matter what.
19838     */
19839    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19840            final boolean reportStatus) {
19841        if (DEBUG_SD_INSTALL)
19842            Log.i(TAG, "unloading media packages");
19843        ArrayList<String> pkgList = new ArrayList<String>();
19844        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19845        final Set<AsecInstallArgs> keys = processCids.keySet();
19846        for (AsecInstallArgs args : keys) {
19847            String pkgName = args.getPackageName();
19848            if (DEBUG_SD_INSTALL)
19849                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19850            // Delete package internally
19851            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19852            synchronized (mInstallLock) {
19853                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19854                final boolean res;
19855                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19856                        "unloadMediaPackages")) {
19857                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19858                            null);
19859                }
19860                if (res) {
19861                    pkgList.add(pkgName);
19862                } else {
19863                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19864                    failedList.add(args);
19865                }
19866            }
19867        }
19868
19869        // reader
19870        synchronized (mPackages) {
19871            // We didn't update the settings after removing each package;
19872            // write them now for all packages.
19873            mSettings.writeLPr();
19874        }
19875
19876        // We have to absolutely send UPDATED_MEDIA_STATUS only
19877        // after confirming that all the receivers processed the ordered
19878        // broadcast when packages get disabled, force a gc to clean things up.
19879        // and unload all the containers.
19880        if (pkgList.size() > 0) {
19881            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19882                    new IIntentReceiver.Stub() {
19883                public void performReceive(Intent intent, int resultCode, String data,
19884                        Bundle extras, boolean ordered, boolean sticky,
19885                        int sendingUser) throws RemoteException {
19886                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19887                            reportStatus ? 1 : 0, 1, keys);
19888                    mHandler.sendMessage(msg);
19889                }
19890            });
19891        } else {
19892            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19893                    keys);
19894            mHandler.sendMessage(msg);
19895        }
19896    }
19897
19898    private void loadPrivatePackages(final VolumeInfo vol) {
19899        mHandler.post(new Runnable() {
19900            @Override
19901            public void run() {
19902                loadPrivatePackagesInner(vol);
19903            }
19904        });
19905    }
19906
19907    private void loadPrivatePackagesInner(VolumeInfo vol) {
19908        final String volumeUuid = vol.fsUuid;
19909        if (TextUtils.isEmpty(volumeUuid)) {
19910            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19911            return;
19912        }
19913
19914        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19915        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19916        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19917
19918        final VersionInfo ver;
19919        final List<PackageSetting> packages;
19920        synchronized (mPackages) {
19921            ver = mSettings.findOrCreateVersion(volumeUuid);
19922            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19923        }
19924
19925        for (PackageSetting ps : packages) {
19926            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19927            synchronized (mInstallLock) {
19928                final PackageParser.Package pkg;
19929                try {
19930                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19931                    loaded.add(pkg.applicationInfo);
19932
19933                } catch (PackageManagerException e) {
19934                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19935                }
19936
19937                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19938                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19939                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19940                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19941                }
19942            }
19943        }
19944
19945        // Reconcile app data for all started/unlocked users
19946        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19947        final UserManager um = mContext.getSystemService(UserManager.class);
19948        UserManagerInternal umInternal = getUserManagerInternal();
19949        for (UserInfo user : um.getUsers()) {
19950            final int flags;
19951            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19952                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19953            } else if (umInternal.isUserRunning(user.id)) {
19954                flags = StorageManager.FLAG_STORAGE_DE;
19955            } else {
19956                continue;
19957            }
19958
19959            try {
19960                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19961                synchronized (mInstallLock) {
19962                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19963                }
19964            } catch (IllegalStateException e) {
19965                // Device was probably ejected, and we'll process that event momentarily
19966                Slog.w(TAG, "Failed to prepare storage: " + e);
19967            }
19968        }
19969
19970        synchronized (mPackages) {
19971            int updateFlags = UPDATE_PERMISSIONS_ALL;
19972            if (ver.sdkVersion != mSdkVersion) {
19973                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19974                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19975                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19976            }
19977            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19978
19979            // Yay, everything is now upgraded
19980            ver.forceCurrent();
19981
19982            mSettings.writeLPr();
19983        }
19984
19985        for (PackageFreezer freezer : freezers) {
19986            freezer.close();
19987        }
19988
19989        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19990        sendResourcesChangedBroadcast(true, false, loaded, null);
19991    }
19992
19993    private void unloadPrivatePackages(final VolumeInfo vol) {
19994        mHandler.post(new Runnable() {
19995            @Override
19996            public void run() {
19997                unloadPrivatePackagesInner(vol);
19998            }
19999        });
20000    }
20001
20002    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20003        final String volumeUuid = vol.fsUuid;
20004        if (TextUtils.isEmpty(volumeUuid)) {
20005            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20006            return;
20007        }
20008
20009        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20010        synchronized (mInstallLock) {
20011        synchronized (mPackages) {
20012            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20013            for (PackageSetting ps : packages) {
20014                if (ps.pkg == null) continue;
20015
20016                final ApplicationInfo info = ps.pkg.applicationInfo;
20017                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20018                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20019
20020                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20021                        "unloadPrivatePackagesInner")) {
20022                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20023                            false, null)) {
20024                        unloaded.add(info);
20025                    } else {
20026                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20027                    }
20028                }
20029
20030                // Try very hard to release any references to this package
20031                // so we don't risk the system server being killed due to
20032                // open FDs
20033                AttributeCache.instance().removePackage(ps.name);
20034            }
20035
20036            mSettings.writeLPr();
20037        }
20038        }
20039
20040        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20041        sendResourcesChangedBroadcast(false, false, unloaded, null);
20042
20043        // Try very hard to release any references to this path so we don't risk
20044        // the system server being killed due to open FDs
20045        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20046
20047        for (int i = 0; i < 3; i++) {
20048            System.gc();
20049            System.runFinalization();
20050        }
20051    }
20052
20053    /**
20054     * Prepare storage areas for given user on all mounted devices.
20055     */
20056    void prepareUserData(int userId, int userSerial, int flags) {
20057        synchronized (mInstallLock) {
20058            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20059            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20060                final String volumeUuid = vol.getFsUuid();
20061                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20062            }
20063        }
20064    }
20065
20066    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20067            boolean allowRecover) {
20068        // Prepare storage and verify that serial numbers are consistent; if
20069        // there's a mismatch we need to destroy to avoid leaking data
20070        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20071        try {
20072            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20073
20074            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20075                UserManagerService.enforceSerialNumber(
20076                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20077                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20078                    UserManagerService.enforceSerialNumber(
20079                            Environment.getDataSystemDeDirectory(userId), userSerial);
20080                }
20081            }
20082            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20083                UserManagerService.enforceSerialNumber(
20084                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20085                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20086                    UserManagerService.enforceSerialNumber(
20087                            Environment.getDataSystemCeDirectory(userId), userSerial);
20088                }
20089            }
20090
20091            synchronized (mInstallLock) {
20092                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20093            }
20094        } catch (Exception e) {
20095            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20096                    + " because we failed to prepare: " + e);
20097            destroyUserDataLI(volumeUuid, userId,
20098                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20099
20100            if (allowRecover) {
20101                // Try one last time; if we fail again we're really in trouble
20102                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20103            }
20104        }
20105    }
20106
20107    /**
20108     * Destroy storage areas for given user on all mounted devices.
20109     */
20110    void destroyUserData(int userId, int flags) {
20111        synchronized (mInstallLock) {
20112            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20113            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20114                final String volumeUuid = vol.getFsUuid();
20115                destroyUserDataLI(volumeUuid, userId, flags);
20116            }
20117        }
20118    }
20119
20120    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20121        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20122        try {
20123            // Clean up app data, profile data, and media data
20124            mInstaller.destroyUserData(volumeUuid, userId, flags);
20125
20126            // Clean up system data
20127            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20128                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20129                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20130                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20131                }
20132                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20133                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20134                }
20135            }
20136
20137            // Data with special labels is now gone, so finish the job
20138            storage.destroyUserStorage(volumeUuid, userId, flags);
20139
20140        } catch (Exception e) {
20141            logCriticalInfo(Log.WARN,
20142                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20143        }
20144    }
20145
20146    /**
20147     * Examine all users present on given mounted volume, and destroy data
20148     * belonging to users that are no longer valid, or whose user ID has been
20149     * recycled.
20150     */
20151    private void reconcileUsers(String volumeUuid) {
20152        final List<File> files = new ArrayList<>();
20153        Collections.addAll(files, FileUtils
20154                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20155        Collections.addAll(files, FileUtils
20156                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20157        Collections.addAll(files, FileUtils
20158                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20159        Collections.addAll(files, FileUtils
20160                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20161        for (File file : files) {
20162            if (!file.isDirectory()) continue;
20163
20164            final int userId;
20165            final UserInfo info;
20166            try {
20167                userId = Integer.parseInt(file.getName());
20168                info = sUserManager.getUserInfo(userId);
20169            } catch (NumberFormatException e) {
20170                Slog.w(TAG, "Invalid user directory " + file);
20171                continue;
20172            }
20173
20174            boolean destroyUser = false;
20175            if (info == null) {
20176                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20177                        + " because no matching user was found");
20178                destroyUser = true;
20179            } else if (!mOnlyCore) {
20180                try {
20181                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20182                } catch (IOException e) {
20183                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20184                            + " because we failed to enforce serial number: " + e);
20185                    destroyUser = true;
20186                }
20187            }
20188
20189            if (destroyUser) {
20190                synchronized (mInstallLock) {
20191                    destroyUserDataLI(volumeUuid, userId,
20192                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20193                }
20194            }
20195        }
20196    }
20197
20198    private void assertPackageKnown(String volumeUuid, String packageName)
20199            throws PackageManagerException {
20200        synchronized (mPackages) {
20201            // Normalize package name to handle renamed packages
20202            packageName = normalizePackageNameLPr(packageName);
20203
20204            final PackageSetting ps = mSettings.mPackages.get(packageName);
20205            if (ps == null) {
20206                throw new PackageManagerException("Package " + packageName + " is unknown");
20207            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20208                throw new PackageManagerException(
20209                        "Package " + packageName + " found on unknown volume " + volumeUuid
20210                                + "; expected volume " + ps.volumeUuid);
20211            }
20212        }
20213    }
20214
20215    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20216            throws PackageManagerException {
20217        synchronized (mPackages) {
20218            // Normalize package name to handle renamed packages
20219            packageName = normalizePackageNameLPr(packageName);
20220
20221            final PackageSetting ps = mSettings.mPackages.get(packageName);
20222            if (ps == null) {
20223                throw new PackageManagerException("Package " + packageName + " is unknown");
20224            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20225                throw new PackageManagerException(
20226                        "Package " + packageName + " found on unknown volume " + volumeUuid
20227                                + "; expected volume " + ps.volumeUuid);
20228            } else if (!ps.getInstalled(userId)) {
20229                throw new PackageManagerException(
20230                        "Package " + packageName + " not installed for user " + userId);
20231            }
20232        }
20233    }
20234
20235    /**
20236     * Examine all apps present on given mounted volume, and destroy apps that
20237     * aren't expected, either due to uninstallation or reinstallation on
20238     * another volume.
20239     */
20240    private void reconcileApps(String volumeUuid) {
20241        final File[] files = FileUtils
20242                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20243        for (File file : files) {
20244            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20245                    && !PackageInstallerService.isStageName(file.getName());
20246            if (!isPackage) {
20247                // Ignore entries which are not packages
20248                continue;
20249            }
20250
20251            try {
20252                final PackageLite pkg = PackageParser.parsePackageLite(file,
20253                        PackageParser.PARSE_MUST_BE_APK);
20254                assertPackageKnown(volumeUuid, pkg.packageName);
20255
20256            } catch (PackageParserException | PackageManagerException e) {
20257                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20258                synchronized (mInstallLock) {
20259                    removeCodePathLI(file);
20260                }
20261            }
20262        }
20263    }
20264
20265    /**
20266     * Reconcile all app data for the given user.
20267     * <p>
20268     * Verifies that directories exist and that ownership and labeling is
20269     * correct for all installed apps on all mounted volumes.
20270     */
20271    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20272        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20273        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20274            final String volumeUuid = vol.getFsUuid();
20275            synchronized (mInstallLock) {
20276                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20277            }
20278        }
20279    }
20280
20281    /**
20282     * Reconcile all app data on given mounted volume.
20283     * <p>
20284     * Destroys app data that isn't expected, either due to uninstallation or
20285     * reinstallation on another volume.
20286     * <p>
20287     * Verifies that directories exist and that ownership and labeling is
20288     * correct for all installed apps.
20289     */
20290    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20291            boolean migrateAppData) {
20292        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20293                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20294
20295        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20296        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20297
20298        // First look for stale data that doesn't belong, and check if things
20299        // have changed since we did our last restorecon
20300        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20301            if (StorageManager.isFileEncryptedNativeOrEmulated()
20302                    && !StorageManager.isUserKeyUnlocked(userId)) {
20303                throw new RuntimeException(
20304                        "Yikes, someone asked us to reconcile CE storage while " + userId
20305                                + " was still locked; this would have caused massive data loss!");
20306            }
20307
20308            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20309            for (File file : files) {
20310                final String packageName = file.getName();
20311                try {
20312                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20313                } catch (PackageManagerException e) {
20314                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20315                    try {
20316                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20317                                StorageManager.FLAG_STORAGE_CE, 0);
20318                    } catch (InstallerException e2) {
20319                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20320                    }
20321                }
20322            }
20323        }
20324        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20325            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20326            for (File file : files) {
20327                final String packageName = file.getName();
20328                try {
20329                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20330                } catch (PackageManagerException e) {
20331                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20332                    try {
20333                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20334                                StorageManager.FLAG_STORAGE_DE, 0);
20335                    } catch (InstallerException e2) {
20336                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20337                    }
20338                }
20339            }
20340        }
20341
20342        // Ensure that data directories are ready to roll for all packages
20343        // installed for this volume and user
20344        final List<PackageSetting> packages;
20345        synchronized (mPackages) {
20346            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20347        }
20348        int preparedCount = 0;
20349        for (PackageSetting ps : packages) {
20350            final String packageName = ps.name;
20351            if (ps.pkg == null) {
20352                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20353                // TODO: might be due to legacy ASEC apps; we should circle back
20354                // and reconcile again once they're scanned
20355                continue;
20356            }
20357
20358            if (ps.getInstalled(userId)) {
20359                prepareAppDataLIF(ps.pkg, userId, flags);
20360
20361                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20362                    // We may have just shuffled around app data directories, so
20363                    // prepare them one more time
20364                    prepareAppDataLIF(ps.pkg, userId, flags);
20365                }
20366
20367                preparedCount++;
20368            }
20369        }
20370
20371        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20372    }
20373
20374    /**
20375     * Prepare app data for the given app just after it was installed or
20376     * upgraded. This method carefully only touches users that it's installed
20377     * for, and it forces a restorecon to handle any seinfo changes.
20378     * <p>
20379     * Verifies that directories exist and that ownership and labeling is
20380     * correct for all installed apps. If there is an ownership mismatch, it
20381     * will try recovering system apps by wiping data; third-party app data is
20382     * left intact.
20383     * <p>
20384     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20385     */
20386    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20387        final PackageSetting ps;
20388        synchronized (mPackages) {
20389            ps = mSettings.mPackages.get(pkg.packageName);
20390            mSettings.writeKernelMappingLPr(ps);
20391        }
20392
20393        final UserManager um = mContext.getSystemService(UserManager.class);
20394        UserManagerInternal umInternal = getUserManagerInternal();
20395        for (UserInfo user : um.getUsers()) {
20396            final int flags;
20397            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20398                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20399            } else if (umInternal.isUserRunning(user.id)) {
20400                flags = StorageManager.FLAG_STORAGE_DE;
20401            } else {
20402                continue;
20403            }
20404
20405            if (ps.getInstalled(user.id)) {
20406                // TODO: when user data is locked, mark that we're still dirty
20407                prepareAppDataLIF(pkg, user.id, flags);
20408            }
20409        }
20410    }
20411
20412    /**
20413     * Prepare app data for the given app.
20414     * <p>
20415     * Verifies that directories exist and that ownership and labeling is
20416     * correct for all installed apps. If there is an ownership mismatch, this
20417     * will try recovering system apps by wiping data; third-party app data is
20418     * left intact.
20419     */
20420    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20421        if (pkg == null) {
20422            Slog.wtf(TAG, "Package was null!", new Throwable());
20423            return;
20424        }
20425        prepareAppDataLeafLIF(pkg, userId, flags);
20426        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20427        for (int i = 0; i < childCount; i++) {
20428            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20429        }
20430    }
20431
20432    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20433        if (DEBUG_APP_DATA) {
20434            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20435                    + Integer.toHexString(flags));
20436        }
20437
20438        final String volumeUuid = pkg.volumeUuid;
20439        final String packageName = pkg.packageName;
20440        final ApplicationInfo app = pkg.applicationInfo;
20441        final int appId = UserHandle.getAppId(app.uid);
20442
20443        Preconditions.checkNotNull(app.seinfo);
20444
20445        try {
20446            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20447                    appId, app.seinfo, app.targetSdkVersion);
20448        } catch (InstallerException e) {
20449            if (app.isSystemApp()) {
20450                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20451                        + ", but trying to recover: " + e);
20452                destroyAppDataLeafLIF(pkg, userId, flags);
20453                try {
20454                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20455                            appId, app.seinfo, app.targetSdkVersion);
20456                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20457                } catch (InstallerException e2) {
20458                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20459                }
20460            } else {
20461                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20462            }
20463        }
20464
20465        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20466            try {
20467                // CE storage is unlocked right now, so read out the inode and
20468                // remember for use later when it's locked
20469                // TODO: mark this structure as dirty so we persist it!
20470                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20471                        StorageManager.FLAG_STORAGE_CE);
20472                synchronized (mPackages) {
20473                    final PackageSetting ps = mSettings.mPackages.get(packageName);
20474                    if (ps != null) {
20475                        ps.setCeDataInode(ceDataInode, userId);
20476                    }
20477                }
20478            } catch (InstallerException e) {
20479                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20480            }
20481        }
20482
20483        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20484    }
20485
20486    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20487        if (pkg == null) {
20488            Slog.wtf(TAG, "Package was null!", new Throwable());
20489            return;
20490        }
20491        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20492        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20493        for (int i = 0; i < childCount; i++) {
20494            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20495        }
20496    }
20497
20498    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20499        final String volumeUuid = pkg.volumeUuid;
20500        final String packageName = pkg.packageName;
20501        final ApplicationInfo app = pkg.applicationInfo;
20502
20503        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20504            // Create a native library symlink only if we have native libraries
20505            // and if the native libraries are 32 bit libraries. We do not provide
20506            // this symlink for 64 bit libraries.
20507            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20508                final String nativeLibPath = app.nativeLibraryDir;
20509                try {
20510                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20511                            nativeLibPath, userId);
20512                } catch (InstallerException e) {
20513                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20514                }
20515            }
20516        }
20517    }
20518
20519    /**
20520     * For system apps on non-FBE devices, this method migrates any existing
20521     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20522     * requested by the app.
20523     */
20524    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20525        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20526                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20527            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20528                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20529            try {
20530                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20531                        storageTarget);
20532            } catch (InstallerException e) {
20533                logCriticalInfo(Log.WARN,
20534                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20535            }
20536            return true;
20537        } else {
20538            return false;
20539        }
20540    }
20541
20542    public PackageFreezer freezePackage(String packageName, String killReason) {
20543        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20544    }
20545
20546    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20547        return new PackageFreezer(packageName, userId, killReason);
20548    }
20549
20550    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20551            String killReason) {
20552        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20553    }
20554
20555    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20556            String killReason) {
20557        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20558            return new PackageFreezer();
20559        } else {
20560            return freezePackage(packageName, userId, killReason);
20561        }
20562    }
20563
20564    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20565            String killReason) {
20566        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20567    }
20568
20569    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20570            String killReason) {
20571        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20572            return new PackageFreezer();
20573        } else {
20574            return freezePackage(packageName, userId, killReason);
20575        }
20576    }
20577
20578    /**
20579     * Class that freezes and kills the given package upon creation, and
20580     * unfreezes it upon closing. This is typically used when doing surgery on
20581     * app code/data to prevent the app from running while you're working.
20582     */
20583    private class PackageFreezer implements AutoCloseable {
20584        private final String mPackageName;
20585        private final PackageFreezer[] mChildren;
20586
20587        private final boolean mWeFroze;
20588
20589        private final AtomicBoolean mClosed = new AtomicBoolean();
20590        private final CloseGuard mCloseGuard = CloseGuard.get();
20591
20592        /**
20593         * Create and return a stub freezer that doesn't actually do anything,
20594         * typically used when someone requested
20595         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20596         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20597         */
20598        public PackageFreezer() {
20599            mPackageName = null;
20600            mChildren = null;
20601            mWeFroze = false;
20602            mCloseGuard.open("close");
20603        }
20604
20605        public PackageFreezer(String packageName, int userId, String killReason) {
20606            synchronized (mPackages) {
20607                mPackageName = packageName;
20608                mWeFroze = mFrozenPackages.add(mPackageName);
20609
20610                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20611                if (ps != null) {
20612                    killApplication(ps.name, ps.appId, userId, killReason);
20613                }
20614
20615                final PackageParser.Package p = mPackages.get(packageName);
20616                if (p != null && p.childPackages != null) {
20617                    final int N = p.childPackages.size();
20618                    mChildren = new PackageFreezer[N];
20619                    for (int i = 0; i < N; i++) {
20620                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20621                                userId, killReason);
20622                    }
20623                } else {
20624                    mChildren = null;
20625                }
20626            }
20627            mCloseGuard.open("close");
20628        }
20629
20630        @Override
20631        protected void finalize() throws Throwable {
20632            try {
20633                mCloseGuard.warnIfOpen();
20634                close();
20635            } finally {
20636                super.finalize();
20637            }
20638        }
20639
20640        @Override
20641        public void close() {
20642            mCloseGuard.close();
20643            if (mClosed.compareAndSet(false, true)) {
20644                synchronized (mPackages) {
20645                    if (mWeFroze) {
20646                        mFrozenPackages.remove(mPackageName);
20647                    }
20648
20649                    if (mChildren != null) {
20650                        for (PackageFreezer freezer : mChildren) {
20651                            freezer.close();
20652                        }
20653                    }
20654                }
20655            }
20656        }
20657    }
20658
20659    /**
20660     * Verify that given package is currently frozen.
20661     */
20662    private void checkPackageFrozen(String packageName) {
20663        synchronized (mPackages) {
20664            if (!mFrozenPackages.contains(packageName)) {
20665                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20666            }
20667        }
20668    }
20669
20670    @Override
20671    public int movePackage(final String packageName, final String volumeUuid) {
20672        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20673
20674        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20675        final int moveId = mNextMoveId.getAndIncrement();
20676        mHandler.post(new Runnable() {
20677            @Override
20678            public void run() {
20679                try {
20680                    movePackageInternal(packageName, volumeUuid, moveId, user);
20681                } catch (PackageManagerException e) {
20682                    Slog.w(TAG, "Failed to move " + packageName, e);
20683                    mMoveCallbacks.notifyStatusChanged(moveId,
20684                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20685                }
20686            }
20687        });
20688        return moveId;
20689    }
20690
20691    private void movePackageInternal(final String packageName, final String volumeUuid,
20692            final int moveId, UserHandle user) throws PackageManagerException {
20693        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20694        final PackageManager pm = mContext.getPackageManager();
20695
20696        final boolean currentAsec;
20697        final String currentVolumeUuid;
20698        final File codeFile;
20699        final String installerPackageName;
20700        final String packageAbiOverride;
20701        final int appId;
20702        final String seinfo;
20703        final String label;
20704        final int targetSdkVersion;
20705        final PackageFreezer freezer;
20706        final int[] installedUserIds;
20707
20708        // reader
20709        synchronized (mPackages) {
20710            final PackageParser.Package pkg = mPackages.get(packageName);
20711            final PackageSetting ps = mSettings.mPackages.get(packageName);
20712            if (pkg == null || ps == null) {
20713                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20714            }
20715
20716            if (pkg.applicationInfo.isSystemApp()) {
20717                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20718                        "Cannot move system application");
20719            }
20720
20721            if (pkg.applicationInfo.isExternalAsec()) {
20722                currentAsec = true;
20723                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20724            } else if (pkg.applicationInfo.isForwardLocked()) {
20725                currentAsec = true;
20726                currentVolumeUuid = "forward_locked";
20727            } else {
20728                currentAsec = false;
20729                currentVolumeUuid = ps.volumeUuid;
20730
20731                final File probe = new File(pkg.codePath);
20732                final File probeOat = new File(probe, "oat");
20733                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20734                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20735                            "Move only supported for modern cluster style installs");
20736                }
20737            }
20738
20739            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20740                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20741                        "Package already moved to " + volumeUuid);
20742            }
20743            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20744                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20745                        "Device admin cannot be moved");
20746            }
20747
20748            if (mFrozenPackages.contains(packageName)) {
20749                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20750                        "Failed to move already frozen package");
20751            }
20752
20753            codeFile = new File(pkg.codePath);
20754            installerPackageName = ps.installerPackageName;
20755            packageAbiOverride = ps.cpuAbiOverrideString;
20756            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20757            seinfo = pkg.applicationInfo.seinfo;
20758            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20759            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20760            freezer = freezePackage(packageName, "movePackageInternal");
20761            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20762        }
20763
20764        final Bundle extras = new Bundle();
20765        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20766        extras.putString(Intent.EXTRA_TITLE, label);
20767        mMoveCallbacks.notifyCreated(moveId, extras);
20768
20769        int installFlags;
20770        final boolean moveCompleteApp;
20771        final File measurePath;
20772
20773        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20774            installFlags = INSTALL_INTERNAL;
20775            moveCompleteApp = !currentAsec;
20776            measurePath = Environment.getDataAppDirectory(volumeUuid);
20777        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20778            installFlags = INSTALL_EXTERNAL;
20779            moveCompleteApp = false;
20780            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20781        } else {
20782            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20783            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20784                    || !volume.isMountedWritable()) {
20785                freezer.close();
20786                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20787                        "Move location not mounted private volume");
20788            }
20789
20790            Preconditions.checkState(!currentAsec);
20791
20792            installFlags = INSTALL_INTERNAL;
20793            moveCompleteApp = true;
20794            measurePath = Environment.getDataAppDirectory(volumeUuid);
20795        }
20796
20797        final PackageStats stats = new PackageStats(null, -1);
20798        synchronized (mInstaller) {
20799            for (int userId : installedUserIds) {
20800                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20801                    freezer.close();
20802                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20803                            "Failed to measure package size");
20804                }
20805            }
20806        }
20807
20808        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20809                + stats.dataSize);
20810
20811        final long startFreeBytes = measurePath.getFreeSpace();
20812        final long sizeBytes;
20813        if (moveCompleteApp) {
20814            sizeBytes = stats.codeSize + stats.dataSize;
20815        } else {
20816            sizeBytes = stats.codeSize;
20817        }
20818
20819        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20820            freezer.close();
20821            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20822                    "Not enough free space to move");
20823        }
20824
20825        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20826
20827        final CountDownLatch installedLatch = new CountDownLatch(1);
20828        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20829            @Override
20830            public void onUserActionRequired(Intent intent) throws RemoteException {
20831                throw new IllegalStateException();
20832            }
20833
20834            @Override
20835            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20836                    Bundle extras) throws RemoteException {
20837                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20838                        + PackageManager.installStatusToString(returnCode, msg));
20839
20840                installedLatch.countDown();
20841                freezer.close();
20842
20843                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20844                switch (status) {
20845                    case PackageInstaller.STATUS_SUCCESS:
20846                        mMoveCallbacks.notifyStatusChanged(moveId,
20847                                PackageManager.MOVE_SUCCEEDED);
20848                        break;
20849                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20850                        mMoveCallbacks.notifyStatusChanged(moveId,
20851                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20852                        break;
20853                    default:
20854                        mMoveCallbacks.notifyStatusChanged(moveId,
20855                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20856                        break;
20857                }
20858            }
20859        };
20860
20861        final MoveInfo move;
20862        if (moveCompleteApp) {
20863            // Kick off a thread to report progress estimates
20864            new Thread() {
20865                @Override
20866                public void run() {
20867                    while (true) {
20868                        try {
20869                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20870                                break;
20871                            }
20872                        } catch (InterruptedException ignored) {
20873                        }
20874
20875                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20876                        final int progress = 10 + (int) MathUtils.constrain(
20877                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20878                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20879                    }
20880                }
20881            }.start();
20882
20883            final String dataAppName = codeFile.getName();
20884            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20885                    dataAppName, appId, seinfo, targetSdkVersion);
20886        } else {
20887            move = null;
20888        }
20889
20890        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20891
20892        final Message msg = mHandler.obtainMessage(INIT_COPY);
20893        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20894        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20895                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20896                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20897        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20898        msg.obj = params;
20899
20900        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20901                System.identityHashCode(msg.obj));
20902        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20903                System.identityHashCode(msg.obj));
20904
20905        mHandler.sendMessage(msg);
20906    }
20907
20908    @Override
20909    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20910        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20911
20912        final int realMoveId = mNextMoveId.getAndIncrement();
20913        final Bundle extras = new Bundle();
20914        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20915        mMoveCallbacks.notifyCreated(realMoveId, extras);
20916
20917        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20918            @Override
20919            public void onCreated(int moveId, Bundle extras) {
20920                // Ignored
20921            }
20922
20923            @Override
20924            public void onStatusChanged(int moveId, int status, long estMillis) {
20925                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20926            }
20927        };
20928
20929        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20930        storage.setPrimaryStorageUuid(volumeUuid, callback);
20931        return realMoveId;
20932    }
20933
20934    @Override
20935    public int getMoveStatus(int moveId) {
20936        mContext.enforceCallingOrSelfPermission(
20937                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20938        return mMoveCallbacks.mLastStatus.get(moveId);
20939    }
20940
20941    @Override
20942    public void registerMoveCallback(IPackageMoveObserver callback) {
20943        mContext.enforceCallingOrSelfPermission(
20944                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20945        mMoveCallbacks.register(callback);
20946    }
20947
20948    @Override
20949    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20950        mContext.enforceCallingOrSelfPermission(
20951                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20952        mMoveCallbacks.unregister(callback);
20953    }
20954
20955    @Override
20956    public boolean setInstallLocation(int loc) {
20957        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20958                null);
20959        if (getInstallLocation() == loc) {
20960            return true;
20961        }
20962        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20963                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20964            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20965                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20966            return true;
20967        }
20968        return false;
20969   }
20970
20971    @Override
20972    public int getInstallLocation() {
20973        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20974                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20975                PackageHelper.APP_INSTALL_AUTO);
20976    }
20977
20978    /** Called by UserManagerService */
20979    void cleanUpUser(UserManagerService userManager, int userHandle) {
20980        synchronized (mPackages) {
20981            mDirtyUsers.remove(userHandle);
20982            mUserNeedsBadging.delete(userHandle);
20983            mSettings.removeUserLPw(userHandle);
20984            mPendingBroadcasts.remove(userHandle);
20985            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20986            removeUnusedPackagesLPw(userManager, userHandle);
20987        }
20988    }
20989
20990    /**
20991     * We're removing userHandle and would like to remove any downloaded packages
20992     * that are no longer in use by any other user.
20993     * @param userHandle the user being removed
20994     */
20995    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20996        final boolean DEBUG_CLEAN_APKS = false;
20997        int [] users = userManager.getUserIds();
20998        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20999        while (psit.hasNext()) {
21000            PackageSetting ps = psit.next();
21001            if (ps.pkg == null) {
21002                continue;
21003            }
21004            final String packageName = ps.pkg.packageName;
21005            // Skip over if system app
21006            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21007                continue;
21008            }
21009            if (DEBUG_CLEAN_APKS) {
21010                Slog.i(TAG, "Checking package " + packageName);
21011            }
21012            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21013            if (keep) {
21014                if (DEBUG_CLEAN_APKS) {
21015                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21016                }
21017            } else {
21018                for (int i = 0; i < users.length; i++) {
21019                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21020                        keep = true;
21021                        if (DEBUG_CLEAN_APKS) {
21022                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21023                                    + users[i]);
21024                        }
21025                        break;
21026                    }
21027                }
21028            }
21029            if (!keep) {
21030                if (DEBUG_CLEAN_APKS) {
21031                    Slog.i(TAG, "  Removing package " + packageName);
21032                }
21033                mHandler.post(new Runnable() {
21034                    public void run() {
21035                        deletePackageX(packageName, userHandle, 0);
21036                    } //end run
21037                });
21038            }
21039        }
21040    }
21041
21042    /** Called by UserManagerService */
21043    void createNewUser(int userId, String[] disallowedPackages) {
21044        synchronized (mInstallLock) {
21045            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21046        }
21047        synchronized (mPackages) {
21048            scheduleWritePackageRestrictionsLocked(userId);
21049            scheduleWritePackageListLocked(userId);
21050            applyFactoryDefaultBrowserLPw(userId);
21051            primeDomainVerificationsLPw(userId);
21052        }
21053    }
21054
21055    void onNewUserCreated(final int userId) {
21056        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21057        // If permission review for legacy apps is required, we represent
21058        // dagerous permissions for such apps as always granted runtime
21059        // permissions to keep per user flag state whether review is needed.
21060        // Hence, if a new user is added we have to propagate dangerous
21061        // permission grants for these legacy apps.
21062        if (mPermissionReviewRequired) {
21063            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21064                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21065        }
21066    }
21067
21068    @Override
21069    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21070        mContext.enforceCallingOrSelfPermission(
21071                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21072                "Only package verification agents can read the verifier device identity");
21073
21074        synchronized (mPackages) {
21075            return mSettings.getVerifierDeviceIdentityLPw();
21076        }
21077    }
21078
21079    @Override
21080    public void setPermissionEnforced(String permission, boolean enforced) {
21081        // TODO: Now that we no longer change GID for storage, this should to away.
21082        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21083                "setPermissionEnforced");
21084        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21085            synchronized (mPackages) {
21086                if (mSettings.mReadExternalStorageEnforced == null
21087                        || mSettings.mReadExternalStorageEnforced != enforced) {
21088                    mSettings.mReadExternalStorageEnforced = enforced;
21089                    mSettings.writeLPr();
21090                }
21091            }
21092            // kill any non-foreground processes so we restart them and
21093            // grant/revoke the GID.
21094            final IActivityManager am = ActivityManager.getService();
21095            if (am != null) {
21096                final long token = Binder.clearCallingIdentity();
21097                try {
21098                    am.killProcessesBelowForeground("setPermissionEnforcement");
21099                } catch (RemoteException e) {
21100                } finally {
21101                    Binder.restoreCallingIdentity(token);
21102                }
21103            }
21104        } else {
21105            throw new IllegalArgumentException("No selective enforcement for " + permission);
21106        }
21107    }
21108
21109    @Override
21110    @Deprecated
21111    public boolean isPermissionEnforced(String permission) {
21112        return true;
21113    }
21114
21115    @Override
21116    public boolean isStorageLow() {
21117        final long token = Binder.clearCallingIdentity();
21118        try {
21119            final DeviceStorageMonitorInternal
21120                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21121            if (dsm != null) {
21122                return dsm.isMemoryLow();
21123            } else {
21124                return false;
21125            }
21126        } finally {
21127            Binder.restoreCallingIdentity(token);
21128        }
21129    }
21130
21131    @Override
21132    public IPackageInstaller getPackageInstaller() {
21133        return mInstallerService;
21134    }
21135
21136    private boolean userNeedsBadging(int userId) {
21137        int index = mUserNeedsBadging.indexOfKey(userId);
21138        if (index < 0) {
21139            final UserInfo userInfo;
21140            final long token = Binder.clearCallingIdentity();
21141            try {
21142                userInfo = sUserManager.getUserInfo(userId);
21143            } finally {
21144                Binder.restoreCallingIdentity(token);
21145            }
21146            final boolean b;
21147            if (userInfo != null && userInfo.isManagedProfile()) {
21148                b = true;
21149            } else {
21150                b = false;
21151            }
21152            mUserNeedsBadging.put(userId, b);
21153            return b;
21154        }
21155        return mUserNeedsBadging.valueAt(index);
21156    }
21157
21158    @Override
21159    public KeySet getKeySetByAlias(String packageName, String alias) {
21160        if (packageName == null || alias == null) {
21161            return null;
21162        }
21163        synchronized(mPackages) {
21164            final PackageParser.Package pkg = mPackages.get(packageName);
21165            if (pkg == null) {
21166                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21167                throw new IllegalArgumentException("Unknown package: " + packageName);
21168            }
21169            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21170            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21171        }
21172    }
21173
21174    @Override
21175    public KeySet getSigningKeySet(String packageName) {
21176        if (packageName == null) {
21177            return null;
21178        }
21179        synchronized(mPackages) {
21180            final PackageParser.Package pkg = mPackages.get(packageName);
21181            if (pkg == null) {
21182                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21183                throw new IllegalArgumentException("Unknown package: " + packageName);
21184            }
21185            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21186                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21187                throw new SecurityException("May not access signing KeySet of other apps.");
21188            }
21189            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21190            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21191        }
21192    }
21193
21194    @Override
21195    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21196        if (packageName == null || ks == null) {
21197            return false;
21198        }
21199        synchronized(mPackages) {
21200            final PackageParser.Package pkg = mPackages.get(packageName);
21201            if (pkg == null) {
21202                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21203                throw new IllegalArgumentException("Unknown package: " + packageName);
21204            }
21205            IBinder ksh = ks.getToken();
21206            if (ksh instanceof KeySetHandle) {
21207                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21208                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21209            }
21210            return false;
21211        }
21212    }
21213
21214    @Override
21215    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21216        if (packageName == null || ks == null) {
21217            return false;
21218        }
21219        synchronized(mPackages) {
21220            final PackageParser.Package pkg = mPackages.get(packageName);
21221            if (pkg == null) {
21222                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21223                throw new IllegalArgumentException("Unknown package: " + packageName);
21224            }
21225            IBinder ksh = ks.getToken();
21226            if (ksh instanceof KeySetHandle) {
21227                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21228                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21229            }
21230            return false;
21231        }
21232    }
21233
21234    private void deletePackageIfUnusedLPr(final String packageName) {
21235        PackageSetting ps = mSettings.mPackages.get(packageName);
21236        if (ps == null) {
21237            return;
21238        }
21239        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21240            // TODO Implement atomic delete if package is unused
21241            // It is currently possible that the package will be deleted even if it is installed
21242            // after this method returns.
21243            mHandler.post(new Runnable() {
21244                public void run() {
21245                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21246                }
21247            });
21248        }
21249    }
21250
21251    /**
21252     * Check and throw if the given before/after packages would be considered a
21253     * downgrade.
21254     */
21255    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21256            throws PackageManagerException {
21257        if (after.versionCode < before.mVersionCode) {
21258            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21259                    "Update version code " + after.versionCode + " is older than current "
21260                    + before.mVersionCode);
21261        } else if (after.versionCode == before.mVersionCode) {
21262            if (after.baseRevisionCode < before.baseRevisionCode) {
21263                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21264                        "Update base revision code " + after.baseRevisionCode
21265                        + " is older than current " + before.baseRevisionCode);
21266            }
21267
21268            if (!ArrayUtils.isEmpty(after.splitNames)) {
21269                for (int i = 0; i < after.splitNames.length; i++) {
21270                    final String splitName = after.splitNames[i];
21271                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21272                    if (j != -1) {
21273                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21274                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21275                                    "Update split " + splitName + " revision code "
21276                                    + after.splitRevisionCodes[i] + " is older than current "
21277                                    + before.splitRevisionCodes[j]);
21278                        }
21279                    }
21280                }
21281            }
21282        }
21283    }
21284
21285    private static class MoveCallbacks extends Handler {
21286        private static final int MSG_CREATED = 1;
21287        private static final int MSG_STATUS_CHANGED = 2;
21288
21289        private final RemoteCallbackList<IPackageMoveObserver>
21290                mCallbacks = new RemoteCallbackList<>();
21291
21292        private final SparseIntArray mLastStatus = new SparseIntArray();
21293
21294        public MoveCallbacks(Looper looper) {
21295            super(looper);
21296        }
21297
21298        public void register(IPackageMoveObserver callback) {
21299            mCallbacks.register(callback);
21300        }
21301
21302        public void unregister(IPackageMoveObserver callback) {
21303            mCallbacks.unregister(callback);
21304        }
21305
21306        @Override
21307        public void handleMessage(Message msg) {
21308            final SomeArgs args = (SomeArgs) msg.obj;
21309            final int n = mCallbacks.beginBroadcast();
21310            for (int i = 0; i < n; i++) {
21311                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21312                try {
21313                    invokeCallback(callback, msg.what, args);
21314                } catch (RemoteException ignored) {
21315                }
21316            }
21317            mCallbacks.finishBroadcast();
21318            args.recycle();
21319        }
21320
21321        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21322                throws RemoteException {
21323            switch (what) {
21324                case MSG_CREATED: {
21325                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21326                    break;
21327                }
21328                case MSG_STATUS_CHANGED: {
21329                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21330                    break;
21331                }
21332            }
21333        }
21334
21335        private void notifyCreated(int moveId, Bundle extras) {
21336            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21337
21338            final SomeArgs args = SomeArgs.obtain();
21339            args.argi1 = moveId;
21340            args.arg2 = extras;
21341            obtainMessage(MSG_CREATED, args).sendToTarget();
21342        }
21343
21344        private void notifyStatusChanged(int moveId, int status) {
21345            notifyStatusChanged(moveId, status, -1);
21346        }
21347
21348        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21349            Slog.v(TAG, "Move " + moveId + " status " + status);
21350
21351            final SomeArgs args = SomeArgs.obtain();
21352            args.argi1 = moveId;
21353            args.argi2 = status;
21354            args.arg3 = estMillis;
21355            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21356
21357            synchronized (mLastStatus) {
21358                mLastStatus.put(moveId, status);
21359            }
21360        }
21361    }
21362
21363    private final static class OnPermissionChangeListeners extends Handler {
21364        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21365
21366        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21367                new RemoteCallbackList<>();
21368
21369        public OnPermissionChangeListeners(Looper looper) {
21370            super(looper);
21371        }
21372
21373        @Override
21374        public void handleMessage(Message msg) {
21375            switch (msg.what) {
21376                case MSG_ON_PERMISSIONS_CHANGED: {
21377                    final int uid = msg.arg1;
21378                    handleOnPermissionsChanged(uid);
21379                } break;
21380            }
21381        }
21382
21383        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21384            mPermissionListeners.register(listener);
21385
21386        }
21387
21388        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21389            mPermissionListeners.unregister(listener);
21390        }
21391
21392        public void onPermissionsChanged(int uid) {
21393            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21394                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21395            }
21396        }
21397
21398        private void handleOnPermissionsChanged(int uid) {
21399            final int count = mPermissionListeners.beginBroadcast();
21400            try {
21401                for (int i = 0; i < count; i++) {
21402                    IOnPermissionsChangeListener callback = mPermissionListeners
21403                            .getBroadcastItem(i);
21404                    try {
21405                        callback.onPermissionsChanged(uid);
21406                    } catch (RemoteException e) {
21407                        Log.e(TAG, "Permission listener is dead", e);
21408                    }
21409                }
21410            } finally {
21411                mPermissionListeners.finishBroadcast();
21412            }
21413        }
21414    }
21415
21416    private class PackageManagerInternalImpl extends PackageManagerInternal {
21417        @Override
21418        public void setLocationPackagesProvider(PackagesProvider provider) {
21419            synchronized (mPackages) {
21420                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21421            }
21422        }
21423
21424        @Override
21425        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21426            synchronized (mPackages) {
21427                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21428            }
21429        }
21430
21431        @Override
21432        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21433            synchronized (mPackages) {
21434                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21435            }
21436        }
21437
21438        @Override
21439        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21440            synchronized (mPackages) {
21441                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21442            }
21443        }
21444
21445        @Override
21446        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21447            synchronized (mPackages) {
21448                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21449            }
21450        }
21451
21452        @Override
21453        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21454            synchronized (mPackages) {
21455                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21456            }
21457        }
21458
21459        @Override
21460        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21461            synchronized (mPackages) {
21462                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21463                        packageName, userId);
21464            }
21465        }
21466
21467        @Override
21468        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21469            synchronized (mPackages) {
21470                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21471                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21472                        packageName, userId);
21473            }
21474        }
21475
21476        @Override
21477        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21478            synchronized (mPackages) {
21479                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21480                        packageName, userId);
21481            }
21482        }
21483
21484        @Override
21485        public void setKeepUninstalledPackages(final List<String> packageList) {
21486            Preconditions.checkNotNull(packageList);
21487            List<String> removedFromList = null;
21488            synchronized (mPackages) {
21489                if (mKeepUninstalledPackages != null) {
21490                    final int packagesCount = mKeepUninstalledPackages.size();
21491                    for (int i = 0; i < packagesCount; i++) {
21492                        String oldPackage = mKeepUninstalledPackages.get(i);
21493                        if (packageList != null && packageList.contains(oldPackage)) {
21494                            continue;
21495                        }
21496                        if (removedFromList == null) {
21497                            removedFromList = new ArrayList<>();
21498                        }
21499                        removedFromList.add(oldPackage);
21500                    }
21501                }
21502                mKeepUninstalledPackages = new ArrayList<>(packageList);
21503                if (removedFromList != null) {
21504                    final int removedCount = removedFromList.size();
21505                    for (int i = 0; i < removedCount; i++) {
21506                        deletePackageIfUnusedLPr(removedFromList.get(i));
21507                    }
21508                }
21509            }
21510        }
21511
21512        @Override
21513        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21514            synchronized (mPackages) {
21515                // If we do not support permission review, done.
21516                if (!mPermissionReviewRequired) {
21517                    return false;
21518                }
21519
21520                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21521                if (packageSetting == null) {
21522                    return false;
21523                }
21524
21525                // Permission review applies only to apps not supporting the new permission model.
21526                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21527                    return false;
21528                }
21529
21530                // Legacy apps have the permission and get user consent on launch.
21531                PermissionsState permissionsState = packageSetting.getPermissionsState();
21532                return permissionsState.isPermissionReviewRequired(userId);
21533            }
21534        }
21535
21536        @Override
21537        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21538            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21539        }
21540
21541        @Override
21542        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21543                int userId) {
21544            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21545        }
21546
21547        @Override
21548        public void setDeviceAndProfileOwnerPackages(
21549                int deviceOwnerUserId, String deviceOwnerPackage,
21550                SparseArray<String> profileOwnerPackages) {
21551            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21552                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21553        }
21554
21555        @Override
21556        public boolean isPackageDataProtected(int userId, String packageName) {
21557            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21558        }
21559
21560        @Override
21561        public boolean isPackageEphemeral(int userId, String packageName) {
21562            synchronized (mPackages) {
21563                PackageParser.Package p = mPackages.get(packageName);
21564                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21565            }
21566        }
21567
21568        @Override
21569        public boolean wasPackageEverLaunched(String packageName, int userId) {
21570            synchronized (mPackages) {
21571                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21572            }
21573        }
21574
21575        @Override
21576        public void grantRuntimePermission(String packageName, String name, int userId,
21577                boolean overridePolicy) {
21578            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21579                    overridePolicy);
21580        }
21581
21582        @Override
21583        public void revokeRuntimePermission(String packageName, String name, int userId,
21584                boolean overridePolicy) {
21585            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21586                    overridePolicy);
21587        }
21588
21589        @Override
21590        public String getNameForUid(int uid) {
21591            return PackageManagerService.this.getNameForUid(uid);
21592        }
21593
21594        @Override
21595        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21596                Intent origIntent, String resolvedType, Intent launchIntent,
21597                String callingPackage, int userId) {
21598            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21599                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21600        }
21601    }
21602
21603    @Override
21604    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21605        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21606        synchronized (mPackages) {
21607            final long identity = Binder.clearCallingIdentity();
21608            try {
21609                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21610                        packageNames, userId);
21611            } finally {
21612                Binder.restoreCallingIdentity(identity);
21613            }
21614        }
21615    }
21616
21617    private static void enforceSystemOrPhoneCaller(String tag) {
21618        int callingUid = Binder.getCallingUid();
21619        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21620            throw new SecurityException(
21621                    "Cannot call " + tag + " from UID " + callingUid);
21622        }
21623    }
21624
21625    boolean isHistoricalPackageUsageAvailable() {
21626        return mPackageUsage.isHistoricalPackageUsageAvailable();
21627    }
21628
21629    /**
21630     * Return a <b>copy</b> of the collection of packages known to the package manager.
21631     * @return A copy of the values of mPackages.
21632     */
21633    Collection<PackageParser.Package> getPackages() {
21634        synchronized (mPackages) {
21635            return new ArrayList<>(mPackages.values());
21636        }
21637    }
21638
21639    /**
21640     * Logs process start information (including base APK hash) to the security log.
21641     * @hide
21642     */
21643    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21644            String apkFile, int pid) {
21645        if (!SecurityLog.isLoggingEnabled()) {
21646            return;
21647        }
21648        Bundle data = new Bundle();
21649        data.putLong("startTimestamp", System.currentTimeMillis());
21650        data.putString("processName", processName);
21651        data.putInt("uid", uid);
21652        data.putString("seinfo", seinfo);
21653        data.putString("apkFile", apkFile);
21654        data.putInt("pid", pid);
21655        Message msg = mProcessLoggingHandler.obtainMessage(
21656                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21657        msg.setData(data);
21658        mProcessLoggingHandler.sendMessage(msg);
21659    }
21660
21661    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21662        return mCompilerStats.getPackageStats(pkgName);
21663    }
21664
21665    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21666        return getOrCreateCompilerPackageStats(pkg.packageName);
21667    }
21668
21669    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21670        return mCompilerStats.getOrCreatePackageStats(pkgName);
21671    }
21672
21673    public void deleteCompilerPackageStats(String pkgName) {
21674        mCompilerStats.deletePackageStats(pkgName);
21675    }
21676}
21677