PackageManagerService.java revision 457608986ca2e44cbe1677523d1892f1d8c8f985
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                // When specifying an explicit component, we prevent the activity from being
5528                // used when either 1) the calling package is normal and the activity is within
5529                // an ephemeral application or 2) the calling package is ephemeral and the
5530                // activity is not visible to ephemeral applications.
5531                boolean blockResolution =
5532                        (ephemeralPkgName == null
5533                                && (ai.applicationInfo.privateFlags
5534                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5535                        || (ephemeralPkgName != null
5536                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5537                if (!blockResolution) {
5538                    final ResolveInfo ri = new ResolveInfo();
5539                    ri.activityInfo = ai;
5540                    list.add(ri);
5541                }
5542            }
5543            return list;
5544        }
5545
5546        // reader
5547        boolean sortResult = false;
5548        boolean addEphemeral = false;
5549        List<ResolveInfo> result;
5550        final String pkgName = intent.getPackage();
5551        synchronized (mPackages) {
5552            if (pkgName == null) {
5553                List<CrossProfileIntentFilter> matchingFilters =
5554                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5555                // Check for results that need to skip the current profile.
5556                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5557                        resolvedType, flags, userId);
5558                if (xpResolveInfo != null) {
5559                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5560                    xpResult.add(xpResolveInfo);
5561                    return filterForEphemeral(
5562                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
5563                }
5564
5565                // Check for results in the current profile.
5566                result = filterIfNotSystemUser(mActivities.queryIntent(
5567                        intent, resolvedType, flags, userId), userId);
5568                addEphemeral =
5569                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5570
5571                // Check for cross profile results.
5572                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5573                xpResolveInfo = queryCrossProfileIntents(
5574                        matchingFilters, intent, resolvedType, flags, userId,
5575                        hasNonNegativePriorityResult);
5576                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5577                    boolean isVisibleToUser = filterIfNotSystemUser(
5578                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5579                    if (isVisibleToUser) {
5580                        result.add(xpResolveInfo);
5581                        sortResult = true;
5582                    }
5583                }
5584                if (hasWebURI(intent)) {
5585                    CrossProfileDomainInfo xpDomainInfo = null;
5586                    final UserInfo parent = getProfileParent(userId);
5587                    if (parent != null) {
5588                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5589                                flags, userId, parent.id);
5590                    }
5591                    if (xpDomainInfo != null) {
5592                        if (xpResolveInfo != null) {
5593                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5594                            // in the result.
5595                            result.remove(xpResolveInfo);
5596                        }
5597                        if (result.size() == 0 && !addEphemeral) {
5598                            // No result in current profile, but found candidate in parent user.
5599                            // And we are not going to add emphemeral app, so we can return the
5600                            // result straight away.
5601                            result.add(xpDomainInfo.resolveInfo);
5602                            return filterForEphemeral(result, ephemeralPkgName);
5603                        }
5604                    } else if (result.size() <= 1 && !addEphemeral) {
5605                        // No result in parent user and <= 1 result in current profile, and we
5606                        // are not going to add emphemeral app, so we can return the result without
5607                        // further processing.
5608                        return filterForEphemeral(result, ephemeralPkgName);
5609                    }
5610                    // We have more than one candidate (combining results from current and parent
5611                    // profile), so we need filtering and sorting.
5612                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
5613                            intent, flags, result, xpDomainInfo, userId);
5614                    sortResult = true;
5615                }
5616            } else {
5617                final PackageParser.Package pkg = mPackages.get(pkgName);
5618                if (pkg != null) {
5619                    result = filterForEphemeral(filterIfNotSystemUser(
5620                            mActivities.queryIntentForPackage(
5621                                    intent, resolvedType, flags, pkg.activities, userId),
5622                            userId), ephemeralPkgName);
5623                } else {
5624                    // the caller wants to resolve for a particular package; however, there
5625                    // were no installed results, so, try to find an ephemeral result
5626                    addEphemeral = isEphemeralAllowed(
5627                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
5628                    result = new ArrayList<ResolveInfo>();
5629                }
5630            }
5631        }
5632        if (addEphemeral) {
5633            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5634            final EphemeralRequest requestObject = new EphemeralRequest(
5635                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
5636                    null /*launchIntent*/, null /*callingPackage*/, userId);
5637            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
5638                    mContext, mEphemeralResolverConnection, requestObject);
5639            if (intentInfo != null) {
5640                if (DEBUG_EPHEMERAL) {
5641                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5642                }
5643                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5644                ephemeralInstaller.ephemeralResponse = intentInfo;
5645                // make sure this resolver is the default
5646                ephemeralInstaller.isDefault = true;
5647                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5648                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5649                // add a non-generic filter
5650                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5651                ephemeralInstaller.filter.addDataPath(
5652                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5653                result.add(ephemeralInstaller);
5654            }
5655            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5656        }
5657        if (sortResult) {
5658            Collections.sort(result, mResolvePrioritySorter);
5659        }
5660        return filterForEphemeral(result, ephemeralPkgName);
5661    }
5662
5663    private static class CrossProfileDomainInfo {
5664        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5665        ResolveInfo resolveInfo;
5666        /* Best domain verification status of the activities found in the other profile */
5667        int bestDomainVerificationStatus;
5668    }
5669
5670    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5671            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5672        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5673                sourceUserId)) {
5674            return null;
5675        }
5676        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5677                resolvedType, flags, parentUserId);
5678
5679        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5680            return null;
5681        }
5682        CrossProfileDomainInfo result = null;
5683        int size = resultTargetUser.size();
5684        for (int i = 0; i < size; i++) {
5685            ResolveInfo riTargetUser = resultTargetUser.get(i);
5686            // Intent filter verification is only for filters that specify a host. So don't return
5687            // those that handle all web uris.
5688            if (riTargetUser.handleAllWebDataURI) {
5689                continue;
5690            }
5691            String packageName = riTargetUser.activityInfo.packageName;
5692            PackageSetting ps = mSettings.mPackages.get(packageName);
5693            if (ps == null) {
5694                continue;
5695            }
5696            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5697            int status = (int)(verificationState >> 32);
5698            if (result == null) {
5699                result = new CrossProfileDomainInfo();
5700                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5701                        sourceUserId, parentUserId);
5702                result.bestDomainVerificationStatus = status;
5703            } else {
5704                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5705                        result.bestDomainVerificationStatus);
5706            }
5707        }
5708        // Don't consider matches with status NEVER across profiles.
5709        if (result != null && result.bestDomainVerificationStatus
5710                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5711            return null;
5712        }
5713        return result;
5714    }
5715
5716    /**
5717     * Verification statuses are ordered from the worse to the best, except for
5718     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5719     */
5720    private int bestDomainVerificationStatus(int status1, int status2) {
5721        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5722            return status2;
5723        }
5724        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5725            return status1;
5726        }
5727        return (int) MathUtils.max(status1, status2);
5728    }
5729
5730    private boolean isUserEnabled(int userId) {
5731        long callingId = Binder.clearCallingIdentity();
5732        try {
5733            UserInfo userInfo = sUserManager.getUserInfo(userId);
5734            return userInfo != null && userInfo.isEnabled();
5735        } finally {
5736            Binder.restoreCallingIdentity(callingId);
5737        }
5738    }
5739
5740    /**
5741     * Filter out activities with systemUserOnly flag set, when current user is not System.
5742     *
5743     * @return filtered list
5744     */
5745    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5746        if (userId == UserHandle.USER_SYSTEM) {
5747            return resolveInfos;
5748        }
5749        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5750            ResolveInfo info = resolveInfos.get(i);
5751            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5752                resolveInfos.remove(i);
5753            }
5754        }
5755        return resolveInfos;
5756    }
5757
5758    /**
5759     * Filters out ephemeral activities.
5760     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
5761     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
5762     *
5763     * @param resolveInfos The pre-filtered list of resolved activities
5764     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
5765     *          is performed.
5766     * @return A filtered list of resolved activities.
5767     */
5768    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
5769            String ephemeralPkgName) {
5770        if (ephemeralPkgName == null) {
5771            return resolveInfos;
5772        }
5773        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5774            ResolveInfo info = resolveInfos.get(i);
5775            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp();
5776            // allow activities that are defined in the provided package
5777            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
5778                continue;
5779            }
5780            // allow activities that have been explicitly exposed to ephemeral apps
5781            if (!isEphemeralApp
5782                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
5783                continue;
5784            }
5785            resolveInfos.remove(i);
5786        }
5787        return resolveInfos;
5788    }
5789
5790    /**
5791     * @param resolveInfos list of resolve infos in descending priority order
5792     * @return if the list contains a resolve info with non-negative priority
5793     */
5794    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5795        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5796    }
5797
5798    private static boolean hasWebURI(Intent intent) {
5799        if (intent.getData() == null) {
5800            return false;
5801        }
5802        final String scheme = intent.getScheme();
5803        if (TextUtils.isEmpty(scheme)) {
5804            return false;
5805        }
5806        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5807    }
5808
5809    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5810            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5811            int userId) {
5812        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5813
5814        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5815            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5816                    candidates.size());
5817        }
5818
5819        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5820        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5821        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5822        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5823        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5824        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5825
5826        synchronized (mPackages) {
5827            final int count = candidates.size();
5828            // First, try to use linked apps. Partition the candidates into four lists:
5829            // one for the final results, one for the "do not use ever", one for "undefined status"
5830            // and finally one for "browser app type".
5831            for (int n=0; n<count; n++) {
5832                ResolveInfo info = candidates.get(n);
5833                String packageName = info.activityInfo.packageName;
5834                PackageSetting ps = mSettings.mPackages.get(packageName);
5835                if (ps != null) {
5836                    // Add to the special match all list (Browser use case)
5837                    if (info.handleAllWebDataURI) {
5838                        matchAllList.add(info);
5839                        continue;
5840                    }
5841                    // Try to get the status from User settings first
5842                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5843                    int status = (int)(packedStatus >> 32);
5844                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5845                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5846                        if (DEBUG_DOMAIN_VERIFICATION) {
5847                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5848                                    + " : linkgen=" + linkGeneration);
5849                        }
5850                        // Use link-enabled generation as preferredOrder, i.e.
5851                        // prefer newly-enabled over earlier-enabled.
5852                        info.preferredOrder = linkGeneration;
5853                        alwaysList.add(info);
5854                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5855                        if (DEBUG_DOMAIN_VERIFICATION) {
5856                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5857                        }
5858                        neverList.add(info);
5859                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5860                        if (DEBUG_DOMAIN_VERIFICATION) {
5861                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5862                        }
5863                        alwaysAskList.add(info);
5864                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5865                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5866                        if (DEBUG_DOMAIN_VERIFICATION) {
5867                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5868                        }
5869                        undefinedList.add(info);
5870                    }
5871                }
5872            }
5873
5874            // We'll want to include browser possibilities in a few cases
5875            boolean includeBrowser = false;
5876
5877            // First try to add the "always" resolution(s) for the current user, if any
5878            if (alwaysList.size() > 0) {
5879                result.addAll(alwaysList);
5880            } else {
5881                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5882                result.addAll(undefinedList);
5883                // Maybe add one for the other profile.
5884                if (xpDomainInfo != null && (
5885                        xpDomainInfo.bestDomainVerificationStatus
5886                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5887                    result.add(xpDomainInfo.resolveInfo);
5888                }
5889                includeBrowser = true;
5890            }
5891
5892            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5893            // If there were 'always' entries their preferred order has been set, so we also
5894            // back that off to make the alternatives equivalent
5895            if (alwaysAskList.size() > 0) {
5896                for (ResolveInfo i : result) {
5897                    i.preferredOrder = 0;
5898                }
5899                result.addAll(alwaysAskList);
5900                includeBrowser = true;
5901            }
5902
5903            if (includeBrowser) {
5904                // Also add browsers (all of them or only the default one)
5905                if (DEBUG_DOMAIN_VERIFICATION) {
5906                    Slog.v(TAG, "   ...including browsers in candidate set");
5907                }
5908                if ((matchFlags & MATCH_ALL) != 0) {
5909                    result.addAll(matchAllList);
5910                } else {
5911                    // Browser/generic handling case.  If there's a default browser, go straight
5912                    // to that (but only if there is no other higher-priority match).
5913                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5914                    int maxMatchPrio = 0;
5915                    ResolveInfo defaultBrowserMatch = null;
5916                    final int numCandidates = matchAllList.size();
5917                    for (int n = 0; n < numCandidates; n++) {
5918                        ResolveInfo info = matchAllList.get(n);
5919                        // track the highest overall match priority...
5920                        if (info.priority > maxMatchPrio) {
5921                            maxMatchPrio = info.priority;
5922                        }
5923                        // ...and the highest-priority default browser match
5924                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5925                            if (defaultBrowserMatch == null
5926                                    || (defaultBrowserMatch.priority < info.priority)) {
5927                                if (debug) {
5928                                    Slog.v(TAG, "Considering default browser match " + info);
5929                                }
5930                                defaultBrowserMatch = info;
5931                            }
5932                        }
5933                    }
5934                    if (defaultBrowserMatch != null
5935                            && defaultBrowserMatch.priority >= maxMatchPrio
5936                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5937                    {
5938                        if (debug) {
5939                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5940                        }
5941                        result.add(defaultBrowserMatch);
5942                    } else {
5943                        result.addAll(matchAllList);
5944                    }
5945                }
5946
5947                // If there is nothing selected, add all candidates and remove the ones that the user
5948                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5949                if (result.size() == 0) {
5950                    result.addAll(candidates);
5951                    result.removeAll(neverList);
5952                }
5953            }
5954        }
5955        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5956            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5957                    result.size());
5958            for (ResolveInfo info : result) {
5959                Slog.v(TAG, "  + " + info.activityInfo);
5960            }
5961        }
5962        return result;
5963    }
5964
5965    // Returns a packed value as a long:
5966    //
5967    // high 'int'-sized word: link status: undefined/ask/never/always.
5968    // low 'int'-sized word: relative priority among 'always' results.
5969    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5970        long result = ps.getDomainVerificationStatusForUser(userId);
5971        // if none available, get the master status
5972        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5973            if (ps.getIntentFilterVerificationInfo() != null) {
5974                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5975            }
5976        }
5977        return result;
5978    }
5979
5980    private ResolveInfo querySkipCurrentProfileIntents(
5981            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5982            int flags, int sourceUserId) {
5983        if (matchingFilters != null) {
5984            int size = matchingFilters.size();
5985            for (int i = 0; i < size; i ++) {
5986                CrossProfileIntentFilter filter = matchingFilters.get(i);
5987                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5988                    // Checking if there are activities in the target user that can handle the
5989                    // intent.
5990                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5991                            resolvedType, flags, sourceUserId);
5992                    if (resolveInfo != null) {
5993                        return resolveInfo;
5994                    }
5995                }
5996            }
5997        }
5998        return null;
5999    }
6000
6001    // Return matching ResolveInfo in target user if any.
6002    private ResolveInfo queryCrossProfileIntents(
6003            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6004            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6005        if (matchingFilters != null) {
6006            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6007            // match the same intent. For performance reasons, it is better not to
6008            // run queryIntent twice for the same userId
6009            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6010            int size = matchingFilters.size();
6011            for (int i = 0; i < size; i++) {
6012                CrossProfileIntentFilter filter = matchingFilters.get(i);
6013                int targetUserId = filter.getTargetUserId();
6014                boolean skipCurrentProfile =
6015                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6016                boolean skipCurrentProfileIfNoMatchFound =
6017                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6018                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6019                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6020                    // Checking if there are activities in the target user that can handle the
6021                    // intent.
6022                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6023                            resolvedType, flags, sourceUserId);
6024                    if (resolveInfo != null) return resolveInfo;
6025                    alreadyTriedUserIds.put(targetUserId, true);
6026                }
6027            }
6028        }
6029        return null;
6030    }
6031
6032    /**
6033     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6034     * will forward the intent to the filter's target user.
6035     * Otherwise, returns null.
6036     */
6037    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6038            String resolvedType, int flags, int sourceUserId) {
6039        int targetUserId = filter.getTargetUserId();
6040        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6041                resolvedType, flags, targetUserId);
6042        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6043            // If all the matches in the target profile are suspended, return null.
6044            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6045                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6046                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6047                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6048                            targetUserId);
6049                }
6050            }
6051        }
6052        return null;
6053    }
6054
6055    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6056            int sourceUserId, int targetUserId) {
6057        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6058        long ident = Binder.clearCallingIdentity();
6059        boolean targetIsProfile;
6060        try {
6061            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6062        } finally {
6063            Binder.restoreCallingIdentity(ident);
6064        }
6065        String className;
6066        if (targetIsProfile) {
6067            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6068        } else {
6069            className = FORWARD_INTENT_TO_PARENT;
6070        }
6071        ComponentName forwardingActivityComponentName = new ComponentName(
6072                mAndroidApplication.packageName, className);
6073        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6074                sourceUserId);
6075        if (!targetIsProfile) {
6076            forwardingActivityInfo.showUserIcon = targetUserId;
6077            forwardingResolveInfo.noResourceId = true;
6078        }
6079        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6080        forwardingResolveInfo.priority = 0;
6081        forwardingResolveInfo.preferredOrder = 0;
6082        forwardingResolveInfo.match = 0;
6083        forwardingResolveInfo.isDefault = true;
6084        forwardingResolveInfo.filter = filter;
6085        forwardingResolveInfo.targetUserId = targetUserId;
6086        return forwardingResolveInfo;
6087    }
6088
6089    @Override
6090    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6091            Intent[] specifics, String[] specificTypes, Intent intent,
6092            String resolvedType, int flags, int userId) {
6093        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6094                specificTypes, intent, resolvedType, flags, userId));
6095    }
6096
6097    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6098            Intent[] specifics, String[] specificTypes, Intent intent,
6099            String resolvedType, int flags, int userId) {
6100        if (!sUserManager.exists(userId)) return Collections.emptyList();
6101        flags = updateFlagsForResolve(flags, userId, intent);
6102        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6103                false /* requireFullPermission */, false /* checkShell */,
6104                "query intent activity options");
6105        final String resultsAction = intent.getAction();
6106
6107        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6108                | PackageManager.GET_RESOLVED_FILTER, userId);
6109
6110        if (DEBUG_INTENT_MATCHING) {
6111            Log.v(TAG, "Query " + intent + ": " + results);
6112        }
6113
6114        int specificsPos = 0;
6115        int N;
6116
6117        // todo: note that the algorithm used here is O(N^2).  This
6118        // isn't a problem in our current environment, but if we start running
6119        // into situations where we have more than 5 or 10 matches then this
6120        // should probably be changed to something smarter...
6121
6122        // First we go through and resolve each of the specific items
6123        // that were supplied, taking care of removing any corresponding
6124        // duplicate items in the generic resolve list.
6125        if (specifics != null) {
6126            for (int i=0; i<specifics.length; i++) {
6127                final Intent sintent = specifics[i];
6128                if (sintent == null) {
6129                    continue;
6130                }
6131
6132                if (DEBUG_INTENT_MATCHING) {
6133                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6134                }
6135
6136                String action = sintent.getAction();
6137                if (resultsAction != null && resultsAction.equals(action)) {
6138                    // If this action was explicitly requested, then don't
6139                    // remove things that have it.
6140                    action = null;
6141                }
6142
6143                ResolveInfo ri = null;
6144                ActivityInfo ai = null;
6145
6146                ComponentName comp = sintent.getComponent();
6147                if (comp == null) {
6148                    ri = resolveIntent(
6149                        sintent,
6150                        specificTypes != null ? specificTypes[i] : null,
6151                            flags, userId);
6152                    if (ri == null) {
6153                        continue;
6154                    }
6155                    if (ri == mResolveInfo) {
6156                        // ACK!  Must do something better with this.
6157                    }
6158                    ai = ri.activityInfo;
6159                    comp = new ComponentName(ai.applicationInfo.packageName,
6160                            ai.name);
6161                } else {
6162                    ai = getActivityInfo(comp, flags, userId);
6163                    if (ai == null) {
6164                        continue;
6165                    }
6166                }
6167
6168                // Look for any generic query activities that are duplicates
6169                // of this specific one, and remove them from the results.
6170                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6171                N = results.size();
6172                int j;
6173                for (j=specificsPos; j<N; j++) {
6174                    ResolveInfo sri = results.get(j);
6175                    if ((sri.activityInfo.name.equals(comp.getClassName())
6176                            && sri.activityInfo.applicationInfo.packageName.equals(
6177                                    comp.getPackageName()))
6178                        || (action != null && sri.filter.matchAction(action))) {
6179                        results.remove(j);
6180                        if (DEBUG_INTENT_MATCHING) Log.v(
6181                            TAG, "Removing duplicate item from " + j
6182                            + " due to specific " + specificsPos);
6183                        if (ri == null) {
6184                            ri = sri;
6185                        }
6186                        j--;
6187                        N--;
6188                    }
6189                }
6190
6191                // Add this specific item to its proper place.
6192                if (ri == null) {
6193                    ri = new ResolveInfo();
6194                    ri.activityInfo = ai;
6195                }
6196                results.add(specificsPos, ri);
6197                ri.specificIndex = i;
6198                specificsPos++;
6199            }
6200        }
6201
6202        // Now we go through the remaining generic results and remove any
6203        // duplicate actions that are found here.
6204        N = results.size();
6205        for (int i=specificsPos; i<N-1; i++) {
6206            final ResolveInfo rii = results.get(i);
6207            if (rii.filter == null) {
6208                continue;
6209            }
6210
6211            // Iterate over all of the actions of this result's intent
6212            // filter...  typically this should be just one.
6213            final Iterator<String> it = rii.filter.actionsIterator();
6214            if (it == null) {
6215                continue;
6216            }
6217            while (it.hasNext()) {
6218                final String action = it.next();
6219                if (resultsAction != null && resultsAction.equals(action)) {
6220                    // If this action was explicitly requested, then don't
6221                    // remove things that have it.
6222                    continue;
6223                }
6224                for (int j=i+1; j<N; j++) {
6225                    final ResolveInfo rij = results.get(j);
6226                    if (rij.filter != null && rij.filter.hasAction(action)) {
6227                        results.remove(j);
6228                        if (DEBUG_INTENT_MATCHING) Log.v(
6229                            TAG, "Removing duplicate item from " + j
6230                            + " due to action " + action + " at " + i);
6231                        j--;
6232                        N--;
6233                    }
6234                }
6235            }
6236
6237            // If the caller didn't request filter information, drop it now
6238            // so we don't have to marshall/unmarshall it.
6239            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6240                rii.filter = null;
6241            }
6242        }
6243
6244        // Filter out the caller activity if so requested.
6245        if (caller != null) {
6246            N = results.size();
6247            for (int i=0; i<N; i++) {
6248                ActivityInfo ainfo = results.get(i).activityInfo;
6249                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6250                        && caller.getClassName().equals(ainfo.name)) {
6251                    results.remove(i);
6252                    break;
6253                }
6254            }
6255        }
6256
6257        // If the caller didn't request filter information,
6258        // drop them now so we don't have to
6259        // marshall/unmarshall it.
6260        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6261            N = results.size();
6262            for (int i=0; i<N; i++) {
6263                results.get(i).filter = null;
6264            }
6265        }
6266
6267        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6268        return results;
6269    }
6270
6271    @Override
6272    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6273            String resolvedType, int flags, int userId) {
6274        return new ParceledListSlice<>(
6275                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6276    }
6277
6278    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6279            String resolvedType, int flags, int userId) {
6280        if (!sUserManager.exists(userId)) return Collections.emptyList();
6281        flags = updateFlagsForResolve(flags, userId, intent);
6282        ComponentName comp = intent.getComponent();
6283        if (comp == null) {
6284            if (intent.getSelector() != null) {
6285                intent = intent.getSelector();
6286                comp = intent.getComponent();
6287            }
6288        }
6289        if (comp != null) {
6290            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6291            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6292            if (ai != null) {
6293                ResolveInfo ri = new ResolveInfo();
6294                ri.activityInfo = ai;
6295                list.add(ri);
6296            }
6297            return list;
6298        }
6299
6300        // reader
6301        synchronized (mPackages) {
6302            String pkgName = intent.getPackage();
6303            if (pkgName == null) {
6304                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6305            }
6306            final PackageParser.Package pkg = mPackages.get(pkgName);
6307            if (pkg != null) {
6308                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6309                        userId);
6310            }
6311            return Collections.emptyList();
6312        }
6313    }
6314
6315    @Override
6316    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6317        if (!sUserManager.exists(userId)) return null;
6318        flags = updateFlagsForResolve(flags, userId, intent);
6319        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6320        if (query != null) {
6321            if (query.size() >= 1) {
6322                // If there is more than one service with the same priority,
6323                // just arbitrarily pick the first one.
6324                return query.get(0);
6325            }
6326        }
6327        return null;
6328    }
6329
6330    @Override
6331    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6332            String resolvedType, int flags, int userId) {
6333        return new ParceledListSlice<>(
6334                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6335    }
6336
6337    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6338            String resolvedType, int flags, int userId) {
6339        if (!sUserManager.exists(userId)) return Collections.emptyList();
6340        flags = updateFlagsForResolve(flags, userId, intent);
6341        ComponentName comp = intent.getComponent();
6342        if (comp == null) {
6343            if (intent.getSelector() != null) {
6344                intent = intent.getSelector();
6345                comp = intent.getComponent();
6346            }
6347        }
6348        if (comp != null) {
6349            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6350            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6351            if (si != null) {
6352                final ResolveInfo ri = new ResolveInfo();
6353                ri.serviceInfo = si;
6354                list.add(ri);
6355            }
6356            return list;
6357        }
6358
6359        // reader
6360        synchronized (mPackages) {
6361            String pkgName = intent.getPackage();
6362            if (pkgName == null) {
6363                return mServices.queryIntent(intent, resolvedType, flags, userId);
6364            }
6365            final PackageParser.Package pkg = mPackages.get(pkgName);
6366            if (pkg != null) {
6367                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6368                        userId);
6369            }
6370            return Collections.emptyList();
6371        }
6372    }
6373
6374    @Override
6375    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6376            String resolvedType, int flags, int userId) {
6377        return new ParceledListSlice<>(
6378                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6379    }
6380
6381    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6382            Intent intent, String resolvedType, int flags, int userId) {
6383        if (!sUserManager.exists(userId)) return Collections.emptyList();
6384        flags = updateFlagsForResolve(flags, userId, intent);
6385        ComponentName comp = intent.getComponent();
6386        if (comp == null) {
6387            if (intent.getSelector() != null) {
6388                intent = intent.getSelector();
6389                comp = intent.getComponent();
6390            }
6391        }
6392        if (comp != null) {
6393            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6394            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6395            if (pi != null) {
6396                final ResolveInfo ri = new ResolveInfo();
6397                ri.providerInfo = pi;
6398                list.add(ri);
6399            }
6400            return list;
6401        }
6402
6403        // reader
6404        synchronized (mPackages) {
6405            String pkgName = intent.getPackage();
6406            if (pkgName == null) {
6407                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6408            }
6409            final PackageParser.Package pkg = mPackages.get(pkgName);
6410            if (pkg != null) {
6411                return mProviders.queryIntentForPackage(
6412                        intent, resolvedType, flags, pkg.providers, userId);
6413            }
6414            return Collections.emptyList();
6415        }
6416    }
6417
6418    @Override
6419    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6420        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6421        flags = updateFlagsForPackage(flags, userId, null);
6422        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6423        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6424                true /* requireFullPermission */, false /* checkShell */,
6425                "get installed packages");
6426
6427        // writer
6428        synchronized (mPackages) {
6429            ArrayList<PackageInfo> list;
6430            if (listUninstalled) {
6431                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6432                for (PackageSetting ps : mSettings.mPackages.values()) {
6433                    final PackageInfo pi;
6434                    if (ps.pkg != null) {
6435                        pi = generatePackageInfo(ps, flags, userId);
6436                    } else {
6437                        pi = generatePackageInfo(ps, flags, userId);
6438                    }
6439                    if (pi != null) {
6440                        list.add(pi);
6441                    }
6442                }
6443            } else {
6444                list = new ArrayList<PackageInfo>(mPackages.size());
6445                for (PackageParser.Package p : mPackages.values()) {
6446                    final PackageInfo pi =
6447                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6448                    if (pi != null) {
6449                        list.add(pi);
6450                    }
6451                }
6452            }
6453
6454            return new ParceledListSlice<PackageInfo>(list);
6455        }
6456    }
6457
6458    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6459            String[] permissions, boolean[] tmp, int flags, int userId) {
6460        int numMatch = 0;
6461        final PermissionsState permissionsState = ps.getPermissionsState();
6462        for (int i=0; i<permissions.length; i++) {
6463            final String permission = permissions[i];
6464            if (permissionsState.hasPermission(permission, userId)) {
6465                tmp[i] = true;
6466                numMatch++;
6467            } else {
6468                tmp[i] = false;
6469            }
6470        }
6471        if (numMatch == 0) {
6472            return;
6473        }
6474        final PackageInfo pi;
6475        if (ps.pkg != null) {
6476            pi = generatePackageInfo(ps, flags, userId);
6477        } else {
6478            pi = generatePackageInfo(ps, flags, userId);
6479        }
6480        // The above might return null in cases of uninstalled apps or install-state
6481        // skew across users/profiles.
6482        if (pi != null) {
6483            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6484                if (numMatch == permissions.length) {
6485                    pi.requestedPermissions = permissions;
6486                } else {
6487                    pi.requestedPermissions = new String[numMatch];
6488                    numMatch = 0;
6489                    for (int i=0; i<permissions.length; i++) {
6490                        if (tmp[i]) {
6491                            pi.requestedPermissions[numMatch] = permissions[i];
6492                            numMatch++;
6493                        }
6494                    }
6495                }
6496            }
6497            list.add(pi);
6498        }
6499    }
6500
6501    @Override
6502    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6503            String[] permissions, int flags, int userId) {
6504        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6505        flags = updateFlagsForPackage(flags, userId, permissions);
6506        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6507                true /* requireFullPermission */, false /* checkShell */,
6508                "get packages holding permissions");
6509        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6510
6511        // writer
6512        synchronized (mPackages) {
6513            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6514            boolean[] tmpBools = new boolean[permissions.length];
6515            if (listUninstalled) {
6516                for (PackageSetting ps : mSettings.mPackages.values()) {
6517                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6518                            userId);
6519                }
6520            } else {
6521                for (PackageParser.Package pkg : mPackages.values()) {
6522                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6523                    if (ps != null) {
6524                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6525                                userId);
6526                    }
6527                }
6528            }
6529
6530            return new ParceledListSlice<PackageInfo>(list);
6531        }
6532    }
6533
6534    @Override
6535    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6536        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6537        flags = updateFlagsForApplication(flags, userId, null);
6538        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6539
6540        // writer
6541        synchronized (mPackages) {
6542            ArrayList<ApplicationInfo> list;
6543            if (listUninstalled) {
6544                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6545                for (PackageSetting ps : mSettings.mPackages.values()) {
6546                    ApplicationInfo ai;
6547                    int effectiveFlags = flags;
6548                    if (ps.isSystem()) {
6549                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6550                    }
6551                    if (ps.pkg != null) {
6552                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
6553                                ps.readUserState(userId), userId);
6554                    } else {
6555                        ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags,
6556                                userId);
6557                    }
6558                    if (ai != null) {
6559                        list.add(ai);
6560                    }
6561                }
6562            } else {
6563                list = new ArrayList<ApplicationInfo>(mPackages.size());
6564                for (PackageParser.Package p : mPackages.values()) {
6565                    if (p.mExtras != null) {
6566                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6567                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6568                        if (ai != null) {
6569                            list.add(ai);
6570                        }
6571                    }
6572                }
6573            }
6574
6575            return new ParceledListSlice<ApplicationInfo>(list);
6576        }
6577    }
6578
6579    @Override
6580    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6581        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6582            return null;
6583        }
6584
6585        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6586                "getEphemeralApplications");
6587        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6588                true /* requireFullPermission */, false /* checkShell */,
6589                "getEphemeralApplications");
6590        synchronized (mPackages) {
6591            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6592                    .getEphemeralApplicationsLPw(userId);
6593            if (ephemeralApps != null) {
6594                return new ParceledListSlice<>(ephemeralApps);
6595            }
6596        }
6597        return null;
6598    }
6599
6600    @Override
6601    public boolean isEphemeralApplication(String packageName, int userId) {
6602        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6603                true /* requireFullPermission */, false /* checkShell */,
6604                "isEphemeral");
6605        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6606            return false;
6607        }
6608
6609        if (!isCallerSameApp(packageName)) {
6610            return false;
6611        }
6612        synchronized (mPackages) {
6613            PackageParser.Package pkg = mPackages.get(packageName);
6614            if (pkg != null) {
6615                return pkg.applicationInfo.isEphemeralApp();
6616            }
6617        }
6618        return false;
6619    }
6620
6621    @Override
6622    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6623        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6624            return null;
6625        }
6626
6627        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6628                true /* requireFullPermission */, false /* checkShell */,
6629                "getCookie");
6630        if (!isCallerSameApp(packageName)) {
6631            return null;
6632        }
6633        synchronized (mPackages) {
6634            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6635                    packageName, userId);
6636        }
6637    }
6638
6639    @Override
6640    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6641        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6642            return true;
6643        }
6644
6645        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6646                true /* requireFullPermission */, true /* checkShell */,
6647                "setCookie");
6648        if (!isCallerSameApp(packageName)) {
6649            return false;
6650        }
6651        synchronized (mPackages) {
6652            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6653                    packageName, cookie, userId);
6654        }
6655    }
6656
6657    @Override
6658    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6659        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6660            return null;
6661        }
6662
6663        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6664                "getEphemeralApplicationIcon");
6665        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6666                true /* requireFullPermission */, false /* checkShell */,
6667                "getEphemeralApplicationIcon");
6668        synchronized (mPackages) {
6669            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6670                    packageName, userId);
6671        }
6672    }
6673
6674    private boolean isCallerSameApp(String packageName) {
6675        PackageParser.Package pkg = mPackages.get(packageName);
6676        return pkg != null
6677                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6678    }
6679
6680    @Override
6681    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6682        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6683    }
6684
6685    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6686        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6687
6688        // reader
6689        synchronized (mPackages) {
6690            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6691            final int userId = UserHandle.getCallingUserId();
6692            while (i.hasNext()) {
6693                final PackageParser.Package p = i.next();
6694                if (p.applicationInfo == null) continue;
6695
6696                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6697                        && !p.applicationInfo.isDirectBootAware();
6698                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6699                        && p.applicationInfo.isDirectBootAware();
6700
6701                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6702                        && (!mSafeMode || isSystemApp(p))
6703                        && (matchesUnaware || matchesAware)) {
6704                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6705                    if (ps != null) {
6706                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6707                                ps.readUserState(userId), userId);
6708                        if (ai != null) {
6709                            finalList.add(ai);
6710                        }
6711                    }
6712                }
6713            }
6714        }
6715
6716        return finalList;
6717    }
6718
6719    @Override
6720    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6721        if (!sUserManager.exists(userId)) return null;
6722        flags = updateFlagsForComponent(flags, userId, name);
6723        // reader
6724        synchronized (mPackages) {
6725            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6726            PackageSetting ps = provider != null
6727                    ? mSettings.mPackages.get(provider.owner.packageName)
6728                    : null;
6729            return ps != null
6730                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6731                    ? PackageParser.generateProviderInfo(provider, flags,
6732                            ps.readUserState(userId), userId)
6733                    : null;
6734        }
6735    }
6736
6737    /**
6738     * @deprecated
6739     */
6740    @Deprecated
6741    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6742        // reader
6743        synchronized (mPackages) {
6744            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6745                    .entrySet().iterator();
6746            final int userId = UserHandle.getCallingUserId();
6747            while (i.hasNext()) {
6748                Map.Entry<String, PackageParser.Provider> entry = i.next();
6749                PackageParser.Provider p = entry.getValue();
6750                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6751
6752                if (ps != null && p.syncable
6753                        && (!mSafeMode || (p.info.applicationInfo.flags
6754                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6755                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6756                            ps.readUserState(userId), userId);
6757                    if (info != null) {
6758                        outNames.add(entry.getKey());
6759                        outInfo.add(info);
6760                    }
6761                }
6762            }
6763        }
6764    }
6765
6766    @Override
6767    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6768            int uid, int flags) {
6769        final int userId = processName != null ? UserHandle.getUserId(uid)
6770                : UserHandle.getCallingUserId();
6771        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6772        flags = updateFlagsForComponent(flags, userId, processName);
6773
6774        ArrayList<ProviderInfo> finalList = null;
6775        // reader
6776        synchronized (mPackages) {
6777            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6778            while (i.hasNext()) {
6779                final PackageParser.Provider p = i.next();
6780                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6781                if (ps != null && p.info.authority != null
6782                        && (processName == null
6783                                || (p.info.processName.equals(processName)
6784                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6785                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6786                    if (finalList == null) {
6787                        finalList = new ArrayList<ProviderInfo>(3);
6788                    }
6789                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6790                            ps.readUserState(userId), userId);
6791                    if (info != null) {
6792                        finalList.add(info);
6793                    }
6794                }
6795            }
6796        }
6797
6798        if (finalList != null) {
6799            Collections.sort(finalList, mProviderInitOrderSorter);
6800            return new ParceledListSlice<ProviderInfo>(finalList);
6801        }
6802
6803        return ParceledListSlice.emptyList();
6804    }
6805
6806    @Override
6807    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6808        // reader
6809        synchronized (mPackages) {
6810            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6811            return PackageParser.generateInstrumentationInfo(i, flags);
6812        }
6813    }
6814
6815    @Override
6816    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6817            String targetPackage, int flags) {
6818        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6819    }
6820
6821    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6822            int flags) {
6823        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6824
6825        // reader
6826        synchronized (mPackages) {
6827            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6828            while (i.hasNext()) {
6829                final PackageParser.Instrumentation p = i.next();
6830                if (targetPackage == null
6831                        || targetPackage.equals(p.info.targetPackage)) {
6832                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6833                            flags);
6834                    if (ii != null) {
6835                        finalList.add(ii);
6836                    }
6837                }
6838            }
6839        }
6840
6841        return finalList;
6842    }
6843
6844    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6845        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6846        if (overlays == null) {
6847            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6848            return;
6849        }
6850        for (PackageParser.Package opkg : overlays.values()) {
6851            // Not much to do if idmap fails: we already logged the error
6852            // and we certainly don't want to abort installation of pkg simply
6853            // because an overlay didn't fit properly. For these reasons,
6854            // ignore the return value of createIdmapForPackagePairLI.
6855            createIdmapForPackagePairLI(pkg, opkg);
6856        }
6857    }
6858
6859    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6860            PackageParser.Package opkg) {
6861        if (!opkg.mTrustedOverlay) {
6862            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6863                    opkg.baseCodePath + ": overlay not trusted");
6864            return false;
6865        }
6866        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6867        if (overlaySet == null) {
6868            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6869                    opkg.baseCodePath + " but target package has no known overlays");
6870            return false;
6871        }
6872        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6873        // TODO: generate idmap for split APKs
6874        try {
6875            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6876        } catch (InstallerException e) {
6877            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6878                    + opkg.baseCodePath);
6879            return false;
6880        }
6881        PackageParser.Package[] overlayArray =
6882            overlaySet.values().toArray(new PackageParser.Package[0]);
6883        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6884            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6885                return p1.mOverlayPriority - p2.mOverlayPriority;
6886            }
6887        };
6888        Arrays.sort(overlayArray, cmp);
6889
6890        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6891        int i = 0;
6892        for (PackageParser.Package p : overlayArray) {
6893            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6894        }
6895        return true;
6896    }
6897
6898    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6899        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6900        try {
6901            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6902        } finally {
6903            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6904        }
6905    }
6906
6907    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6908        final File[] files = dir.listFiles();
6909        if (ArrayUtils.isEmpty(files)) {
6910            Log.d(TAG, "No files in app dir " + dir);
6911            return;
6912        }
6913
6914        if (DEBUG_PACKAGE_SCANNING) {
6915            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6916                    + " flags=0x" + Integer.toHexString(parseFlags));
6917        }
6918        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
6919                mSeparateProcesses, mOnlyCore, mMetrics);
6920
6921        // Submit files for parsing in parallel
6922        int fileCount = 0;
6923        for (File file : files) {
6924            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6925                    && !PackageInstallerService.isStageName(file.getName());
6926            if (!isPackage) {
6927                // Ignore entries which are not packages
6928                continue;
6929            }
6930            parallelPackageParser.submit(file, parseFlags);
6931            fileCount++;
6932        }
6933
6934        // Process results one by one
6935        for (; fileCount > 0; fileCount--) {
6936            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
6937            Throwable throwable = parseResult.throwable;
6938            int errorCode = PackageManager.INSTALL_SUCCEEDED;
6939
6940            if (throwable == null) {
6941                try {
6942                    scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
6943                            currentTime, null);
6944                } catch (PackageManagerException e) {
6945                    errorCode = e.error;
6946                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
6947                }
6948            } else if (throwable instanceof PackageParser.PackageParserException) {
6949                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
6950                        throwable;
6951                errorCode = e.error;
6952                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
6953            } else {
6954                throw new IllegalStateException("Unexpected exception occurred while parsing "
6955                        + parseResult.scanFile, throwable);
6956            }
6957
6958            // Delete invalid userdata apps
6959            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6960                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
6961                logCriticalInfo(Log.WARN,
6962                        "Deleting invalid package at " + parseResult.scanFile);
6963                removeCodePathLI(parseResult.scanFile);
6964            }
6965        }
6966        parallelPackageParser.close();
6967    }
6968
6969    private static File getSettingsProblemFile() {
6970        File dataDir = Environment.getDataDirectory();
6971        File systemDir = new File(dataDir, "system");
6972        File fname = new File(systemDir, "uiderrors.txt");
6973        return fname;
6974    }
6975
6976    static void reportSettingsProblem(int priority, String msg) {
6977        logCriticalInfo(priority, msg);
6978    }
6979
6980    static void logCriticalInfo(int priority, String msg) {
6981        Slog.println(priority, TAG, msg);
6982        EventLogTags.writePmCriticalInfo(msg);
6983        try {
6984            File fname = getSettingsProblemFile();
6985            FileOutputStream out = new FileOutputStream(fname, true);
6986            PrintWriter pw = new FastPrintWriter(out);
6987            SimpleDateFormat formatter = new SimpleDateFormat();
6988            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6989            pw.println(dateString + ": " + msg);
6990            pw.close();
6991            FileUtils.setPermissions(
6992                    fname.toString(),
6993                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6994                    -1, -1);
6995        } catch (java.io.IOException e) {
6996        }
6997    }
6998
6999    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7000        if (srcFile.isDirectory()) {
7001            final File baseFile = new File(pkg.baseCodePath);
7002            long maxModifiedTime = baseFile.lastModified();
7003            if (pkg.splitCodePaths != null) {
7004                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7005                    final File splitFile = new File(pkg.splitCodePaths[i]);
7006                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7007                }
7008            }
7009            return maxModifiedTime;
7010        }
7011        return srcFile.lastModified();
7012    }
7013
7014    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7015            final int policyFlags) throws PackageManagerException {
7016        // When upgrading from pre-N MR1, verify the package time stamp using the package
7017        // directory and not the APK file.
7018        final long lastModifiedTime = mIsPreNMR1Upgrade
7019                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7020        if (ps != null
7021                && ps.codePath.equals(srcFile)
7022                && ps.timeStamp == lastModifiedTime
7023                && !isCompatSignatureUpdateNeeded(pkg)
7024                && !isRecoverSignatureUpdateNeeded(pkg)) {
7025            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7026            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7027            ArraySet<PublicKey> signingKs;
7028            synchronized (mPackages) {
7029                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7030            }
7031            if (ps.signatures.mSignatures != null
7032                    && ps.signatures.mSignatures.length != 0
7033                    && signingKs != null) {
7034                // Optimization: reuse the existing cached certificates
7035                // if the package appears to be unchanged.
7036                pkg.mSignatures = ps.signatures.mSignatures;
7037                pkg.mSigningKeys = signingKs;
7038                return;
7039            }
7040
7041            Slog.w(TAG, "PackageSetting for " + ps.name
7042                    + " is missing signatures.  Collecting certs again to recover them.");
7043        } else {
7044            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7045        }
7046
7047        try {
7048            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7049            PackageParser.collectCertificates(pkg, policyFlags);
7050        } catch (PackageParserException e) {
7051            throw PackageManagerException.from(e);
7052        } finally {
7053            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7054        }
7055    }
7056
7057    /**
7058     *  Traces a package scan.
7059     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7060     */
7061    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7062            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7063        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7064        try {
7065            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7066        } finally {
7067            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7068        }
7069    }
7070
7071    /**
7072     *  Scans a package and returns the newly parsed package.
7073     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7074     */
7075    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7076            long currentTime, UserHandle user) throws PackageManagerException {
7077        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7078        PackageParser pp = new PackageParser();
7079        pp.setSeparateProcesses(mSeparateProcesses);
7080        pp.setOnlyCoreApps(mOnlyCore);
7081        pp.setDisplayMetrics(mMetrics);
7082
7083        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7084            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7085        }
7086
7087        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7088        final PackageParser.Package pkg;
7089        try {
7090            pkg = pp.parsePackage(scanFile, parseFlags);
7091        } catch (PackageParserException e) {
7092            throw PackageManagerException.from(e);
7093        } finally {
7094            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7095        }
7096
7097        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7098    }
7099
7100    /**
7101     *  Scans a package and returns the newly parsed package.
7102     *  @throws PackageManagerException on a parse error.
7103     */
7104    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7105            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7106            throws PackageManagerException {
7107        // If the package has children and this is the first dive in the function
7108        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7109        // packages (parent and children) would be successfully scanned before the
7110        // actual scan since scanning mutates internal state and we want to atomically
7111        // install the package and its children.
7112        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7113            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7114                scanFlags |= SCAN_CHECK_ONLY;
7115            }
7116        } else {
7117            scanFlags &= ~SCAN_CHECK_ONLY;
7118        }
7119
7120        // Scan the parent
7121        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7122                scanFlags, currentTime, user);
7123
7124        // Scan the children
7125        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7126        for (int i = 0; i < childCount; i++) {
7127            PackageParser.Package childPackage = pkg.childPackages.get(i);
7128            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7129                    currentTime, user);
7130        }
7131
7132
7133        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7134            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7135        }
7136
7137        return scannedPkg;
7138    }
7139
7140    /**
7141     *  Scans a package and returns the newly parsed package.
7142     *  @throws PackageManagerException on a parse error.
7143     */
7144    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7145            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7146            throws PackageManagerException {
7147        PackageSetting ps = null;
7148        PackageSetting updatedPkg;
7149        // reader
7150        synchronized (mPackages) {
7151            // Look to see if we already know about this package.
7152            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7153            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7154                // This package has been renamed to its original name.  Let's
7155                // use that.
7156                ps = mSettings.getPackageLPr(oldName);
7157            }
7158            // If there was no original package, see one for the real package name.
7159            if (ps == null) {
7160                ps = mSettings.getPackageLPr(pkg.packageName);
7161            }
7162            // Check to see if this package could be hiding/updating a system
7163            // package.  Must look for it either under the original or real
7164            // package name depending on our state.
7165            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7166            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7167
7168            // If this is a package we don't know about on the system partition, we
7169            // may need to remove disabled child packages on the system partition
7170            // or may need to not add child packages if the parent apk is updated
7171            // on the data partition and no longer defines this child package.
7172            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7173                // If this is a parent package for an updated system app and this system
7174                // app got an OTA update which no longer defines some of the child packages
7175                // we have to prune them from the disabled system packages.
7176                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7177                if (disabledPs != null) {
7178                    final int scannedChildCount = (pkg.childPackages != null)
7179                            ? pkg.childPackages.size() : 0;
7180                    final int disabledChildCount = disabledPs.childPackageNames != null
7181                            ? disabledPs.childPackageNames.size() : 0;
7182                    for (int i = 0; i < disabledChildCount; i++) {
7183                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7184                        boolean disabledPackageAvailable = false;
7185                        for (int j = 0; j < scannedChildCount; j++) {
7186                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7187                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7188                                disabledPackageAvailable = true;
7189                                break;
7190                            }
7191                         }
7192                         if (!disabledPackageAvailable) {
7193                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7194                         }
7195                    }
7196                }
7197            }
7198        }
7199
7200        boolean updatedPkgBetter = false;
7201        // First check if this is a system package that may involve an update
7202        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7203            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7204            // it needs to drop FLAG_PRIVILEGED.
7205            if (locationIsPrivileged(scanFile)) {
7206                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7207            } else {
7208                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7209            }
7210
7211            if (ps != null && !ps.codePath.equals(scanFile)) {
7212                // The path has changed from what was last scanned...  check the
7213                // version of the new path against what we have stored to determine
7214                // what to do.
7215                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7216                if (pkg.mVersionCode <= ps.versionCode) {
7217                    // The system package has been updated and the code path does not match
7218                    // Ignore entry. Skip it.
7219                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7220                            + " ignored: updated version " + ps.versionCode
7221                            + " better than this " + pkg.mVersionCode);
7222                    if (!updatedPkg.codePath.equals(scanFile)) {
7223                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7224                                + ps.name + " changing from " + updatedPkg.codePathString
7225                                + " to " + scanFile);
7226                        updatedPkg.codePath = scanFile;
7227                        updatedPkg.codePathString = scanFile.toString();
7228                        updatedPkg.resourcePath = scanFile;
7229                        updatedPkg.resourcePathString = scanFile.toString();
7230                    }
7231                    updatedPkg.pkg = pkg;
7232                    updatedPkg.versionCode = pkg.mVersionCode;
7233
7234                    // Update the disabled system child packages to point to the package too.
7235                    final int childCount = updatedPkg.childPackageNames != null
7236                            ? updatedPkg.childPackageNames.size() : 0;
7237                    for (int i = 0; i < childCount; i++) {
7238                        String childPackageName = updatedPkg.childPackageNames.get(i);
7239                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7240                                childPackageName);
7241                        if (updatedChildPkg != null) {
7242                            updatedChildPkg.pkg = pkg;
7243                            updatedChildPkg.versionCode = pkg.mVersionCode;
7244                        }
7245                    }
7246
7247                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7248                            + scanFile + " ignored: updated version " + ps.versionCode
7249                            + " better than this " + pkg.mVersionCode);
7250                } else {
7251                    // The current app on the system partition is better than
7252                    // what we have updated to on the data partition; switch
7253                    // back to the system partition version.
7254                    // At this point, its safely assumed that package installation for
7255                    // apps in system partition will go through. If not there won't be a working
7256                    // version of the app
7257                    // writer
7258                    synchronized (mPackages) {
7259                        // Just remove the loaded entries from package lists.
7260                        mPackages.remove(ps.name);
7261                    }
7262
7263                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7264                            + " reverting from " + ps.codePathString
7265                            + ": new version " + pkg.mVersionCode
7266                            + " better than installed " + ps.versionCode);
7267
7268                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7269                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7270                    synchronized (mInstallLock) {
7271                        args.cleanUpResourcesLI();
7272                    }
7273                    synchronized (mPackages) {
7274                        mSettings.enableSystemPackageLPw(ps.name);
7275                    }
7276                    updatedPkgBetter = true;
7277                }
7278            }
7279        }
7280
7281        if (updatedPkg != null) {
7282            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7283            // initially
7284            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7285
7286            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7287            // flag set initially
7288            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7289                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7290            }
7291        }
7292
7293        // Verify certificates against what was last scanned
7294        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7295
7296        /*
7297         * A new system app appeared, but we already had a non-system one of the
7298         * same name installed earlier.
7299         */
7300        boolean shouldHideSystemApp = false;
7301        if (updatedPkg == null && ps != null
7302                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7303            /*
7304             * Check to make sure the signatures match first. If they don't,
7305             * wipe the installed application and its data.
7306             */
7307            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7308                    != PackageManager.SIGNATURE_MATCH) {
7309                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7310                        + " signatures don't match existing userdata copy; removing");
7311                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7312                        "scanPackageInternalLI")) {
7313                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7314                }
7315                ps = null;
7316            } else {
7317                /*
7318                 * If the newly-added system app is an older version than the
7319                 * already installed version, hide it. It will be scanned later
7320                 * and re-added like an update.
7321                 */
7322                if (pkg.mVersionCode <= ps.versionCode) {
7323                    shouldHideSystemApp = true;
7324                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7325                            + " but new version " + pkg.mVersionCode + " better than installed "
7326                            + ps.versionCode + "; hiding system");
7327                } else {
7328                    /*
7329                     * The newly found system app is a newer version that the
7330                     * one previously installed. Simply remove the
7331                     * already-installed application and replace it with our own
7332                     * while keeping the application data.
7333                     */
7334                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7335                            + " reverting from " + ps.codePathString + ": new version "
7336                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7337                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7338                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7339                    synchronized (mInstallLock) {
7340                        args.cleanUpResourcesLI();
7341                    }
7342                }
7343            }
7344        }
7345
7346        // The apk is forward locked (not public) if its code and resources
7347        // are kept in different files. (except for app in either system or
7348        // vendor path).
7349        // TODO grab this value from PackageSettings
7350        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7351            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7352                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7353            }
7354        }
7355
7356        // TODO: extend to support forward-locked splits
7357        String resourcePath = null;
7358        String baseResourcePath = null;
7359        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7360            if (ps != null && ps.resourcePathString != null) {
7361                resourcePath = ps.resourcePathString;
7362                baseResourcePath = ps.resourcePathString;
7363            } else {
7364                // Should not happen at all. Just log an error.
7365                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7366            }
7367        } else {
7368            resourcePath = pkg.codePath;
7369            baseResourcePath = pkg.baseCodePath;
7370        }
7371
7372        // Set application objects path explicitly.
7373        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7374        pkg.setApplicationInfoCodePath(pkg.codePath);
7375        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7376        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7377        pkg.setApplicationInfoResourcePath(resourcePath);
7378        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7379        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7380
7381        // Note that we invoke the following method only if we are about to unpack an application
7382        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7383                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7384
7385        /*
7386         * If the system app should be overridden by a previously installed
7387         * data, hide the system app now and let the /data/app scan pick it up
7388         * again.
7389         */
7390        if (shouldHideSystemApp) {
7391            synchronized (mPackages) {
7392                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7393            }
7394        }
7395
7396        return scannedPkg;
7397    }
7398
7399    private static String fixProcessName(String defProcessName,
7400            String processName) {
7401        if (processName == null) {
7402            return defProcessName;
7403        }
7404        return processName;
7405    }
7406
7407    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7408            throws PackageManagerException {
7409        if (pkgSetting.signatures.mSignatures != null) {
7410            // Already existing package. Make sure signatures match
7411            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7412                    == PackageManager.SIGNATURE_MATCH;
7413            if (!match) {
7414                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7415                        == PackageManager.SIGNATURE_MATCH;
7416            }
7417            if (!match) {
7418                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7419                        == PackageManager.SIGNATURE_MATCH;
7420            }
7421            if (!match) {
7422                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7423                        + pkg.packageName + " signatures do not match the "
7424                        + "previously installed version; ignoring!");
7425            }
7426        }
7427
7428        // Check for shared user signatures
7429        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7430            // Already existing package. Make sure signatures match
7431            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7432                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7433            if (!match) {
7434                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7435                        == PackageManager.SIGNATURE_MATCH;
7436            }
7437            if (!match) {
7438                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7439                        == PackageManager.SIGNATURE_MATCH;
7440            }
7441            if (!match) {
7442                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7443                        "Package " + pkg.packageName
7444                        + " has no signatures that match those in shared user "
7445                        + pkgSetting.sharedUser.name + "; ignoring!");
7446            }
7447        }
7448    }
7449
7450    /**
7451     * Enforces that only the system UID or root's UID can call a method exposed
7452     * via Binder.
7453     *
7454     * @param message used as message if SecurityException is thrown
7455     * @throws SecurityException if the caller is not system or root
7456     */
7457    private static final void enforceSystemOrRoot(String message) {
7458        final int uid = Binder.getCallingUid();
7459        if (uid != Process.SYSTEM_UID && uid != 0) {
7460            throw new SecurityException(message);
7461        }
7462    }
7463
7464    @Override
7465    public void performFstrimIfNeeded() {
7466        enforceSystemOrRoot("Only the system can request fstrim");
7467
7468        // Before everything else, see whether we need to fstrim.
7469        try {
7470            IStorageManager sm = PackageHelper.getStorageManager();
7471            if (sm != null) {
7472                boolean doTrim = false;
7473                final long interval = android.provider.Settings.Global.getLong(
7474                        mContext.getContentResolver(),
7475                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7476                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7477                if (interval > 0) {
7478                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7479                    if (timeSinceLast > interval) {
7480                        doTrim = true;
7481                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7482                                + "; running immediately");
7483                    }
7484                }
7485                if (doTrim) {
7486                    final boolean dexOptDialogShown;
7487                    synchronized (mPackages) {
7488                        dexOptDialogShown = mDexOptDialogShown;
7489                    }
7490                    if (!isFirstBoot() && dexOptDialogShown) {
7491                        try {
7492                            ActivityManager.getService().showBootMessage(
7493                                    mContext.getResources().getString(
7494                                            R.string.android_upgrading_fstrim), true);
7495                        } catch (RemoteException e) {
7496                        }
7497                    }
7498                    sm.runMaintenance();
7499                }
7500            } else {
7501                Slog.e(TAG, "storageManager service unavailable!");
7502            }
7503        } catch (RemoteException e) {
7504            // Can't happen; StorageManagerService is local
7505        }
7506    }
7507
7508    @Override
7509    public void updatePackagesIfNeeded() {
7510        enforceSystemOrRoot("Only the system can request package update");
7511
7512        // We need to re-extract after an OTA.
7513        boolean causeUpgrade = isUpgrade();
7514
7515        // First boot or factory reset.
7516        // Note: we also handle devices that are upgrading to N right now as if it is their
7517        //       first boot, as they do not have profile data.
7518        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7519
7520        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7521        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7522
7523        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7524            return;
7525        }
7526
7527        List<PackageParser.Package> pkgs;
7528        synchronized (mPackages) {
7529            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7530        }
7531
7532        final long startTime = System.nanoTime();
7533        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7534                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7535
7536        final int elapsedTimeSeconds =
7537                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7538
7539        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7540        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7541        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7542        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7543        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7544    }
7545
7546    /**
7547     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7548     * containing statistics about the invocation. The array consists of three elements,
7549     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7550     * and {@code numberOfPackagesFailed}.
7551     */
7552    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7553            String compilerFilter) {
7554
7555        int numberOfPackagesVisited = 0;
7556        int numberOfPackagesOptimized = 0;
7557        int numberOfPackagesSkipped = 0;
7558        int numberOfPackagesFailed = 0;
7559        final int numberOfPackagesToDexopt = pkgs.size();
7560
7561        for (PackageParser.Package pkg : pkgs) {
7562            numberOfPackagesVisited++;
7563
7564            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7565                if (DEBUG_DEXOPT) {
7566                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7567                }
7568                numberOfPackagesSkipped++;
7569                continue;
7570            }
7571
7572            if (DEBUG_DEXOPT) {
7573                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7574                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7575            }
7576
7577            if (showDialog) {
7578                try {
7579                    ActivityManager.getService().showBootMessage(
7580                            mContext.getResources().getString(R.string.android_upgrading_apk,
7581                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7582                } catch (RemoteException e) {
7583                }
7584                synchronized (mPackages) {
7585                    mDexOptDialogShown = true;
7586                }
7587            }
7588
7589            // If the OTA updates a system app which was previously preopted to a non-preopted state
7590            // the app might end up being verified at runtime. That's because by default the apps
7591            // are verify-profile but for preopted apps there's no profile.
7592            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7593            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7594            // filter (by default interpret-only).
7595            // Note that at this stage unused apps are already filtered.
7596            if (isSystemApp(pkg) &&
7597                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7598                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7599                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7600            }
7601
7602            // checkProfiles is false to avoid merging profiles during boot which
7603            // might interfere with background compilation (b/28612421).
7604            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7605            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7606            // trade-off worth doing to save boot time work.
7607            int dexOptStatus = performDexOptTraced(pkg.packageName,
7608                    false /* checkProfiles */,
7609                    compilerFilter,
7610                    false /* force */);
7611            switch (dexOptStatus) {
7612                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7613                    numberOfPackagesOptimized++;
7614                    break;
7615                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7616                    numberOfPackagesSkipped++;
7617                    break;
7618                case PackageDexOptimizer.DEX_OPT_FAILED:
7619                    numberOfPackagesFailed++;
7620                    break;
7621                default:
7622                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7623                    break;
7624            }
7625        }
7626
7627        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7628                numberOfPackagesFailed };
7629    }
7630
7631    @Override
7632    public void notifyPackageUse(String packageName, int reason) {
7633        synchronized (mPackages) {
7634            PackageParser.Package p = mPackages.get(packageName);
7635            if (p == null) {
7636                return;
7637            }
7638            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7639        }
7640    }
7641
7642    @Override
7643    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
7644      // TODO(calin): b/32871170
7645    }
7646
7647    // TODO: this is not used nor needed. Delete it.
7648    @Override
7649    public boolean performDexOptIfNeeded(String packageName) {
7650        int dexOptStatus = performDexOptTraced(packageName,
7651                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7652        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7653    }
7654
7655    @Override
7656    public boolean performDexOpt(String packageName,
7657            boolean checkProfiles, int compileReason, boolean force) {
7658        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7659                getCompilerFilterForReason(compileReason), force);
7660        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7661    }
7662
7663    @Override
7664    public boolean performDexOptMode(String packageName,
7665            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7666        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7667                targetCompilerFilter, force);
7668        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7669    }
7670
7671    private int performDexOptTraced(String packageName,
7672                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7673        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7674        try {
7675            return performDexOptInternal(packageName, checkProfiles,
7676                    targetCompilerFilter, force);
7677        } finally {
7678            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7679        }
7680    }
7681
7682    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7683    // if the package can now be considered up to date for the given filter.
7684    private int performDexOptInternal(String packageName,
7685                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7686        PackageParser.Package p;
7687        synchronized (mPackages) {
7688            p = mPackages.get(packageName);
7689            if (p == null) {
7690                // Package could not be found. Report failure.
7691                return PackageDexOptimizer.DEX_OPT_FAILED;
7692            }
7693            mPackageUsage.maybeWriteAsync(mPackages);
7694            mCompilerStats.maybeWriteAsync();
7695        }
7696        long callingId = Binder.clearCallingIdentity();
7697        try {
7698            synchronized (mInstallLock) {
7699                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7700                        targetCompilerFilter, force);
7701            }
7702        } finally {
7703            Binder.restoreCallingIdentity(callingId);
7704        }
7705    }
7706
7707    public ArraySet<String> getOptimizablePackages() {
7708        ArraySet<String> pkgs = new ArraySet<String>();
7709        synchronized (mPackages) {
7710            for (PackageParser.Package p : mPackages.values()) {
7711                if (PackageDexOptimizer.canOptimizePackage(p)) {
7712                    pkgs.add(p.packageName);
7713                }
7714            }
7715        }
7716        return pkgs;
7717    }
7718
7719    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7720            boolean checkProfiles, String targetCompilerFilter,
7721            boolean force) {
7722        // Select the dex optimizer based on the force parameter.
7723        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7724        //       allocate an object here.
7725        PackageDexOptimizer pdo = force
7726                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7727                : mPackageDexOptimizer;
7728
7729        // Optimize all dependencies first. Note: we ignore the return value and march on
7730        // on errors.
7731        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7732        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7733        if (!deps.isEmpty()) {
7734            for (PackageParser.Package depPackage : deps) {
7735                // TODO: Analyze and investigate if we (should) profile libraries.
7736                // Currently this will do a full compilation of the library by default.
7737                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7738                        false /* checkProfiles */,
7739                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7740                        getOrCreateCompilerPackageStats(depPackage));
7741            }
7742        }
7743        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7744                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7745    }
7746
7747    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7748        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7749            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7750            Set<String> collectedNames = new HashSet<>();
7751            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7752
7753            retValue.remove(p);
7754
7755            return retValue;
7756        } else {
7757            return Collections.emptyList();
7758        }
7759    }
7760
7761    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7762            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7763        if (!collectedNames.contains(p.packageName)) {
7764            collectedNames.add(p.packageName);
7765            collected.add(p);
7766
7767            if (p.usesLibraries != null) {
7768                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7769            }
7770            if (p.usesOptionalLibraries != null) {
7771                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7772                        collectedNames);
7773            }
7774        }
7775    }
7776
7777    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7778            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7779        for (String libName : libs) {
7780            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7781            if (libPkg != null) {
7782                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7783            }
7784        }
7785    }
7786
7787    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7788        synchronized (mPackages) {
7789            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7790            if (lib != null && lib.apk != null) {
7791                return mPackages.get(lib.apk);
7792            }
7793        }
7794        return null;
7795    }
7796
7797    public void shutdown() {
7798        mPackageUsage.writeNow(mPackages);
7799        mCompilerStats.writeNow();
7800    }
7801
7802    @Override
7803    public void dumpProfiles(String packageName) {
7804        PackageParser.Package pkg;
7805        synchronized (mPackages) {
7806            pkg = mPackages.get(packageName);
7807            if (pkg == null) {
7808                throw new IllegalArgumentException("Unknown package: " + packageName);
7809            }
7810        }
7811        /* Only the shell, root, or the app user should be able to dump profiles. */
7812        int callingUid = Binder.getCallingUid();
7813        if (callingUid != Process.SHELL_UID &&
7814            callingUid != Process.ROOT_UID &&
7815            callingUid != pkg.applicationInfo.uid) {
7816            throw new SecurityException("dumpProfiles");
7817        }
7818
7819        synchronized (mInstallLock) {
7820            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7821            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7822            try {
7823                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7824                String codePaths = TextUtils.join(";", allCodePaths);
7825                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
7826            } catch (InstallerException e) {
7827                Slog.w(TAG, "Failed to dump profiles", e);
7828            }
7829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7830        }
7831    }
7832
7833    @Override
7834    public void forceDexOpt(String packageName) {
7835        enforceSystemOrRoot("forceDexOpt");
7836
7837        PackageParser.Package pkg;
7838        synchronized (mPackages) {
7839            pkg = mPackages.get(packageName);
7840            if (pkg == null) {
7841                throw new IllegalArgumentException("Unknown package: " + packageName);
7842            }
7843        }
7844
7845        synchronized (mInstallLock) {
7846            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7847
7848            // Whoever is calling forceDexOpt wants a fully compiled package.
7849            // Don't use profiles since that may cause compilation to be skipped.
7850            final int res = performDexOptInternalWithDependenciesLI(pkg,
7851                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7852                    true /* force */);
7853
7854            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7855            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7856                throw new IllegalStateException("Failed to dexopt: " + res);
7857            }
7858        }
7859    }
7860
7861    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7862        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7863            Slog.w(TAG, "Unable to update from " + oldPkg.name
7864                    + " to " + newPkg.packageName
7865                    + ": old package not in system partition");
7866            return false;
7867        } else if (mPackages.get(oldPkg.name) != null) {
7868            Slog.w(TAG, "Unable to update from " + oldPkg.name
7869                    + " to " + newPkg.packageName
7870                    + ": old package still exists");
7871            return false;
7872        }
7873        return true;
7874    }
7875
7876    void removeCodePathLI(File codePath) {
7877        if (codePath.isDirectory()) {
7878            try {
7879                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7880            } catch (InstallerException e) {
7881                Slog.w(TAG, "Failed to remove code path", e);
7882            }
7883        } else {
7884            codePath.delete();
7885        }
7886    }
7887
7888    private int[] resolveUserIds(int userId) {
7889        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7890    }
7891
7892    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7893        if (pkg == null) {
7894            Slog.wtf(TAG, "Package was null!", new Throwable());
7895            return;
7896        }
7897        clearAppDataLeafLIF(pkg, userId, flags);
7898        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7899        for (int i = 0; i < childCount; i++) {
7900            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7901        }
7902    }
7903
7904    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7905        final PackageSetting ps;
7906        synchronized (mPackages) {
7907            ps = mSettings.mPackages.get(pkg.packageName);
7908        }
7909        for (int realUserId : resolveUserIds(userId)) {
7910            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7911            try {
7912                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7913                        ceDataInode);
7914            } catch (InstallerException e) {
7915                Slog.w(TAG, String.valueOf(e));
7916            }
7917        }
7918    }
7919
7920    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7921        if (pkg == null) {
7922            Slog.wtf(TAG, "Package was null!", new Throwable());
7923            return;
7924        }
7925        destroyAppDataLeafLIF(pkg, userId, flags);
7926        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7927        for (int i = 0; i < childCount; i++) {
7928            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7929        }
7930    }
7931
7932    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7933        final PackageSetting ps;
7934        synchronized (mPackages) {
7935            ps = mSettings.mPackages.get(pkg.packageName);
7936        }
7937        for (int realUserId : resolveUserIds(userId)) {
7938            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7939            try {
7940                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7941                        ceDataInode);
7942            } catch (InstallerException e) {
7943                Slog.w(TAG, String.valueOf(e));
7944            }
7945        }
7946    }
7947
7948    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7949        if (pkg == null) {
7950            Slog.wtf(TAG, "Package was null!", new Throwable());
7951            return;
7952        }
7953        destroyAppProfilesLeafLIF(pkg);
7954        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7955        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7956        for (int i = 0; i < childCount; i++) {
7957            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7958            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7959                    true /* removeBaseMarker */);
7960        }
7961    }
7962
7963    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7964            boolean removeBaseMarker) {
7965        if (pkg.isForwardLocked()) {
7966            return;
7967        }
7968
7969        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7970            try {
7971                path = PackageManagerServiceUtils.realpath(new File(path));
7972            } catch (IOException e) {
7973                // TODO: Should we return early here ?
7974                Slog.w(TAG, "Failed to get canonical path", e);
7975                continue;
7976            }
7977
7978            final String useMarker = path.replace('/', '@');
7979            for (int realUserId : resolveUserIds(userId)) {
7980                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7981                if (removeBaseMarker) {
7982                    File foreignUseMark = new File(profileDir, useMarker);
7983                    if (foreignUseMark.exists()) {
7984                        if (!foreignUseMark.delete()) {
7985                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7986                                    + pkg.packageName);
7987                        }
7988                    }
7989                }
7990
7991                File[] markers = profileDir.listFiles();
7992                if (markers != null) {
7993                    final String searchString = "@" + pkg.packageName + "@";
7994                    // We also delete all markers that contain the package name we're
7995                    // uninstalling. These are associated with secondary dex-files belonging
7996                    // to the package. Reconstructing the path of these dex files is messy
7997                    // in general.
7998                    for (File marker : markers) {
7999                        if (marker.getName().indexOf(searchString) > 0) {
8000                            if (!marker.delete()) {
8001                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8002                                    + pkg.packageName);
8003                            }
8004                        }
8005                    }
8006                }
8007            }
8008        }
8009    }
8010
8011    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8012        try {
8013            mInstaller.destroyAppProfiles(pkg.packageName);
8014        } catch (InstallerException e) {
8015            Slog.w(TAG, String.valueOf(e));
8016        }
8017    }
8018
8019    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8020        if (pkg == null) {
8021            Slog.wtf(TAG, "Package was null!", new Throwable());
8022            return;
8023        }
8024        clearAppProfilesLeafLIF(pkg);
8025        // We don't remove the base foreign use marker when clearing profiles because
8026        // we will rename it when the app is updated. Unlike the actual profile contents,
8027        // the foreign use marker is good across installs.
8028        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8029        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8030        for (int i = 0; i < childCount; i++) {
8031            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8032        }
8033    }
8034
8035    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8036        try {
8037            mInstaller.clearAppProfiles(pkg.packageName);
8038        } catch (InstallerException e) {
8039            Slog.w(TAG, String.valueOf(e));
8040        }
8041    }
8042
8043    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8044            long lastUpdateTime) {
8045        // Set parent install/update time
8046        PackageSetting ps = (PackageSetting) pkg.mExtras;
8047        if (ps != null) {
8048            ps.firstInstallTime = firstInstallTime;
8049            ps.lastUpdateTime = lastUpdateTime;
8050        }
8051        // Set children install/update time
8052        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8053        for (int i = 0; i < childCount; i++) {
8054            PackageParser.Package childPkg = pkg.childPackages.get(i);
8055            ps = (PackageSetting) childPkg.mExtras;
8056            if (ps != null) {
8057                ps.firstInstallTime = firstInstallTime;
8058                ps.lastUpdateTime = lastUpdateTime;
8059            }
8060        }
8061    }
8062
8063    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8064            PackageParser.Package changingLib) {
8065        if (file.path != null) {
8066            usesLibraryFiles.add(file.path);
8067            return;
8068        }
8069        PackageParser.Package p = mPackages.get(file.apk);
8070        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8071            // If we are doing this while in the middle of updating a library apk,
8072            // then we need to make sure to use that new apk for determining the
8073            // dependencies here.  (We haven't yet finished committing the new apk
8074            // to the package manager state.)
8075            if (p == null || p.packageName.equals(changingLib.packageName)) {
8076                p = changingLib;
8077            }
8078        }
8079        if (p != null) {
8080            usesLibraryFiles.addAll(p.getAllCodePaths());
8081        }
8082    }
8083
8084    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8085            PackageParser.Package changingLib) throws PackageManagerException {
8086        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
8087            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
8088            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
8089            for (int i=0; i<N; i++) {
8090                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
8091                if (file == null) {
8092                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8093                            "Package " + pkg.packageName + " requires unavailable shared library "
8094                            + pkg.usesLibraries.get(i) + "; failing!");
8095                }
8096                addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8097            }
8098            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
8099            for (int i=0; i<N; i++) {
8100                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
8101                if (file == null) {
8102                    Slog.w(TAG, "Package " + pkg.packageName
8103                            + " desires unavailable shared library "
8104                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
8105                } else {
8106                    addSharedLibraryLPr(usesLibraryFiles, file, changingLib);
8107                }
8108            }
8109            N = usesLibraryFiles.size();
8110            if (N > 0) {
8111                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
8112            } else {
8113                pkg.usesLibraryFiles = null;
8114            }
8115        }
8116    }
8117
8118    private static boolean hasString(List<String> list, List<String> which) {
8119        if (list == null) {
8120            return false;
8121        }
8122        for (int i=list.size()-1; i>=0; i--) {
8123            for (int j=which.size()-1; j>=0; j--) {
8124                if (which.get(j).equals(list.get(i))) {
8125                    return true;
8126                }
8127            }
8128        }
8129        return false;
8130    }
8131
8132    private void updateAllSharedLibrariesLPw() {
8133        for (PackageParser.Package pkg : mPackages.values()) {
8134            try {
8135                updateSharedLibrariesLPr(pkg, null);
8136            } catch (PackageManagerException e) {
8137                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8138            }
8139        }
8140    }
8141
8142    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8143            PackageParser.Package changingPkg) {
8144        ArrayList<PackageParser.Package> res = null;
8145        for (PackageParser.Package pkg : mPackages.values()) {
8146            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
8147                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
8148                if (res == null) {
8149                    res = new ArrayList<PackageParser.Package>();
8150                }
8151                res.add(pkg);
8152                try {
8153                    updateSharedLibrariesLPr(pkg, changingPkg);
8154                } catch (PackageManagerException e) {
8155                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8156                }
8157            }
8158        }
8159        return res;
8160    }
8161
8162    /**
8163     * Derive the value of the {@code cpuAbiOverride} based on the provided
8164     * value and an optional stored value from the package settings.
8165     */
8166    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8167        String cpuAbiOverride = null;
8168
8169        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8170            cpuAbiOverride = null;
8171        } else if (abiOverride != null) {
8172            cpuAbiOverride = abiOverride;
8173        } else if (settings != null) {
8174            cpuAbiOverride = settings.cpuAbiOverrideString;
8175        }
8176
8177        return cpuAbiOverride;
8178    }
8179
8180    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8181            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8182                    throws PackageManagerException {
8183        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8184        // If the package has children and this is the first dive in the function
8185        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8186        // whether all packages (parent and children) would be successfully scanned
8187        // before the actual scan since scanning mutates internal state and we want
8188        // to atomically install the package and its children.
8189        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8190            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8191                scanFlags |= SCAN_CHECK_ONLY;
8192            }
8193        } else {
8194            scanFlags &= ~SCAN_CHECK_ONLY;
8195        }
8196
8197        final PackageParser.Package scannedPkg;
8198        try {
8199            // Scan the parent
8200            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8201            // Scan the children
8202            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8203            for (int i = 0; i < childCount; i++) {
8204                PackageParser.Package childPkg = pkg.childPackages.get(i);
8205                scanPackageLI(childPkg, policyFlags,
8206                        scanFlags, currentTime, user);
8207            }
8208        } finally {
8209            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8210        }
8211
8212        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8213            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8214        }
8215
8216        return scannedPkg;
8217    }
8218
8219    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8220            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8221        boolean success = false;
8222        try {
8223            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8224                    currentTime, user);
8225            success = true;
8226            return res;
8227        } finally {
8228            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8229                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8230                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8231                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8232                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8233            }
8234        }
8235    }
8236
8237    /**
8238     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8239     */
8240    private static boolean apkHasCode(String fileName) {
8241        StrictJarFile jarFile = null;
8242        try {
8243            jarFile = new StrictJarFile(fileName,
8244                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8245            return jarFile.findEntry("classes.dex") != null;
8246        } catch (IOException ignore) {
8247        } finally {
8248            try {
8249                if (jarFile != null) {
8250                    jarFile.close();
8251                }
8252            } catch (IOException ignore) {}
8253        }
8254        return false;
8255    }
8256
8257    /**
8258     * Enforces code policy for the package. This ensures that if an APK has
8259     * declared hasCode="true" in its manifest that the APK actually contains
8260     * code.
8261     *
8262     * @throws PackageManagerException If bytecode could not be found when it should exist
8263     */
8264    private static void assertCodePolicy(PackageParser.Package pkg)
8265            throws PackageManagerException {
8266        final boolean shouldHaveCode =
8267                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8268        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8269            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8270                    "Package " + pkg.baseCodePath + " code is missing");
8271        }
8272
8273        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8274            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8275                final boolean splitShouldHaveCode =
8276                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8277                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8278                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8279                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8280                }
8281            }
8282        }
8283    }
8284
8285    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8286            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8287                    throws PackageManagerException {
8288        if (DEBUG_PACKAGE_SCANNING) {
8289            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8290                Log.d(TAG, "Scanning package " + pkg.packageName);
8291        }
8292
8293        applyPolicy(pkg, policyFlags);
8294
8295        assertPackageIsValid(pkg, policyFlags, scanFlags);
8296
8297        // Initialize package source and resource directories
8298        final File scanFile = new File(pkg.codePath);
8299        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8300        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8301
8302        SharedUserSetting suid = null;
8303        PackageSetting pkgSetting = null;
8304
8305        // Getting the package setting may have a side-effect, so if we
8306        // are only checking if scan would succeed, stash a copy of the
8307        // old setting to restore at the end.
8308        PackageSetting nonMutatedPs = null;
8309
8310        // We keep references to the derived CPU Abis from settings in oder to reuse
8311        // them in the case where we're not upgrading or booting for the first time.
8312        String primaryCpuAbiFromSettings = null;
8313        String secondaryCpuAbiFromSettings = null;
8314
8315        // writer
8316        synchronized (mPackages) {
8317            if (pkg.mSharedUserId != null) {
8318                // SIDE EFFECTS; may potentially allocate a new shared user
8319                suid = mSettings.getSharedUserLPw(
8320                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8321                if (DEBUG_PACKAGE_SCANNING) {
8322                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8323                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8324                                + "): packages=" + suid.packages);
8325                }
8326            }
8327
8328            // Check if we are renaming from an original package name.
8329            PackageSetting origPackage = null;
8330            String realName = null;
8331            if (pkg.mOriginalPackages != null) {
8332                // This package may need to be renamed to a previously
8333                // installed name.  Let's check on that...
8334                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8335                if (pkg.mOriginalPackages.contains(renamed)) {
8336                    // This package had originally been installed as the
8337                    // original name, and we have already taken care of
8338                    // transitioning to the new one.  Just update the new
8339                    // one to continue using the old name.
8340                    realName = pkg.mRealPackage;
8341                    if (!pkg.packageName.equals(renamed)) {
8342                        // Callers into this function may have already taken
8343                        // care of renaming the package; only do it here if
8344                        // it is not already done.
8345                        pkg.setPackageName(renamed);
8346                    }
8347                } else {
8348                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8349                        if ((origPackage = mSettings.getPackageLPr(
8350                                pkg.mOriginalPackages.get(i))) != null) {
8351                            // We do have the package already installed under its
8352                            // original name...  should we use it?
8353                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8354                                // New package is not compatible with original.
8355                                origPackage = null;
8356                                continue;
8357                            } else if (origPackage.sharedUser != null) {
8358                                // Make sure uid is compatible between packages.
8359                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8360                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8361                                            + " to " + pkg.packageName + ": old uid "
8362                                            + origPackage.sharedUser.name
8363                                            + " differs from " + pkg.mSharedUserId);
8364                                    origPackage = null;
8365                                    continue;
8366                                }
8367                                // TODO: Add case when shared user id is added [b/28144775]
8368                            } else {
8369                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8370                                        + pkg.packageName + " to old name " + origPackage.name);
8371                            }
8372                            break;
8373                        }
8374                    }
8375                }
8376            }
8377
8378            if (mTransferedPackages.contains(pkg.packageName)) {
8379                Slog.w(TAG, "Package " + pkg.packageName
8380                        + " was transferred to another, but its .apk remains");
8381            }
8382
8383            // See comments in nonMutatedPs declaration
8384            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8385                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8386                if (foundPs != null) {
8387                    nonMutatedPs = new PackageSetting(foundPs);
8388                }
8389            }
8390
8391            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
8392                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8393                if (foundPs != null) {
8394                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
8395                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
8396                }
8397            }
8398
8399            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
8400            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
8401                PackageManagerService.reportSettingsProblem(Log.WARN,
8402                        "Package " + pkg.packageName + " shared user changed from "
8403                                + (pkgSetting.sharedUser != null
8404                                        ? pkgSetting.sharedUser.name : "<nothing>")
8405                                + " to "
8406                                + (suid != null ? suid.name : "<nothing>")
8407                                + "; replacing with new");
8408                pkgSetting = null;
8409            }
8410            final PackageSetting oldPkgSetting =
8411                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
8412            final PackageSetting disabledPkgSetting =
8413                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8414            if (pkgSetting == null) {
8415                final String parentPackageName = (pkg.parentPackage != null)
8416                        ? pkg.parentPackage.packageName : null;
8417                // REMOVE SharedUserSetting from method; update in a separate call
8418                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
8419                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
8420                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
8421                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
8422                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
8423                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
8424                        UserManagerService.getInstance());
8425                // SIDE EFFECTS; updates system state; move elsewhere
8426                if (origPackage != null) {
8427                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
8428                }
8429                mSettings.addUserToSettingLPw(pkgSetting);
8430            } else {
8431                // REMOVE SharedUserSetting from method; update in a separate call.
8432                //
8433                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
8434                // secondaryCpuAbi are not known at this point so we always update them
8435                // to null here, only to reset them at a later point.
8436                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
8437                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
8438                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
8439                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
8440                        UserManagerService.getInstance());
8441            }
8442            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
8443            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
8444
8445            // SIDE EFFECTS; modifies system state; move elsewhere
8446            if (pkgSetting.origPackage != null) {
8447                // If we are first transitioning from an original package,
8448                // fix up the new package's name now.  We need to do this after
8449                // looking up the package under its new name, so getPackageLP
8450                // can take care of fiddling things correctly.
8451                pkg.setPackageName(origPackage.name);
8452
8453                // File a report about this.
8454                String msg = "New package " + pkgSetting.realName
8455                        + " renamed to replace old package " + pkgSetting.name;
8456                reportSettingsProblem(Log.WARN, msg);
8457
8458                // Make a note of it.
8459                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8460                    mTransferedPackages.add(origPackage.name);
8461                }
8462
8463                // No longer need to retain this.
8464                pkgSetting.origPackage = null;
8465            }
8466
8467            // SIDE EFFECTS; modifies system state; move elsewhere
8468            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8469                // Make a note of it.
8470                mTransferedPackages.add(pkg.packageName);
8471            }
8472
8473            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8474                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8475            }
8476
8477            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8478                // Check all shared libraries and map to their actual file path.
8479                // We only do this here for apps not on a system dir, because those
8480                // are the only ones that can fail an install due to this.  We
8481                // will take care of the system apps by updating all of their
8482                // library paths after the scan is done.
8483                updateSharedLibrariesLPr(pkg, null);
8484            }
8485
8486            if (mFoundPolicyFile) {
8487                SELinuxMMAC.assignSeinfoValue(pkg);
8488            }
8489
8490            pkg.applicationInfo.uid = pkgSetting.appId;
8491            pkg.mExtras = pkgSetting;
8492            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8493                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8494                    // We just determined the app is signed correctly, so bring
8495                    // over the latest parsed certs.
8496                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8497                } else {
8498                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8499                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8500                                "Package " + pkg.packageName + " upgrade keys do not match the "
8501                                + "previously installed version");
8502                    } else {
8503                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8504                        String msg = "System package " + pkg.packageName
8505                                + " signature changed; retaining data.";
8506                        reportSettingsProblem(Log.WARN, msg);
8507                    }
8508                }
8509            } else {
8510                try {
8511                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
8512                    verifySignaturesLP(pkgSetting, pkg);
8513                    // We just determined the app is signed correctly, so bring
8514                    // over the latest parsed certs.
8515                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8516                } catch (PackageManagerException e) {
8517                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8518                        throw e;
8519                    }
8520                    // The signature has changed, but this package is in the system
8521                    // image...  let's recover!
8522                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8523                    // However...  if this package is part of a shared user, but it
8524                    // doesn't match the signature of the shared user, let's fail.
8525                    // What this means is that you can't change the signatures
8526                    // associated with an overall shared user, which doesn't seem all
8527                    // that unreasonable.
8528                    if (pkgSetting.sharedUser != null) {
8529                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8530                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8531                            throw new PackageManagerException(
8532                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8533                                    "Signature mismatch for shared user: "
8534                                            + pkgSetting.sharedUser);
8535                        }
8536                    }
8537                    // File a report about this.
8538                    String msg = "System package " + pkg.packageName
8539                            + " signature changed; retaining data.";
8540                    reportSettingsProblem(Log.WARN, msg);
8541                }
8542            }
8543
8544            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8545                // This package wants to adopt ownership of permissions from
8546                // another package.
8547                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8548                    final String origName = pkg.mAdoptPermissions.get(i);
8549                    final PackageSetting orig = mSettings.getPackageLPr(origName);
8550                    if (orig != null) {
8551                        if (verifyPackageUpdateLPr(orig, pkg)) {
8552                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8553                                    + pkg.packageName);
8554                            // SIDE EFFECTS; updates permissions system state; move elsewhere
8555                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8556                        }
8557                    }
8558                }
8559            }
8560        }
8561
8562        pkg.applicationInfo.processName = fixProcessName(
8563                pkg.applicationInfo.packageName,
8564                pkg.applicationInfo.processName);
8565
8566        if (pkg != mPlatformPackage) {
8567            // Get all of our default paths setup
8568            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8569        }
8570
8571        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8572
8573        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8574            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8575                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8576                derivePackageAbi(
8577                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
8578                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8579
8580                // Some system apps still use directory structure for native libraries
8581                // in which case we might end up not detecting abi solely based on apk
8582                // structure. Try to detect abi based on directory structure.
8583                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8584                        pkg.applicationInfo.primaryCpuAbi == null) {
8585                    setBundledAppAbisAndRoots(pkg, pkgSetting);
8586                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8587                }
8588            } else {
8589                // This is not a first boot or an upgrade, don't bother deriving the
8590                // ABI during the scan. Instead, trust the value that was stored in the
8591                // package setting.
8592                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
8593                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
8594
8595                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8596
8597                if (DEBUG_ABI_SELECTION) {
8598                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
8599                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
8600                        pkg.applicationInfo.secondaryCpuAbi);
8601                }
8602            }
8603        } else {
8604            if ((scanFlags & SCAN_MOVE) != 0) {
8605                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8606                // but we already have this packages package info in the PackageSetting. We just
8607                // use that and derive the native library path based on the new codepath.
8608                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8609                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8610            }
8611
8612            // Set native library paths again. For moves, the path will be updated based on the
8613            // ABIs we've determined above. For non-moves, the path will be updated based on the
8614            // ABIs we determined during compilation, but the path will depend on the final
8615            // package path (after the rename away from the stage path).
8616            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
8617        }
8618
8619        // This is a special case for the "system" package, where the ABI is
8620        // dictated by the zygote configuration (and init.rc). We should keep track
8621        // of this ABI so that we can deal with "normal" applications that run under
8622        // the same UID correctly.
8623        if (mPlatformPackage == pkg) {
8624            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8625                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8626        }
8627
8628        // If there's a mismatch between the abi-override in the package setting
8629        // and the abiOverride specified for the install. Warn about this because we
8630        // would've already compiled the app without taking the package setting into
8631        // account.
8632        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8633            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8634                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8635                        " for package " + pkg.packageName);
8636            }
8637        }
8638
8639        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8640        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8641        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8642
8643        // Copy the derived override back to the parsed package, so that we can
8644        // update the package settings accordingly.
8645        pkg.cpuAbiOverride = cpuAbiOverride;
8646
8647        if (DEBUG_ABI_SELECTION) {
8648            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8649                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8650                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8651        }
8652
8653        // Push the derived path down into PackageSettings so we know what to
8654        // clean up at uninstall time.
8655        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8656
8657        if (DEBUG_ABI_SELECTION) {
8658            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8659                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8660                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8661        }
8662
8663        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
8664        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8665            // We don't do this here during boot because we can do it all
8666            // at once after scanning all existing packages.
8667            //
8668            // We also do this *before* we perform dexopt on this package, so that
8669            // we can avoid redundant dexopts, and also to make sure we've got the
8670            // code and package path correct.
8671            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
8672        }
8673
8674        if (mFactoryTest && pkg.requestedPermissions.contains(
8675                android.Manifest.permission.FACTORY_TEST)) {
8676            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8677        }
8678
8679        if (isSystemApp(pkg)) {
8680            pkgSetting.isOrphaned = true;
8681        }
8682
8683        // Take care of first install / last update times.
8684        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8685        if (currentTime != 0) {
8686            if (pkgSetting.firstInstallTime == 0) {
8687                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8688            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
8689                pkgSetting.lastUpdateTime = currentTime;
8690            }
8691        } else if (pkgSetting.firstInstallTime == 0) {
8692            // We need *something*.  Take time time stamp of the file.
8693            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8694        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8695            if (scanFileTime != pkgSetting.timeStamp) {
8696                // A package on the system image has changed; consider this
8697                // to be an update.
8698                pkgSetting.lastUpdateTime = scanFileTime;
8699            }
8700        }
8701        pkgSetting.setTimeStamp(scanFileTime);
8702
8703        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8704            if (nonMutatedPs != null) {
8705                synchronized (mPackages) {
8706                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8707                }
8708            }
8709        } else {
8710            // Modify state for the given package setting
8711            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
8712                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
8713        }
8714        return pkg;
8715    }
8716
8717    /**
8718     * Applies policy to the parsed package based upon the given policy flags.
8719     * Ensures the package is in a good state.
8720     * <p>
8721     * Implementation detail: This method must NOT have any side effect. It would
8722     * ideally be static, but, it requires locks to read system state.
8723     */
8724    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
8725        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8726            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8727            if (pkg.applicationInfo.isDirectBootAware()) {
8728                // we're direct boot aware; set for all components
8729                for (PackageParser.Service s : pkg.services) {
8730                    s.info.encryptionAware = s.info.directBootAware = true;
8731                }
8732                for (PackageParser.Provider p : pkg.providers) {
8733                    p.info.encryptionAware = p.info.directBootAware = true;
8734                }
8735                for (PackageParser.Activity a : pkg.activities) {
8736                    a.info.encryptionAware = a.info.directBootAware = true;
8737                }
8738                for (PackageParser.Activity r : pkg.receivers) {
8739                    r.info.encryptionAware = r.info.directBootAware = true;
8740                }
8741            }
8742        } else {
8743            // Only allow system apps to be flagged as core apps.
8744            pkg.coreApp = false;
8745            // clear flags not applicable to regular apps
8746            pkg.applicationInfo.privateFlags &=
8747                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8748            pkg.applicationInfo.privateFlags &=
8749                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8750        }
8751        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8752
8753        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8754            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8755        }
8756
8757        if (!isSystemApp(pkg)) {
8758            // Only system apps can use these features.
8759            pkg.mOriginalPackages = null;
8760            pkg.mRealPackage = null;
8761            pkg.mAdoptPermissions = null;
8762        }
8763    }
8764
8765    /**
8766     * Asserts the parsed package is valid according to teh given policy. If the
8767     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
8768     * <p>
8769     * Implementation detail: This method must NOT have any side effects. It would
8770     * ideally be static, but, it requires locks to read system state.
8771     *
8772     * @throws PackageManagerException If the package fails any of the validation checks
8773     */
8774    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
8775            throws PackageManagerException {
8776        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8777            assertCodePolicy(pkg);
8778        }
8779
8780        if (pkg.applicationInfo.getCodePath() == null ||
8781                pkg.applicationInfo.getResourcePath() == null) {
8782            // Bail out. The resource and code paths haven't been set.
8783            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8784                    "Code and resource paths haven't been set correctly");
8785        }
8786
8787        // Make sure we're not adding any bogus keyset info
8788        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8789        ksms.assertScannedPackageValid(pkg);
8790
8791        synchronized (mPackages) {
8792            // The special "android" package can only be defined once
8793            if (pkg.packageName.equals("android")) {
8794                if (mAndroidApplication != null) {
8795                    Slog.w(TAG, "*************************************************");
8796                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8797                    Slog.w(TAG, " codePath=" + pkg.codePath);
8798                    Slog.w(TAG, "*************************************************");
8799                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8800                            "Core android package being redefined.  Skipping.");
8801                }
8802            }
8803
8804            // A package name must be unique; don't allow duplicates
8805            if (mPackages.containsKey(pkg.packageName)
8806                    || mSharedLibraries.containsKey(pkg.packageName)) {
8807                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8808                        "Application package " + pkg.packageName
8809                        + " already installed.  Skipping duplicate.");
8810            }
8811
8812            // Only privileged apps and updated privileged apps can add child packages.
8813            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8814                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8815                    throw new PackageManagerException("Only privileged apps can add child "
8816                            + "packages. Ignoring package " + pkg.packageName);
8817                }
8818                final int childCount = pkg.childPackages.size();
8819                for (int i = 0; i < childCount; i++) {
8820                    PackageParser.Package childPkg = pkg.childPackages.get(i);
8821                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8822                            childPkg.packageName)) {
8823                        throw new PackageManagerException("Can't override child of "
8824                                + "another disabled app. Ignoring package " + pkg.packageName);
8825                    }
8826                }
8827            }
8828
8829            // If we're only installing presumed-existing packages, require that the
8830            // scanned APK is both already known and at the path previously established
8831            // for it.  Previously unknown packages we pick up normally, but if we have an
8832            // a priori expectation about this package's install presence, enforce it.
8833            // With a singular exception for new system packages. When an OTA contains
8834            // a new system package, we allow the codepath to change from a system location
8835            // to the user-installed location. If we don't allow this change, any newer,
8836            // user-installed version of the application will be ignored.
8837            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8838                if (mExpectingBetter.containsKey(pkg.packageName)) {
8839                    logCriticalInfo(Log.WARN,
8840                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8841                } else {
8842                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
8843                    if (known != null) {
8844                        if (DEBUG_PACKAGE_SCANNING) {
8845                            Log.d(TAG, "Examining " + pkg.codePath
8846                                    + " and requiring known paths " + known.codePathString
8847                                    + " & " + known.resourcePathString);
8848                        }
8849                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8850                                || !pkg.applicationInfo.getResourcePath().equals(
8851                                        known.resourcePathString)) {
8852                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8853                                    "Application package " + pkg.packageName
8854                                    + " found at " + pkg.applicationInfo.getCodePath()
8855                                    + " but expected at " + known.codePathString
8856                                    + "; ignoring.");
8857                        }
8858                    }
8859                }
8860            }
8861
8862            // Verify that this new package doesn't have any content providers
8863            // that conflict with existing packages.  Only do this if the
8864            // package isn't already installed, since we don't want to break
8865            // things that are installed.
8866            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8867                final int N = pkg.providers.size();
8868                int i;
8869                for (i=0; i<N; i++) {
8870                    PackageParser.Provider p = pkg.providers.get(i);
8871                    if (p.info.authority != null) {
8872                        String names[] = p.info.authority.split(";");
8873                        for (int j = 0; j < names.length; j++) {
8874                            if (mProvidersByAuthority.containsKey(names[j])) {
8875                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8876                                final String otherPackageName =
8877                                        ((other != null && other.getComponentName() != null) ?
8878                                                other.getComponentName().getPackageName() : "?");
8879                                throw new PackageManagerException(
8880                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8881                                        "Can't install because provider name " + names[j]
8882                                                + " (in package " + pkg.applicationInfo.packageName
8883                                                + ") is already used by " + otherPackageName);
8884                            }
8885                        }
8886                    }
8887                }
8888            }
8889        }
8890    }
8891
8892    /**
8893     * Adds a scanned package to the system. When this method is finished, the package will
8894     * be available for query, resolution, etc...
8895     */
8896    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
8897            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
8898        final String pkgName = pkg.packageName;
8899        if (mCustomResolverComponentName != null &&
8900                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8901            setUpCustomResolverActivity(pkg);
8902        }
8903
8904        if (pkg.packageName.equals("android")) {
8905            synchronized (mPackages) {
8906                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8907                    // Set up information for our fall-back user intent resolution activity.
8908                    mPlatformPackage = pkg;
8909                    pkg.mVersionCode = mSdkVersion;
8910                    mAndroidApplication = pkg.applicationInfo;
8911
8912                    if (!mResolverReplaced) {
8913                        mResolveActivity.applicationInfo = mAndroidApplication;
8914                        mResolveActivity.name = ResolverActivity.class.getName();
8915                        mResolveActivity.packageName = mAndroidApplication.packageName;
8916                        mResolveActivity.processName = "system:ui";
8917                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8918                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8919                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8920                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8921                        mResolveActivity.exported = true;
8922                        mResolveActivity.enabled = true;
8923                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8924                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8925                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8926                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8927                                | ActivityInfo.CONFIG_ORIENTATION
8928                                | ActivityInfo.CONFIG_KEYBOARD
8929                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8930                        mResolveInfo.activityInfo = mResolveActivity;
8931                        mResolveInfo.priority = 0;
8932                        mResolveInfo.preferredOrder = 0;
8933                        mResolveInfo.match = 0;
8934                        mResolveComponentName = new ComponentName(
8935                                mAndroidApplication.packageName, mResolveActivity.name);
8936                    }
8937                }
8938            }
8939        }
8940
8941        ArrayList<PackageParser.Package> clientLibPkgs = null;
8942        // writer
8943        synchronized (mPackages) {
8944            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8945                // Only system apps can add new shared libraries.
8946                if (pkg.libraryNames != null) {
8947                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8948                        String name = pkg.libraryNames.get(i);
8949                        boolean allowed = false;
8950                        if (pkg.isUpdatedSystemApp()) {
8951                            // New library entries can only be added through the
8952                            // system image.  This is important to get rid of a lot
8953                            // of nasty edge cases: for example if we allowed a non-
8954                            // system update of the app to add a library, then uninstalling
8955                            // the update would make the library go away, and assumptions
8956                            // we made such as through app install filtering would now
8957                            // have allowed apps on the device which aren't compatible
8958                            // with it.  Better to just have the restriction here, be
8959                            // conservative, and create many fewer cases that can negatively
8960                            // impact the user experience.
8961                            final PackageSetting sysPs = mSettings
8962                                    .getDisabledSystemPkgLPr(pkg.packageName);
8963                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8964                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8965                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8966                                        allowed = true;
8967                                        break;
8968                                    }
8969                                }
8970                            }
8971                        } else {
8972                            allowed = true;
8973                        }
8974                        if (allowed) {
8975                            if (!mSharedLibraries.containsKey(name)) {
8976                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8977                            } else if (!name.equals(pkg.packageName)) {
8978                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8979                                        + name + " already exists; skipping");
8980                            }
8981                        } else {
8982                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8983                                    + name + " that is not declared on system image; skipping");
8984                        }
8985                    }
8986                    if ((scanFlags & SCAN_BOOTING) == 0) {
8987                        // If we are not booting, we need to update any applications
8988                        // that are clients of our shared library.  If we are booting,
8989                        // this will all be done once the scan is complete.
8990                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8991                    }
8992                }
8993            }
8994        }
8995
8996        if ((scanFlags & SCAN_BOOTING) != 0) {
8997            // No apps can run during boot scan, so they don't need to be frozen
8998        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8999            // Caller asked to not kill app, so it's probably not frozen
9000        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9001            // Caller asked us to ignore frozen check for some reason; they
9002            // probably didn't know the package name
9003        } else {
9004            // We're doing major surgery on this package, so it better be frozen
9005            // right now to keep it from launching
9006            checkPackageFrozen(pkgName);
9007        }
9008
9009        // Also need to kill any apps that are dependent on the library.
9010        if (clientLibPkgs != null) {
9011            for (int i=0; i<clientLibPkgs.size(); i++) {
9012                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9013                killApplication(clientPkg.applicationInfo.packageName,
9014                        clientPkg.applicationInfo.uid, "update lib");
9015            }
9016        }
9017
9018        // writer
9019        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9020
9021        boolean createIdmapFailed = false;
9022        synchronized (mPackages) {
9023            // We don't expect installation to fail beyond this point
9024
9025            if (pkgSetting.pkg != null) {
9026                // Note that |user| might be null during the initial boot scan. If a codePath
9027                // for an app has changed during a boot scan, it's due to an app update that's
9028                // part of the system partition and marker changes must be applied to all users.
9029                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9030                final int[] userIds = resolveUserIds(userId);
9031                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9032            }
9033
9034            // Add the new setting to mSettings
9035            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9036            // Add the new setting to mPackages
9037            mPackages.put(pkg.applicationInfo.packageName, pkg);
9038            // Make sure we don't accidentally delete its data.
9039            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9040            while (iter.hasNext()) {
9041                PackageCleanItem item = iter.next();
9042                if (pkgName.equals(item.packageName)) {
9043                    iter.remove();
9044                }
9045            }
9046
9047            // Add the package's KeySets to the global KeySetManagerService
9048            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9049            ksms.addScannedPackageLPw(pkg);
9050
9051            int N = pkg.providers.size();
9052            StringBuilder r = null;
9053            int i;
9054            for (i=0; i<N; i++) {
9055                PackageParser.Provider p = pkg.providers.get(i);
9056                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9057                        p.info.processName);
9058                mProviders.addProvider(p);
9059                p.syncable = p.info.isSyncable;
9060                if (p.info.authority != null) {
9061                    String names[] = p.info.authority.split(";");
9062                    p.info.authority = null;
9063                    for (int j = 0; j < names.length; j++) {
9064                        if (j == 1 && p.syncable) {
9065                            // We only want the first authority for a provider to possibly be
9066                            // syncable, so if we already added this provider using a different
9067                            // authority clear the syncable flag. We copy the provider before
9068                            // changing it because the mProviders object contains a reference
9069                            // to a provider that we don't want to change.
9070                            // Only do this for the second authority since the resulting provider
9071                            // object can be the same for all future authorities for this provider.
9072                            p = new PackageParser.Provider(p);
9073                            p.syncable = false;
9074                        }
9075                        if (!mProvidersByAuthority.containsKey(names[j])) {
9076                            mProvidersByAuthority.put(names[j], p);
9077                            if (p.info.authority == null) {
9078                                p.info.authority = names[j];
9079                            } else {
9080                                p.info.authority = p.info.authority + ";" + names[j];
9081                            }
9082                            if (DEBUG_PACKAGE_SCANNING) {
9083                                if (chatty)
9084                                    Log.d(TAG, "Registered content provider: " + names[j]
9085                                            + ", className = " + p.info.name + ", isSyncable = "
9086                                            + p.info.isSyncable);
9087                            }
9088                        } else {
9089                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9090                            Slog.w(TAG, "Skipping provider name " + names[j] +
9091                                    " (in package " + pkg.applicationInfo.packageName +
9092                                    "): name already used by "
9093                                    + ((other != null && other.getComponentName() != null)
9094                                            ? other.getComponentName().getPackageName() : "?"));
9095                        }
9096                    }
9097                }
9098                if (chatty) {
9099                    if (r == null) {
9100                        r = new StringBuilder(256);
9101                    } else {
9102                        r.append(' ');
9103                    }
9104                    r.append(p.info.name);
9105                }
9106            }
9107            if (r != null) {
9108                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9109            }
9110
9111            N = pkg.services.size();
9112            r = null;
9113            for (i=0; i<N; i++) {
9114                PackageParser.Service s = pkg.services.get(i);
9115                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9116                        s.info.processName);
9117                mServices.addService(s);
9118                if (chatty) {
9119                    if (r == null) {
9120                        r = new StringBuilder(256);
9121                    } else {
9122                        r.append(' ');
9123                    }
9124                    r.append(s.info.name);
9125                }
9126            }
9127            if (r != null) {
9128                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9129            }
9130
9131            N = pkg.receivers.size();
9132            r = null;
9133            for (i=0; i<N; i++) {
9134                PackageParser.Activity a = pkg.receivers.get(i);
9135                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9136                        a.info.processName);
9137                mReceivers.addActivity(a, "receiver");
9138                if (chatty) {
9139                    if (r == null) {
9140                        r = new StringBuilder(256);
9141                    } else {
9142                        r.append(' ');
9143                    }
9144                    r.append(a.info.name);
9145                }
9146            }
9147            if (r != null) {
9148                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9149            }
9150
9151            N = pkg.activities.size();
9152            r = null;
9153            for (i=0; i<N; i++) {
9154                PackageParser.Activity a = pkg.activities.get(i);
9155                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9156                        a.info.processName);
9157                mActivities.addActivity(a, "activity");
9158                if (chatty) {
9159                    if (r == null) {
9160                        r = new StringBuilder(256);
9161                    } else {
9162                        r.append(' ');
9163                    }
9164                    r.append(a.info.name);
9165                }
9166            }
9167            if (r != null) {
9168                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9169            }
9170
9171            N = pkg.permissionGroups.size();
9172            r = null;
9173            for (i=0; i<N; i++) {
9174                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9175                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
9176                final String curPackageName = cur == null ? null : cur.info.packageName;
9177                // Dont allow ephemeral apps to define new permission groups.
9178                if (pkg.applicationInfo.isEphemeralApp()) {
9179                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9180                            + pg.info.packageName
9181                            + " ignored: ephemeral apps cannot define new permission groups.");
9182                    continue;
9183                }
9184                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
9185                if (cur == null || isPackageUpdate) {
9186                    mPermissionGroups.put(pg.info.name, pg);
9187                    if (chatty) {
9188                        if (r == null) {
9189                            r = new StringBuilder(256);
9190                        } else {
9191                            r.append(' ');
9192                        }
9193                        if (isPackageUpdate) {
9194                            r.append("UPD:");
9195                        }
9196                        r.append(pg.info.name);
9197                    }
9198                } else {
9199                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
9200                            + pg.info.packageName + " ignored: original from "
9201                            + cur.info.packageName);
9202                    if (chatty) {
9203                        if (r == null) {
9204                            r = new StringBuilder(256);
9205                        } else {
9206                            r.append(' ');
9207                        }
9208                        r.append("DUP:");
9209                        r.append(pg.info.name);
9210                    }
9211                }
9212            }
9213            if (r != null) {
9214                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
9215            }
9216
9217            N = pkg.permissions.size();
9218            r = null;
9219            for (i=0; i<N; i++) {
9220                PackageParser.Permission p = pkg.permissions.get(i);
9221
9222                // Dont allow ephemeral apps to define new permissions.
9223                if (pkg.applicationInfo.isEphemeralApp()) {
9224                    Slog.w(TAG, "Permission " + p.info.name + " from package "
9225                            + p.info.packageName
9226                            + " ignored: ephemeral apps cannot define new permissions.");
9227                    continue;
9228                }
9229
9230                // Assume by default that we did not install this permission into the system.
9231                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
9232
9233                // Now that permission groups have a special meaning, we ignore permission
9234                // groups for legacy apps to prevent unexpected behavior. In particular,
9235                // permissions for one app being granted to someone just becase they happen
9236                // to be in a group defined by another app (before this had no implications).
9237                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
9238                    p.group = mPermissionGroups.get(p.info.group);
9239                    // Warn for a permission in an unknown group.
9240                    if (p.info.group != null && p.group == null) {
9241                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9242                                + p.info.packageName + " in an unknown group " + p.info.group);
9243                    }
9244                }
9245
9246                ArrayMap<String, BasePermission> permissionMap =
9247                        p.tree ? mSettings.mPermissionTrees
9248                                : mSettings.mPermissions;
9249                BasePermission bp = permissionMap.get(p.info.name);
9250
9251                // Allow system apps to redefine non-system permissions
9252                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
9253                    final boolean currentOwnerIsSystem = (bp.perm != null
9254                            && isSystemApp(bp.perm.owner));
9255                    if (isSystemApp(p.owner)) {
9256                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
9257                            // It's a built-in permission and no owner, take ownership now
9258                            bp.packageSetting = pkgSetting;
9259                            bp.perm = p;
9260                            bp.uid = pkg.applicationInfo.uid;
9261                            bp.sourcePackage = p.info.packageName;
9262                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9263                        } else if (!currentOwnerIsSystem) {
9264                            String msg = "New decl " + p.owner + " of permission  "
9265                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
9266                            reportSettingsProblem(Log.WARN, msg);
9267                            bp = null;
9268                        }
9269                    }
9270                }
9271
9272                if (bp == null) {
9273                    bp = new BasePermission(p.info.name, p.info.packageName,
9274                            BasePermission.TYPE_NORMAL);
9275                    permissionMap.put(p.info.name, bp);
9276                }
9277
9278                if (bp.perm == null) {
9279                    if (bp.sourcePackage == null
9280                            || bp.sourcePackage.equals(p.info.packageName)) {
9281                        BasePermission tree = findPermissionTreeLP(p.info.name);
9282                        if (tree == null
9283                                || tree.sourcePackage.equals(p.info.packageName)) {
9284                            bp.packageSetting = pkgSetting;
9285                            bp.perm = p;
9286                            bp.uid = pkg.applicationInfo.uid;
9287                            bp.sourcePackage = p.info.packageName;
9288                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
9289                            if (chatty) {
9290                                if (r == null) {
9291                                    r = new StringBuilder(256);
9292                                } else {
9293                                    r.append(' ');
9294                                }
9295                                r.append(p.info.name);
9296                            }
9297                        } else {
9298                            Slog.w(TAG, "Permission " + p.info.name + " from package "
9299                                    + p.info.packageName + " ignored: base tree "
9300                                    + tree.name + " is from package "
9301                                    + tree.sourcePackage);
9302                        }
9303                    } else {
9304                        Slog.w(TAG, "Permission " + p.info.name + " from package "
9305                                + p.info.packageName + " ignored: original from "
9306                                + bp.sourcePackage);
9307                    }
9308                } else if (chatty) {
9309                    if (r == null) {
9310                        r = new StringBuilder(256);
9311                    } else {
9312                        r.append(' ');
9313                    }
9314                    r.append("DUP:");
9315                    r.append(p.info.name);
9316                }
9317                if (bp.perm == p) {
9318                    bp.protectionLevel = p.info.protectionLevel;
9319                }
9320            }
9321
9322            if (r != null) {
9323                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
9324            }
9325
9326            N = pkg.instrumentation.size();
9327            r = null;
9328            for (i=0; i<N; i++) {
9329                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9330                a.info.packageName = pkg.applicationInfo.packageName;
9331                a.info.sourceDir = pkg.applicationInfo.sourceDir;
9332                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
9333                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
9334                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
9335                a.info.dataDir = pkg.applicationInfo.dataDir;
9336                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
9337                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
9338                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
9339                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
9340                mInstrumentation.put(a.getComponentName(), a);
9341                if (chatty) {
9342                    if (r == null) {
9343                        r = new StringBuilder(256);
9344                    } else {
9345                        r.append(' ');
9346                    }
9347                    r.append(a.info.name);
9348                }
9349            }
9350            if (r != null) {
9351                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
9352            }
9353
9354            if (pkg.protectedBroadcasts != null) {
9355                N = pkg.protectedBroadcasts.size();
9356                for (i=0; i<N; i++) {
9357                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
9358                }
9359            }
9360
9361            // Create idmap files for pairs of (packages, overlay packages).
9362            // Note: "android", ie framework-res.apk, is handled by native layers.
9363            if (pkg.mOverlayTarget != null) {
9364                // This is an overlay package.
9365                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
9366                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
9367                        mOverlays.put(pkg.mOverlayTarget,
9368                                new ArrayMap<String, PackageParser.Package>());
9369                    }
9370                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
9371                    map.put(pkg.packageName, pkg);
9372                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
9373                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
9374                        createIdmapFailed = true;
9375                    }
9376                }
9377            } else if (mOverlays.containsKey(pkg.packageName) &&
9378                    !pkg.packageName.equals("android")) {
9379                // This is a regular package, with one or more known overlay packages.
9380                createIdmapsForPackageLI(pkg);
9381            }
9382        }
9383
9384        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9385
9386        if (createIdmapFailed) {
9387            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9388                    "scanPackageLI failed to createIdmap");
9389        }
9390    }
9391
9392    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9393            PackageParser.Package update, int[] userIds) {
9394        if (existing.applicationInfo == null || update.applicationInfo == null) {
9395            // This isn't due to an app installation.
9396            return;
9397        }
9398
9399        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9400        final File newCodePath = new File(update.applicationInfo.getCodePath());
9401
9402        // The codePath hasn't changed, so there's nothing for us to do.
9403        if (Objects.equals(oldCodePath, newCodePath)) {
9404            return;
9405        }
9406
9407        File canonicalNewCodePath;
9408        try {
9409            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9410        } catch (IOException e) {
9411            Slog.w(TAG, "Failed to get canonical path.", e);
9412            return;
9413        }
9414
9415        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9416        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9417        // that the last component of the path (i.e, the name) doesn't need canonicalization
9418        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9419        // but may change in the future. Hopefully this function won't exist at that point.
9420        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9421                oldCodePath.getName());
9422
9423        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9424        // with "@".
9425        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9426        if (!oldMarkerPrefix.endsWith("@")) {
9427            oldMarkerPrefix += "@";
9428        }
9429        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9430        if (!newMarkerPrefix.endsWith("@")) {
9431            newMarkerPrefix += "@";
9432        }
9433
9434        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9435        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9436        for (String updatedPath : updatedPaths) {
9437            String updatedPathName = new File(updatedPath).getName();
9438            markerSuffixes.add(updatedPathName.replace('/', '@'));
9439        }
9440
9441        for (int userId : userIds) {
9442            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9443
9444            for (String markerSuffix : markerSuffixes) {
9445                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9446                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9447                if (oldForeignUseMark.exists()) {
9448                    try {
9449                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9450                                newForeignUseMark.getAbsolutePath());
9451                    } catch (ErrnoException e) {
9452                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9453                        oldForeignUseMark.delete();
9454                    }
9455                }
9456            }
9457        }
9458    }
9459
9460    /**
9461     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9462     * is derived purely on the basis of the contents of {@code scanFile} and
9463     * {@code cpuAbiOverride}.
9464     *
9465     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9466     */
9467    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9468                                 String cpuAbiOverride, boolean extractLibs,
9469                                 File appLib32InstallDir)
9470            throws PackageManagerException {
9471        // Give ourselves some initial paths; we'll come back for another
9472        // pass once we've determined ABI below.
9473        setNativeLibraryPaths(pkg, appLib32InstallDir);
9474
9475        // We would never need to extract libs for forward-locked and external packages,
9476        // since the container service will do it for us. We shouldn't attempt to
9477        // extract libs from system app when it was not updated.
9478        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9479                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9480            extractLibs = false;
9481        }
9482
9483        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9484        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9485
9486        NativeLibraryHelper.Handle handle = null;
9487        try {
9488            handle = NativeLibraryHelper.Handle.create(pkg);
9489            // TODO(multiArch): This can be null for apps that didn't go through the
9490            // usual installation process. We can calculate it again, like we
9491            // do during install time.
9492            //
9493            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9494            // unnecessary.
9495            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9496
9497            // Null out the abis so that they can be recalculated.
9498            pkg.applicationInfo.primaryCpuAbi = null;
9499            pkg.applicationInfo.secondaryCpuAbi = null;
9500            if (isMultiArch(pkg.applicationInfo)) {
9501                // Warn if we've set an abiOverride for multi-lib packages..
9502                // By definition, we need to copy both 32 and 64 bit libraries for
9503                // such packages.
9504                if (pkg.cpuAbiOverride != null
9505                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9506                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9507                }
9508
9509                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9510                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9511                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9512                    if (extractLibs) {
9513                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9514                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9515                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9516                                useIsaSpecificSubdirs);
9517                    } else {
9518                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9519                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9520                    }
9521                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9522                }
9523
9524                maybeThrowExceptionForMultiArchCopy(
9525                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9526
9527                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9528                    if (extractLibs) {
9529                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9530                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9531                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9532                                useIsaSpecificSubdirs);
9533                    } else {
9534                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9535                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9536                    }
9537                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9538                }
9539
9540                maybeThrowExceptionForMultiArchCopy(
9541                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9542
9543                if (abi64 >= 0) {
9544                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9545                }
9546
9547                if (abi32 >= 0) {
9548                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9549                    if (abi64 >= 0) {
9550                        if (pkg.use32bitAbi) {
9551                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9552                            pkg.applicationInfo.primaryCpuAbi = abi;
9553                        } else {
9554                            pkg.applicationInfo.secondaryCpuAbi = abi;
9555                        }
9556                    } else {
9557                        pkg.applicationInfo.primaryCpuAbi = abi;
9558                    }
9559                }
9560
9561            } else {
9562                String[] abiList = (cpuAbiOverride != null) ?
9563                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9564
9565                // Enable gross and lame hacks for apps that are built with old
9566                // SDK tools. We must scan their APKs for renderscript bitcode and
9567                // not launch them if it's present. Don't bother checking on devices
9568                // that don't have 64 bit support.
9569                boolean needsRenderScriptOverride = false;
9570                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9571                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9572                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9573                    needsRenderScriptOverride = true;
9574                }
9575
9576                final int copyRet;
9577                if (extractLibs) {
9578                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9579                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9580                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9581                } else {
9582                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9583                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9584                }
9585                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9586
9587                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9588                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9589                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9590                }
9591
9592                if (copyRet >= 0) {
9593                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9594                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9595                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9596                } else if (needsRenderScriptOverride) {
9597                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9598                }
9599            }
9600        } catch (IOException ioe) {
9601            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9602        } finally {
9603            IoUtils.closeQuietly(handle);
9604        }
9605
9606        // Now that we've calculated the ABIs and determined if it's an internal app,
9607        // we will go ahead and populate the nativeLibraryPath.
9608        setNativeLibraryPaths(pkg, appLib32InstallDir);
9609    }
9610
9611    /**
9612     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9613     * i.e, so that all packages can be run inside a single process if required.
9614     *
9615     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9616     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9617     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9618     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9619     * updating a package that belongs to a shared user.
9620     *
9621     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9622     * adds unnecessary complexity.
9623     */
9624    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9625            PackageParser.Package scannedPackage) {
9626        String requiredInstructionSet = null;
9627        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9628            requiredInstructionSet = VMRuntime.getInstructionSet(
9629                     scannedPackage.applicationInfo.primaryCpuAbi);
9630        }
9631
9632        PackageSetting requirer = null;
9633        for (PackageSetting ps : packagesForUser) {
9634            // If packagesForUser contains scannedPackage, we skip it. This will happen
9635            // when scannedPackage is an update of an existing package. Without this check,
9636            // we will never be able to change the ABI of any package belonging to a shared
9637            // user, even if it's compatible with other packages.
9638            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9639                if (ps.primaryCpuAbiString == null) {
9640                    continue;
9641                }
9642
9643                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9644                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9645                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9646                    // this but there's not much we can do.
9647                    String errorMessage = "Instruction set mismatch, "
9648                            + ((requirer == null) ? "[caller]" : requirer)
9649                            + " requires " + requiredInstructionSet + " whereas " + ps
9650                            + " requires " + instructionSet;
9651                    Slog.w(TAG, errorMessage);
9652                }
9653
9654                if (requiredInstructionSet == null) {
9655                    requiredInstructionSet = instructionSet;
9656                    requirer = ps;
9657                }
9658            }
9659        }
9660
9661        if (requiredInstructionSet != null) {
9662            String adjustedAbi;
9663            if (requirer != null) {
9664                // requirer != null implies that either scannedPackage was null or that scannedPackage
9665                // did not require an ABI, in which case we have to adjust scannedPackage to match
9666                // the ABI of the set (which is the same as requirer's ABI)
9667                adjustedAbi = requirer.primaryCpuAbiString;
9668                if (scannedPackage != null) {
9669                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9670                }
9671            } else {
9672                // requirer == null implies that we're updating all ABIs in the set to
9673                // match scannedPackage.
9674                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9675            }
9676
9677            for (PackageSetting ps : packagesForUser) {
9678                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9679                    if (ps.primaryCpuAbiString != null) {
9680                        continue;
9681                    }
9682
9683                    ps.primaryCpuAbiString = adjustedAbi;
9684                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9685                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9686                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9687                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9688                                + " (requirer="
9689                                + (requirer == null ? "null" : requirer.pkg.packageName)
9690                                + ", scannedPackage="
9691                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9692                                + ")");
9693                        try {
9694                            mInstaller.rmdex(ps.codePathString,
9695                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9696                        } catch (InstallerException ignored) {
9697                        }
9698                    }
9699                }
9700            }
9701        }
9702    }
9703
9704    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9705        synchronized (mPackages) {
9706            mResolverReplaced = true;
9707            // Set up information for custom user intent resolution activity.
9708            mResolveActivity.applicationInfo = pkg.applicationInfo;
9709            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9710            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9711            mResolveActivity.processName = pkg.applicationInfo.packageName;
9712            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9713            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9714                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9715            mResolveActivity.theme = 0;
9716            mResolveActivity.exported = true;
9717            mResolveActivity.enabled = true;
9718            mResolveInfo.activityInfo = mResolveActivity;
9719            mResolveInfo.priority = 0;
9720            mResolveInfo.preferredOrder = 0;
9721            mResolveInfo.match = 0;
9722            mResolveComponentName = mCustomResolverComponentName;
9723            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9724                    mResolveComponentName);
9725        }
9726    }
9727
9728    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9729        if (installerComponent == null) {
9730            if (DEBUG_EPHEMERAL) {
9731                Slog.d(TAG, "Clear ephemeral installer activity");
9732            }
9733            mEphemeralInstallerActivity.applicationInfo = null;
9734            return;
9735        }
9736
9737        if (DEBUG_EPHEMERAL) {
9738            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
9739        }
9740        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9741        // Set up information for ephemeral installer activity
9742        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9743        mEphemeralInstallerActivity.name = installerComponent.getClassName();
9744        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9745        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9746        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9747        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9748                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9749        mEphemeralInstallerActivity.theme = 0;
9750        mEphemeralInstallerActivity.exported = true;
9751        mEphemeralInstallerActivity.enabled = true;
9752        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9753        mEphemeralInstallerInfo.priority = 0;
9754        mEphemeralInstallerInfo.preferredOrder = 1;
9755        mEphemeralInstallerInfo.isDefault = true;
9756        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9757                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9758    }
9759
9760    private static String calculateBundledApkRoot(final String codePathString) {
9761        final File codePath = new File(codePathString);
9762        final File codeRoot;
9763        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9764            codeRoot = Environment.getRootDirectory();
9765        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9766            codeRoot = Environment.getOemDirectory();
9767        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9768            codeRoot = Environment.getVendorDirectory();
9769        } else {
9770            // Unrecognized code path; take its top real segment as the apk root:
9771            // e.g. /something/app/blah.apk => /something
9772            try {
9773                File f = codePath.getCanonicalFile();
9774                File parent = f.getParentFile();    // non-null because codePath is a file
9775                File tmp;
9776                while ((tmp = parent.getParentFile()) != null) {
9777                    f = parent;
9778                    parent = tmp;
9779                }
9780                codeRoot = f;
9781                Slog.w(TAG, "Unrecognized code path "
9782                        + codePath + " - using " + codeRoot);
9783            } catch (IOException e) {
9784                // Can't canonicalize the code path -- shenanigans?
9785                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9786                return Environment.getRootDirectory().getPath();
9787            }
9788        }
9789        return codeRoot.getPath();
9790    }
9791
9792    /**
9793     * Derive and set the location of native libraries for the given package,
9794     * which varies depending on where and how the package was installed.
9795     */
9796    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
9797        final ApplicationInfo info = pkg.applicationInfo;
9798        final String codePath = pkg.codePath;
9799        final File codeFile = new File(codePath);
9800        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9801        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9802
9803        info.nativeLibraryRootDir = null;
9804        info.nativeLibraryRootRequiresIsa = false;
9805        info.nativeLibraryDir = null;
9806        info.secondaryNativeLibraryDir = null;
9807
9808        if (isApkFile(codeFile)) {
9809            // Monolithic install
9810            if (bundledApp) {
9811                // If "/system/lib64/apkname" exists, assume that is the per-package
9812                // native library directory to use; otherwise use "/system/lib/apkname".
9813                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9814                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9815                        getPrimaryInstructionSet(info));
9816
9817                // This is a bundled system app so choose the path based on the ABI.
9818                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9819                // is just the default path.
9820                final String apkName = deriveCodePathName(codePath);
9821                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9822                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9823                        apkName).getAbsolutePath();
9824
9825                if (info.secondaryCpuAbi != null) {
9826                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9827                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9828                            secondaryLibDir, apkName).getAbsolutePath();
9829                }
9830            } else if (asecApp) {
9831                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9832                        .getAbsolutePath();
9833            } else {
9834                final String apkName = deriveCodePathName(codePath);
9835                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
9836                        .getAbsolutePath();
9837            }
9838
9839            info.nativeLibraryRootRequiresIsa = false;
9840            info.nativeLibraryDir = info.nativeLibraryRootDir;
9841        } else {
9842            // Cluster install
9843            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9844            info.nativeLibraryRootRequiresIsa = true;
9845
9846            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9847                    getPrimaryInstructionSet(info)).getAbsolutePath();
9848
9849            if (info.secondaryCpuAbi != null) {
9850                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9851                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9852            }
9853        }
9854    }
9855
9856    /**
9857     * Calculate the abis and roots for a bundled app. These can uniquely
9858     * be determined from the contents of the system partition, i.e whether
9859     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9860     * of this information, and instead assume that the system was built
9861     * sensibly.
9862     */
9863    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9864                                           PackageSetting pkgSetting) {
9865        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9866
9867        // If "/system/lib64/apkname" exists, assume that is the per-package
9868        // native library directory to use; otherwise use "/system/lib/apkname".
9869        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9870        setBundledAppAbi(pkg, apkRoot, apkName);
9871        // pkgSetting might be null during rescan following uninstall of updates
9872        // to a bundled app, so accommodate that possibility.  The settings in
9873        // that case will be established later from the parsed package.
9874        //
9875        // If the settings aren't null, sync them up with what we've just derived.
9876        // note that apkRoot isn't stored in the package settings.
9877        if (pkgSetting != null) {
9878            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9879            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9880        }
9881    }
9882
9883    /**
9884     * Deduces the ABI of a bundled app and sets the relevant fields on the
9885     * parsed pkg object.
9886     *
9887     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9888     *        under which system libraries are installed.
9889     * @param apkName the name of the installed package.
9890     */
9891    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9892        final File codeFile = new File(pkg.codePath);
9893
9894        final boolean has64BitLibs;
9895        final boolean has32BitLibs;
9896        if (isApkFile(codeFile)) {
9897            // Monolithic install
9898            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9899            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9900        } else {
9901            // Cluster install
9902            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9903            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9904                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9905                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9906                has64BitLibs = (new File(rootDir, isa)).exists();
9907            } else {
9908                has64BitLibs = false;
9909            }
9910            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9911                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9912                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9913                has32BitLibs = (new File(rootDir, isa)).exists();
9914            } else {
9915                has32BitLibs = false;
9916            }
9917        }
9918
9919        if (has64BitLibs && !has32BitLibs) {
9920            // The package has 64 bit libs, but not 32 bit libs. Its primary
9921            // ABI should be 64 bit. We can safely assume here that the bundled
9922            // native libraries correspond to the most preferred ABI in the list.
9923
9924            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9925            pkg.applicationInfo.secondaryCpuAbi = null;
9926        } else if (has32BitLibs && !has64BitLibs) {
9927            // The package has 32 bit libs but not 64 bit libs. Its primary
9928            // ABI should be 32 bit.
9929
9930            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9931            pkg.applicationInfo.secondaryCpuAbi = null;
9932        } else if (has32BitLibs && has64BitLibs) {
9933            // The application has both 64 and 32 bit bundled libraries. We check
9934            // here that the app declares multiArch support, and warn if it doesn't.
9935            //
9936            // We will be lenient here and record both ABIs. The primary will be the
9937            // ABI that's higher on the list, i.e, a device that's configured to prefer
9938            // 64 bit apps will see a 64 bit primary ABI,
9939
9940            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9941                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9942            }
9943
9944            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9945                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9946                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9947            } else {
9948                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9949                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9950            }
9951        } else {
9952            pkg.applicationInfo.primaryCpuAbi = null;
9953            pkg.applicationInfo.secondaryCpuAbi = null;
9954        }
9955    }
9956
9957    private void killApplication(String pkgName, int appId, String reason) {
9958        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9959    }
9960
9961    private void killApplication(String pkgName, int appId, int userId, String reason) {
9962        // Request the ActivityManager to kill the process(only for existing packages)
9963        // so that we do not end up in a confused state while the user is still using the older
9964        // version of the application while the new one gets installed.
9965        final long token = Binder.clearCallingIdentity();
9966        try {
9967            IActivityManager am = ActivityManager.getService();
9968            if (am != null) {
9969                try {
9970                    am.killApplication(pkgName, appId, userId, reason);
9971                } catch (RemoteException e) {
9972                }
9973            }
9974        } finally {
9975            Binder.restoreCallingIdentity(token);
9976        }
9977    }
9978
9979    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9980        // Remove the parent package setting
9981        PackageSetting ps = (PackageSetting) pkg.mExtras;
9982        if (ps != null) {
9983            removePackageLI(ps, chatty);
9984        }
9985        // Remove the child package setting
9986        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9987        for (int i = 0; i < childCount; i++) {
9988            PackageParser.Package childPkg = pkg.childPackages.get(i);
9989            ps = (PackageSetting) childPkg.mExtras;
9990            if (ps != null) {
9991                removePackageLI(ps, chatty);
9992            }
9993        }
9994    }
9995
9996    void removePackageLI(PackageSetting ps, boolean chatty) {
9997        if (DEBUG_INSTALL) {
9998            if (chatty)
9999                Log.d(TAG, "Removing package " + ps.name);
10000        }
10001
10002        // writer
10003        synchronized (mPackages) {
10004            mPackages.remove(ps.name);
10005            final PackageParser.Package pkg = ps.pkg;
10006            if (pkg != null) {
10007                cleanPackageDataStructuresLILPw(pkg, chatty);
10008            }
10009        }
10010    }
10011
10012    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10013        if (DEBUG_INSTALL) {
10014            if (chatty)
10015                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10016        }
10017
10018        // writer
10019        synchronized (mPackages) {
10020            // Remove the parent package
10021            mPackages.remove(pkg.applicationInfo.packageName);
10022            cleanPackageDataStructuresLILPw(pkg, chatty);
10023
10024            // Remove the child packages
10025            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10026            for (int i = 0; i < childCount; i++) {
10027                PackageParser.Package childPkg = pkg.childPackages.get(i);
10028                mPackages.remove(childPkg.applicationInfo.packageName);
10029                cleanPackageDataStructuresLILPw(childPkg, chatty);
10030            }
10031        }
10032    }
10033
10034    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10035        int N = pkg.providers.size();
10036        StringBuilder r = null;
10037        int i;
10038        for (i=0; i<N; i++) {
10039            PackageParser.Provider p = pkg.providers.get(i);
10040            mProviders.removeProvider(p);
10041            if (p.info.authority == null) {
10042
10043                /* There was another ContentProvider with this authority when
10044                 * this app was installed so this authority is null,
10045                 * Ignore it as we don't have to unregister the provider.
10046                 */
10047                continue;
10048            }
10049            String names[] = p.info.authority.split(";");
10050            for (int j = 0; j < names.length; j++) {
10051                if (mProvidersByAuthority.get(names[j]) == p) {
10052                    mProvidersByAuthority.remove(names[j]);
10053                    if (DEBUG_REMOVE) {
10054                        if (chatty)
10055                            Log.d(TAG, "Unregistered content provider: " + names[j]
10056                                    + ", className = " + p.info.name + ", isSyncable = "
10057                                    + p.info.isSyncable);
10058                    }
10059                }
10060            }
10061            if (DEBUG_REMOVE && chatty) {
10062                if (r == null) {
10063                    r = new StringBuilder(256);
10064                } else {
10065                    r.append(' ');
10066                }
10067                r.append(p.info.name);
10068            }
10069        }
10070        if (r != null) {
10071            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10072        }
10073
10074        N = pkg.services.size();
10075        r = null;
10076        for (i=0; i<N; i++) {
10077            PackageParser.Service s = pkg.services.get(i);
10078            mServices.removeService(s);
10079            if (chatty) {
10080                if (r == null) {
10081                    r = new StringBuilder(256);
10082                } else {
10083                    r.append(' ');
10084                }
10085                r.append(s.info.name);
10086            }
10087        }
10088        if (r != null) {
10089            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10090        }
10091
10092        N = pkg.receivers.size();
10093        r = null;
10094        for (i=0; i<N; i++) {
10095            PackageParser.Activity a = pkg.receivers.get(i);
10096            mReceivers.removeActivity(a, "receiver");
10097            if (DEBUG_REMOVE && chatty) {
10098                if (r == null) {
10099                    r = new StringBuilder(256);
10100                } else {
10101                    r.append(' ');
10102                }
10103                r.append(a.info.name);
10104            }
10105        }
10106        if (r != null) {
10107            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10108        }
10109
10110        N = pkg.activities.size();
10111        r = null;
10112        for (i=0; i<N; i++) {
10113            PackageParser.Activity a = pkg.activities.get(i);
10114            mActivities.removeActivity(a, "activity");
10115            if (DEBUG_REMOVE && chatty) {
10116                if (r == null) {
10117                    r = new StringBuilder(256);
10118                } else {
10119                    r.append(' ');
10120                }
10121                r.append(a.info.name);
10122            }
10123        }
10124        if (r != null) {
10125            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10126        }
10127
10128        N = pkg.permissions.size();
10129        r = null;
10130        for (i=0; i<N; i++) {
10131            PackageParser.Permission p = pkg.permissions.get(i);
10132            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10133            if (bp == null) {
10134                bp = mSettings.mPermissionTrees.get(p.info.name);
10135            }
10136            if (bp != null && bp.perm == p) {
10137                bp.perm = null;
10138                if (DEBUG_REMOVE && chatty) {
10139                    if (r == null) {
10140                        r = new StringBuilder(256);
10141                    } else {
10142                        r.append(' ');
10143                    }
10144                    r.append(p.info.name);
10145                }
10146            }
10147            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10148                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10149                if (appOpPkgs != null) {
10150                    appOpPkgs.remove(pkg.packageName);
10151                }
10152            }
10153        }
10154        if (r != null) {
10155            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10156        }
10157
10158        N = pkg.requestedPermissions.size();
10159        r = null;
10160        for (i=0; i<N; i++) {
10161            String perm = pkg.requestedPermissions.get(i);
10162            BasePermission bp = mSettings.mPermissions.get(perm);
10163            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10164                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10165                if (appOpPkgs != null) {
10166                    appOpPkgs.remove(pkg.packageName);
10167                    if (appOpPkgs.isEmpty()) {
10168                        mAppOpPermissionPackages.remove(perm);
10169                    }
10170                }
10171            }
10172        }
10173        if (r != null) {
10174            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10175        }
10176
10177        N = pkg.instrumentation.size();
10178        r = null;
10179        for (i=0; i<N; i++) {
10180            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10181            mInstrumentation.remove(a.getComponentName());
10182            if (DEBUG_REMOVE && chatty) {
10183                if (r == null) {
10184                    r = new StringBuilder(256);
10185                } else {
10186                    r.append(' ');
10187                }
10188                r.append(a.info.name);
10189            }
10190        }
10191        if (r != null) {
10192            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
10193        }
10194
10195        r = null;
10196        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10197            // Only system apps can hold shared libraries.
10198            if (pkg.libraryNames != null) {
10199                for (i=0; i<pkg.libraryNames.size(); i++) {
10200                    String name = pkg.libraryNames.get(i);
10201                    SharedLibraryEntry cur = mSharedLibraries.get(name);
10202                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
10203                        mSharedLibraries.remove(name);
10204                        if (DEBUG_REMOVE && chatty) {
10205                            if (r == null) {
10206                                r = new StringBuilder(256);
10207                            } else {
10208                                r.append(' ');
10209                            }
10210                            r.append(name);
10211                        }
10212                    }
10213                }
10214            }
10215        }
10216        if (r != null) {
10217            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
10218        }
10219    }
10220
10221    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
10222        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
10223            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
10224                return true;
10225            }
10226        }
10227        return false;
10228    }
10229
10230    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
10231    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
10232    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
10233
10234    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
10235        // Update the parent permissions
10236        updatePermissionsLPw(pkg.packageName, pkg, flags);
10237        // Update the child permissions
10238        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10239        for (int i = 0; i < childCount; i++) {
10240            PackageParser.Package childPkg = pkg.childPackages.get(i);
10241            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
10242        }
10243    }
10244
10245    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
10246            int flags) {
10247        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
10248        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
10249    }
10250
10251    private void updatePermissionsLPw(String changingPkg,
10252            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
10253        // Make sure there are no dangling permission trees.
10254        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
10255        while (it.hasNext()) {
10256            final BasePermission bp = it.next();
10257            if (bp.packageSetting == null) {
10258                // We may not yet have parsed the package, so just see if
10259                // we still know about its settings.
10260                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10261            }
10262            if (bp.packageSetting == null) {
10263                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
10264                        + " from package " + bp.sourcePackage);
10265                it.remove();
10266            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10267                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10268                    Slog.i(TAG, "Removing old permission tree: " + bp.name
10269                            + " from package " + bp.sourcePackage);
10270                    flags |= UPDATE_PERMISSIONS_ALL;
10271                    it.remove();
10272                }
10273            }
10274        }
10275
10276        // Make sure all dynamic permissions have been assigned to a package,
10277        // and make sure there are no dangling permissions.
10278        it = mSettings.mPermissions.values().iterator();
10279        while (it.hasNext()) {
10280            final BasePermission bp = it.next();
10281            if (bp.type == BasePermission.TYPE_DYNAMIC) {
10282                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
10283                        + bp.name + " pkg=" + bp.sourcePackage
10284                        + " info=" + bp.pendingInfo);
10285                if (bp.packageSetting == null && bp.pendingInfo != null) {
10286                    final BasePermission tree = findPermissionTreeLP(bp.name);
10287                    if (tree != null && tree.perm != null) {
10288                        bp.packageSetting = tree.packageSetting;
10289                        bp.perm = new PackageParser.Permission(tree.perm.owner,
10290                                new PermissionInfo(bp.pendingInfo));
10291                        bp.perm.info.packageName = tree.perm.info.packageName;
10292                        bp.perm.info.name = bp.name;
10293                        bp.uid = tree.uid;
10294                    }
10295                }
10296            }
10297            if (bp.packageSetting == null) {
10298                // We may not yet have parsed the package, so just see if
10299                // we still know about its settings.
10300                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
10301            }
10302            if (bp.packageSetting == null) {
10303                Slog.w(TAG, "Removing dangling permission: " + bp.name
10304                        + " from package " + bp.sourcePackage);
10305                it.remove();
10306            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
10307                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
10308                    Slog.i(TAG, "Removing old permission: " + bp.name
10309                            + " from package " + bp.sourcePackage);
10310                    flags |= UPDATE_PERMISSIONS_ALL;
10311                    it.remove();
10312                }
10313            }
10314        }
10315
10316        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
10317        // Now update the permissions for all packages, in particular
10318        // replace the granted permissions of the system packages.
10319        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
10320            for (PackageParser.Package pkg : mPackages.values()) {
10321                if (pkg != pkgInfo) {
10322                    // Only replace for packages on requested volume
10323                    final String volumeUuid = getVolumeUuidForPackage(pkg);
10324                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
10325                            && Objects.equals(replaceVolumeUuid, volumeUuid);
10326                    grantPermissionsLPw(pkg, replace, changingPkg);
10327                }
10328            }
10329        }
10330
10331        if (pkgInfo != null) {
10332            // Only replace for packages on requested volume
10333            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
10334            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
10335                    && Objects.equals(replaceVolumeUuid, volumeUuid);
10336            grantPermissionsLPw(pkgInfo, replace, changingPkg);
10337        }
10338        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10339    }
10340
10341    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
10342            String packageOfInterest) {
10343        // IMPORTANT: There are two types of permissions: install and runtime.
10344        // Install time permissions are granted when the app is installed to
10345        // all device users and users added in the future. Runtime permissions
10346        // are granted at runtime explicitly to specific users. Normal and signature
10347        // protected permissions are install time permissions. Dangerous permissions
10348        // are install permissions if the app's target SDK is Lollipop MR1 or older,
10349        // otherwise they are runtime permissions. This function does not manage
10350        // runtime permissions except for the case an app targeting Lollipop MR1
10351        // being upgraded to target a newer SDK, in which case dangerous permissions
10352        // are transformed from install time to runtime ones.
10353
10354        final PackageSetting ps = (PackageSetting) pkg.mExtras;
10355        if (ps == null) {
10356            return;
10357        }
10358
10359        PermissionsState permissionsState = ps.getPermissionsState();
10360        PermissionsState origPermissions = permissionsState;
10361
10362        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
10363
10364        boolean runtimePermissionsRevoked = false;
10365        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
10366
10367        boolean changedInstallPermission = false;
10368
10369        if (replace) {
10370            ps.installPermissionsFixed = false;
10371            if (!ps.isSharedUser()) {
10372                origPermissions = new PermissionsState(permissionsState);
10373                permissionsState.reset();
10374            } else {
10375                // We need to know only about runtime permission changes since the
10376                // calling code always writes the install permissions state but
10377                // the runtime ones are written only if changed. The only cases of
10378                // changed runtime permissions here are promotion of an install to
10379                // runtime and revocation of a runtime from a shared user.
10380                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
10381                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
10382                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
10383                    runtimePermissionsRevoked = true;
10384                }
10385            }
10386        }
10387
10388        permissionsState.setGlobalGids(mGlobalGids);
10389
10390        final int N = pkg.requestedPermissions.size();
10391        for (int i=0; i<N; i++) {
10392            final String name = pkg.requestedPermissions.get(i);
10393            final BasePermission bp = mSettings.mPermissions.get(name);
10394
10395            if (DEBUG_INSTALL) {
10396                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10397            }
10398
10399            if (bp == null || bp.packageSetting == null) {
10400                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10401                    Slog.w(TAG, "Unknown permission " + name
10402                            + " in package " + pkg.packageName);
10403                }
10404                continue;
10405            }
10406
10407
10408            // Limit ephemeral apps to ephemeral allowed permissions.
10409            if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) {
10410                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
10411                        + pkg.packageName);
10412                continue;
10413            }
10414
10415            final String perm = bp.name;
10416            boolean allowedSig = false;
10417            int grant = GRANT_DENIED;
10418
10419            // Keep track of app op permissions.
10420            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10421                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10422                if (pkgs == null) {
10423                    pkgs = new ArraySet<>();
10424                    mAppOpPermissionPackages.put(bp.name, pkgs);
10425                }
10426                pkgs.add(pkg.packageName);
10427            }
10428
10429            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10430            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10431                    >= Build.VERSION_CODES.M;
10432            switch (level) {
10433                case PermissionInfo.PROTECTION_NORMAL: {
10434                    // For all apps normal permissions are install time ones.
10435                    grant = GRANT_INSTALL;
10436                } break;
10437
10438                case PermissionInfo.PROTECTION_DANGEROUS: {
10439                    // If a permission review is required for legacy apps we represent
10440                    // their permissions as always granted runtime ones since we need
10441                    // to keep the review required permission flag per user while an
10442                    // install permission's state is shared across all users.
10443                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
10444                        // For legacy apps dangerous permissions are install time ones.
10445                        grant = GRANT_INSTALL;
10446                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10447                        // For legacy apps that became modern, install becomes runtime.
10448                        grant = GRANT_UPGRADE;
10449                    } else if (mPromoteSystemApps
10450                            && isSystemApp(ps)
10451                            && mExistingSystemPackages.contains(ps.name)) {
10452                        // For legacy system apps, install becomes runtime.
10453                        // We cannot check hasInstallPermission() for system apps since those
10454                        // permissions were granted implicitly and not persisted pre-M.
10455                        grant = GRANT_UPGRADE;
10456                    } else {
10457                        // For modern apps keep runtime permissions unchanged.
10458                        grant = GRANT_RUNTIME;
10459                    }
10460                } break;
10461
10462                case PermissionInfo.PROTECTION_SIGNATURE: {
10463                    // For all apps signature permissions are install time ones.
10464                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10465                    if (allowedSig) {
10466                        grant = GRANT_INSTALL;
10467                    }
10468                } break;
10469            }
10470
10471            if (DEBUG_INSTALL) {
10472                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10473            }
10474
10475            if (grant != GRANT_DENIED) {
10476                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10477                    // If this is an existing, non-system package, then
10478                    // we can't add any new permissions to it.
10479                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10480                        // Except...  if this is a permission that was added
10481                        // to the platform (note: need to only do this when
10482                        // updating the platform).
10483                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10484                            grant = GRANT_DENIED;
10485                        }
10486                    }
10487                }
10488
10489                switch (grant) {
10490                    case GRANT_INSTALL: {
10491                        // Revoke this as runtime permission to handle the case of
10492                        // a runtime permission being downgraded to an install one.
10493                        // Also in permission review mode we keep dangerous permissions
10494                        // for legacy apps
10495                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10496                            if (origPermissions.getRuntimePermissionState(
10497                                    bp.name, userId) != null) {
10498                                // Revoke the runtime permission and clear the flags.
10499                                origPermissions.revokeRuntimePermission(bp, userId);
10500                                origPermissions.updatePermissionFlags(bp, userId,
10501                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10502                                // If we revoked a permission permission, we have to write.
10503                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10504                                        changedRuntimePermissionUserIds, userId);
10505                            }
10506                        }
10507                        // Grant an install permission.
10508                        if (permissionsState.grantInstallPermission(bp) !=
10509                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10510                            changedInstallPermission = true;
10511                        }
10512                    } break;
10513
10514                    case GRANT_RUNTIME: {
10515                        // Grant previously granted runtime permissions.
10516                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10517                            PermissionState permissionState = origPermissions
10518                                    .getRuntimePermissionState(bp.name, userId);
10519                            int flags = permissionState != null
10520                                    ? permissionState.getFlags() : 0;
10521                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10522                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10523                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10524                                    // If we cannot put the permission as it was, we have to write.
10525                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10526                                            changedRuntimePermissionUserIds, userId);
10527                                }
10528                                // If the app supports runtime permissions no need for a review.
10529                                if (mPermissionReviewRequired
10530                                        && appSupportsRuntimePermissions
10531                                        && (flags & PackageManager
10532                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10533                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10534                                    // Since we changed the flags, we have to write.
10535                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10536                                            changedRuntimePermissionUserIds, userId);
10537                                }
10538                            } else if (mPermissionReviewRequired
10539                                    && !appSupportsRuntimePermissions) {
10540                                // For legacy apps that need a permission review, every new
10541                                // runtime permission is granted but it is pending a review.
10542                                // We also need to review only platform defined runtime
10543                                // permissions as these are the only ones the platform knows
10544                                // how to disable the API to simulate revocation as legacy
10545                                // apps don't expect to run with revoked permissions.
10546                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10547                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10548                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10549                                        // We changed the flags, hence have to write.
10550                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10551                                                changedRuntimePermissionUserIds, userId);
10552                                    }
10553                                }
10554                                if (permissionsState.grantRuntimePermission(bp, userId)
10555                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10556                                    // We changed the permission, hence have to write.
10557                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10558                                            changedRuntimePermissionUserIds, userId);
10559                                }
10560                            }
10561                            // Propagate the permission flags.
10562                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10563                        }
10564                    } break;
10565
10566                    case GRANT_UPGRADE: {
10567                        // Grant runtime permissions for a previously held install permission.
10568                        PermissionState permissionState = origPermissions
10569                                .getInstallPermissionState(bp.name);
10570                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10571
10572                        if (origPermissions.revokeInstallPermission(bp)
10573                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10574                            // We will be transferring the permission flags, so clear them.
10575                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10576                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10577                            changedInstallPermission = true;
10578                        }
10579
10580                        // If the permission is not to be promoted to runtime we ignore it and
10581                        // also its other flags as they are not applicable to install permissions.
10582                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10583                            for (int userId : currentUserIds) {
10584                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10585                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10586                                    // Transfer the permission flags.
10587                                    permissionsState.updatePermissionFlags(bp, userId,
10588                                            flags, flags);
10589                                    // If we granted the permission, we have to write.
10590                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10591                                            changedRuntimePermissionUserIds, userId);
10592                                }
10593                            }
10594                        }
10595                    } break;
10596
10597                    default: {
10598                        if (packageOfInterest == null
10599                                || packageOfInterest.equals(pkg.packageName)) {
10600                            Slog.w(TAG, "Not granting permission " + perm
10601                                    + " to package " + pkg.packageName
10602                                    + " because it was previously installed without");
10603                        }
10604                    } break;
10605                }
10606            } else {
10607                if (permissionsState.revokeInstallPermission(bp) !=
10608                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10609                    // Also drop the permission flags.
10610                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10611                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10612                    changedInstallPermission = true;
10613                    Slog.i(TAG, "Un-granting permission " + perm
10614                            + " from package " + pkg.packageName
10615                            + " (protectionLevel=" + bp.protectionLevel
10616                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10617                            + ")");
10618                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10619                    // Don't print warning for app op permissions, since it is fine for them
10620                    // not to be granted, there is a UI for the user to decide.
10621                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10622                        Slog.w(TAG, "Not granting permission " + perm
10623                                + " to package " + pkg.packageName
10624                                + " (protectionLevel=" + bp.protectionLevel
10625                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10626                                + ")");
10627                    }
10628                }
10629            }
10630        }
10631
10632        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10633                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10634            // This is the first that we have heard about this package, so the
10635            // permissions we have now selected are fixed until explicitly
10636            // changed.
10637            ps.installPermissionsFixed = true;
10638        }
10639
10640        // Persist the runtime permissions state for users with changes. If permissions
10641        // were revoked because no app in the shared user declares them we have to
10642        // write synchronously to avoid losing runtime permissions state.
10643        for (int userId : changedRuntimePermissionUserIds) {
10644            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10645        }
10646    }
10647
10648    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10649        boolean allowed = false;
10650        final int NP = PackageParser.NEW_PERMISSIONS.length;
10651        for (int ip=0; ip<NP; ip++) {
10652            final PackageParser.NewPermissionInfo npi
10653                    = PackageParser.NEW_PERMISSIONS[ip];
10654            if (npi.name.equals(perm)
10655                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10656                allowed = true;
10657                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10658                        + pkg.packageName);
10659                break;
10660            }
10661        }
10662        return allowed;
10663    }
10664
10665    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10666            BasePermission bp, PermissionsState origPermissions) {
10667        boolean privilegedPermission = (bp.protectionLevel
10668                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
10669        boolean privappPermissionsDisable =
10670                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
10671        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
10672        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
10673        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
10674                && !platformPackage && platformPermission) {
10675            ArraySet<String> wlPermissions = SystemConfig.getInstance()
10676                    .getPrivAppPermissions(pkg.packageName);
10677            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
10678            if (!whitelisted) {
10679                Slog.w(TAG, "Privileged permission " + perm + " for package "
10680                        + pkg.packageName + " - not in privapp-permissions whitelist");
10681                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
10682                    return false;
10683                }
10684            }
10685        }
10686        boolean allowed = (compareSignatures(
10687                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10688                        == PackageManager.SIGNATURE_MATCH)
10689                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10690                        == PackageManager.SIGNATURE_MATCH);
10691        if (!allowed && privilegedPermission) {
10692            if (isSystemApp(pkg)) {
10693                // For updated system applications, a system permission
10694                // is granted only if it had been defined by the original application.
10695                if (pkg.isUpdatedSystemApp()) {
10696                    final PackageSetting sysPs = mSettings
10697                            .getDisabledSystemPkgLPr(pkg.packageName);
10698                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10699                        // If the original was granted this permission, we take
10700                        // that grant decision as read and propagate it to the
10701                        // update.
10702                        if (sysPs.isPrivileged()) {
10703                            allowed = true;
10704                        }
10705                    } else {
10706                        // The system apk may have been updated with an older
10707                        // version of the one on the data partition, but which
10708                        // granted a new system permission that it didn't have
10709                        // before.  In this case we do want to allow the app to
10710                        // now get the new permission if the ancestral apk is
10711                        // privileged to get it.
10712                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10713                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10714                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10715                                    allowed = true;
10716                                    break;
10717                                }
10718                            }
10719                        }
10720                        // Also if a privileged parent package on the system image or any of
10721                        // its children requested a privileged permission, the updated child
10722                        // packages can also get the permission.
10723                        if (pkg.parentPackage != null) {
10724                            final PackageSetting disabledSysParentPs = mSettings
10725                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10726                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10727                                    && disabledSysParentPs.isPrivileged()) {
10728                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10729                                    allowed = true;
10730                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10731                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10732                                    for (int i = 0; i < count; i++) {
10733                                        PackageParser.Package disabledSysChildPkg =
10734                                                disabledSysParentPs.pkg.childPackages.get(i);
10735                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10736                                                perm)) {
10737                                            allowed = true;
10738                                            break;
10739                                        }
10740                                    }
10741                                }
10742                            }
10743                        }
10744                    }
10745                } else {
10746                    allowed = isPrivilegedApp(pkg);
10747                }
10748            }
10749        }
10750        if (!allowed) {
10751            if (!allowed && (bp.protectionLevel
10752                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10753                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10754                // If this was a previously normal/dangerous permission that got moved
10755                // to a system permission as part of the runtime permission redesign, then
10756                // we still want to blindly grant it to old apps.
10757                allowed = true;
10758            }
10759            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10760                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10761                // If this permission is to be granted to the system installer and
10762                // this app is an installer, then it gets the permission.
10763                allowed = true;
10764            }
10765            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10766                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10767                // If this permission is to be granted to the system verifier and
10768                // this app is a verifier, then it gets the permission.
10769                allowed = true;
10770            }
10771            if (!allowed && (bp.protectionLevel
10772                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10773                    && isSystemApp(pkg)) {
10774                // Any pre-installed system app is allowed to get this permission.
10775                allowed = true;
10776            }
10777            if (!allowed && (bp.protectionLevel
10778                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10779                // For development permissions, a development permission
10780                // is granted only if it was already granted.
10781                allowed = origPermissions.hasInstallPermission(perm);
10782            }
10783            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10784                    && pkg.packageName.equals(mSetupWizardPackage)) {
10785                // If this permission is to be granted to the system setup wizard and
10786                // this app is a setup wizard, then it gets the permission.
10787                allowed = true;
10788            }
10789        }
10790        return allowed;
10791    }
10792
10793    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10794        final int permCount = pkg.requestedPermissions.size();
10795        for (int j = 0; j < permCount; j++) {
10796            String requestedPermission = pkg.requestedPermissions.get(j);
10797            if (permission.equals(requestedPermission)) {
10798                return true;
10799            }
10800        }
10801        return false;
10802    }
10803
10804    final class ActivityIntentResolver
10805            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10806        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10807                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
10808            if (!sUserManager.exists(userId)) return null;
10809            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
10810                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
10811                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
10812            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
10813                    isEphemeral, userId);
10814        }
10815
10816        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10817                int userId) {
10818            if (!sUserManager.exists(userId)) return null;
10819            mFlags = flags;
10820            return super.queryIntent(intent, resolvedType,
10821                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
10822                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
10823                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
10824        }
10825
10826        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10827                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10828            if (!sUserManager.exists(userId)) return null;
10829            if (packageActivities == null) {
10830                return null;
10831            }
10832            mFlags = flags;
10833            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10834            final boolean vislbleToEphemeral =
10835                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
10836            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
10837            final int N = packageActivities.size();
10838            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10839                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10840
10841            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10842            for (int i = 0; i < N; ++i) {
10843                intentFilters = packageActivities.get(i).intents;
10844                if (intentFilters != null && intentFilters.size() > 0) {
10845                    PackageParser.ActivityIntentInfo[] array =
10846                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10847                    intentFilters.toArray(array);
10848                    listCut.add(array);
10849                }
10850            }
10851            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
10852                    vislbleToEphemeral, isEphemeral, listCut, userId);
10853        }
10854
10855        /**
10856         * Finds a privileged activity that matches the specified activity names.
10857         */
10858        private PackageParser.Activity findMatchingActivity(
10859                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10860            for (PackageParser.Activity sysActivity : activityList) {
10861                if (sysActivity.info.name.equals(activityInfo.name)) {
10862                    return sysActivity;
10863                }
10864                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10865                    return sysActivity;
10866                }
10867                if (sysActivity.info.targetActivity != null) {
10868                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10869                        return sysActivity;
10870                    }
10871                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10872                        return sysActivity;
10873                    }
10874                }
10875            }
10876            return null;
10877        }
10878
10879        public class IterGenerator<E> {
10880            public Iterator<E> generate(ActivityIntentInfo info) {
10881                return null;
10882            }
10883        }
10884
10885        public class ActionIterGenerator extends IterGenerator<String> {
10886            @Override
10887            public Iterator<String> generate(ActivityIntentInfo info) {
10888                return info.actionsIterator();
10889            }
10890        }
10891
10892        public class CategoriesIterGenerator extends IterGenerator<String> {
10893            @Override
10894            public Iterator<String> generate(ActivityIntentInfo info) {
10895                return info.categoriesIterator();
10896            }
10897        }
10898
10899        public class SchemesIterGenerator extends IterGenerator<String> {
10900            @Override
10901            public Iterator<String> generate(ActivityIntentInfo info) {
10902                return info.schemesIterator();
10903            }
10904        }
10905
10906        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10907            @Override
10908            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10909                return info.authoritiesIterator();
10910            }
10911        }
10912
10913        /**
10914         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10915         * MODIFIED. Do not pass in a list that should not be changed.
10916         */
10917        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10918                IterGenerator<T> generator, Iterator<T> searchIterator) {
10919            // loop through the set of actions; every one must be found in the intent filter
10920            while (searchIterator.hasNext()) {
10921                // we must have at least one filter in the list to consider a match
10922                if (intentList.size() == 0) {
10923                    break;
10924                }
10925
10926                final T searchAction = searchIterator.next();
10927
10928                // loop through the set of intent filters
10929                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10930                while (intentIter.hasNext()) {
10931                    final ActivityIntentInfo intentInfo = intentIter.next();
10932                    boolean selectionFound = false;
10933
10934                    // loop through the intent filter's selection criteria; at least one
10935                    // of them must match the searched criteria
10936                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10937                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10938                        final T intentSelection = intentSelectionIter.next();
10939                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10940                            selectionFound = true;
10941                            break;
10942                        }
10943                    }
10944
10945                    // the selection criteria wasn't found in this filter's set; this filter
10946                    // is not a potential match
10947                    if (!selectionFound) {
10948                        intentIter.remove();
10949                    }
10950                }
10951            }
10952        }
10953
10954        private boolean isProtectedAction(ActivityIntentInfo filter) {
10955            final Iterator<String> actionsIter = filter.actionsIterator();
10956            while (actionsIter != null && actionsIter.hasNext()) {
10957                final String filterAction = actionsIter.next();
10958                if (PROTECTED_ACTIONS.contains(filterAction)) {
10959                    return true;
10960                }
10961            }
10962            return false;
10963        }
10964
10965        /**
10966         * Adjusts the priority of the given intent filter according to policy.
10967         * <p>
10968         * <ul>
10969         * <li>The priority for non privileged applications is capped to '0'</li>
10970         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10971         * <li>The priority for unbundled updates to privileged applications is capped to the
10972         *      priority defined on the system partition</li>
10973         * </ul>
10974         * <p>
10975         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10976         * allowed to obtain any priority on any action.
10977         */
10978        private void adjustPriority(
10979                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10980            // nothing to do; priority is fine as-is
10981            if (intent.getPriority() <= 0) {
10982                return;
10983            }
10984
10985            final ActivityInfo activityInfo = intent.activity.info;
10986            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10987
10988            final boolean privilegedApp =
10989                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10990            if (!privilegedApp) {
10991                // non-privileged applications can never define a priority >0
10992                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10993                        + " package: " + applicationInfo.packageName
10994                        + " activity: " + intent.activity.className
10995                        + " origPrio: " + intent.getPriority());
10996                intent.setPriority(0);
10997                return;
10998            }
10999
11000            if (systemActivities == null) {
11001                // the system package is not disabled; we're parsing the system partition
11002                if (isProtectedAction(intent)) {
11003                    if (mDeferProtectedFilters) {
11004                        // We can't deal with these just yet. No component should ever obtain a
11005                        // >0 priority for a protected actions, with ONE exception -- the setup
11006                        // wizard. The setup wizard, however, cannot be known until we're able to
11007                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11008                        // until all intent filters have been processed. Chicken, meet egg.
11009                        // Let the filter temporarily have a high priority and rectify the
11010                        // priorities after all system packages have been scanned.
11011                        mProtectedFilters.add(intent);
11012                        if (DEBUG_FILTERS) {
11013                            Slog.i(TAG, "Protected action; save for later;"
11014                                    + " package: " + applicationInfo.packageName
11015                                    + " activity: " + intent.activity.className
11016                                    + " origPrio: " + intent.getPriority());
11017                        }
11018                        return;
11019                    } else {
11020                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11021                            Slog.i(TAG, "No setup wizard;"
11022                                + " All protected intents capped to priority 0");
11023                        }
11024                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11025                            if (DEBUG_FILTERS) {
11026                                Slog.i(TAG, "Found setup wizard;"
11027                                    + " allow priority " + intent.getPriority() + ";"
11028                                    + " package: " + intent.activity.info.packageName
11029                                    + " activity: " + intent.activity.className
11030                                    + " priority: " + intent.getPriority());
11031                            }
11032                            // setup wizard gets whatever it wants
11033                            return;
11034                        }
11035                        Slog.w(TAG, "Protected action; cap priority to 0;"
11036                                + " package: " + intent.activity.info.packageName
11037                                + " activity: " + intent.activity.className
11038                                + " origPrio: " + intent.getPriority());
11039                        intent.setPriority(0);
11040                        return;
11041                    }
11042                }
11043                // privileged apps on the system image get whatever priority they request
11044                return;
11045            }
11046
11047            // privileged app unbundled update ... try to find the same activity
11048            final PackageParser.Activity foundActivity =
11049                    findMatchingActivity(systemActivities, activityInfo);
11050            if (foundActivity == null) {
11051                // this is a new activity; it cannot obtain >0 priority
11052                if (DEBUG_FILTERS) {
11053                    Slog.i(TAG, "New activity; cap priority to 0;"
11054                            + " package: " + applicationInfo.packageName
11055                            + " activity: " + intent.activity.className
11056                            + " origPrio: " + intent.getPriority());
11057                }
11058                intent.setPriority(0);
11059                return;
11060            }
11061
11062            // found activity, now check for filter equivalence
11063
11064            // a shallow copy is enough; we modify the list, not its contents
11065            final List<ActivityIntentInfo> intentListCopy =
11066                    new ArrayList<>(foundActivity.intents);
11067            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11068
11069            // find matching action subsets
11070            final Iterator<String> actionsIterator = intent.actionsIterator();
11071            if (actionsIterator != null) {
11072                getIntentListSubset(
11073                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11074                if (intentListCopy.size() == 0) {
11075                    // no more intents to match; we're not equivalent
11076                    if (DEBUG_FILTERS) {
11077                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11078                                + " package: " + applicationInfo.packageName
11079                                + " activity: " + intent.activity.className
11080                                + " origPrio: " + intent.getPriority());
11081                    }
11082                    intent.setPriority(0);
11083                    return;
11084                }
11085            }
11086
11087            // find matching category subsets
11088            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11089            if (categoriesIterator != null) {
11090                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11091                        categoriesIterator);
11092                if (intentListCopy.size() == 0) {
11093                    // no more intents to match; we're not equivalent
11094                    if (DEBUG_FILTERS) {
11095                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11096                                + " package: " + applicationInfo.packageName
11097                                + " activity: " + intent.activity.className
11098                                + " origPrio: " + intent.getPriority());
11099                    }
11100                    intent.setPriority(0);
11101                    return;
11102                }
11103            }
11104
11105            // find matching schemes subsets
11106            final Iterator<String> schemesIterator = intent.schemesIterator();
11107            if (schemesIterator != null) {
11108                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11109                        schemesIterator);
11110                if (intentListCopy.size() == 0) {
11111                    // no more intents to match; we're not equivalent
11112                    if (DEBUG_FILTERS) {
11113                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11114                                + " package: " + applicationInfo.packageName
11115                                + " activity: " + intent.activity.className
11116                                + " origPrio: " + intent.getPriority());
11117                    }
11118                    intent.setPriority(0);
11119                    return;
11120                }
11121            }
11122
11123            // find matching authorities subsets
11124            final Iterator<IntentFilter.AuthorityEntry>
11125                    authoritiesIterator = intent.authoritiesIterator();
11126            if (authoritiesIterator != null) {
11127                getIntentListSubset(intentListCopy,
11128                        new AuthoritiesIterGenerator(),
11129                        authoritiesIterator);
11130                if (intentListCopy.size() == 0) {
11131                    // no more intents to match; we're not equivalent
11132                    if (DEBUG_FILTERS) {
11133                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11134                                + " package: " + applicationInfo.packageName
11135                                + " activity: " + intent.activity.className
11136                                + " origPrio: " + intent.getPriority());
11137                    }
11138                    intent.setPriority(0);
11139                    return;
11140                }
11141            }
11142
11143            // we found matching filter(s); app gets the max priority of all intents
11144            int cappedPriority = 0;
11145            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11146                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11147            }
11148            if (intent.getPriority() > cappedPriority) {
11149                if (DEBUG_FILTERS) {
11150                    Slog.i(TAG, "Found matching filter(s);"
11151                            + " cap priority to " + cappedPriority + ";"
11152                            + " package: " + applicationInfo.packageName
11153                            + " activity: " + intent.activity.className
11154                            + " origPrio: " + intent.getPriority());
11155                }
11156                intent.setPriority(cappedPriority);
11157                return;
11158            }
11159            // all this for nothing; the requested priority was <= what was on the system
11160        }
11161
11162        public final void addActivity(PackageParser.Activity a, String type) {
11163            mActivities.put(a.getComponentName(), a);
11164            if (DEBUG_SHOW_INFO)
11165                Log.v(
11166                TAG, "  " + type + " " +
11167                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11168            if (DEBUG_SHOW_INFO)
11169                Log.v(TAG, "    Class=" + a.info.name);
11170            final int NI = a.intents.size();
11171            for (int j=0; j<NI; j++) {
11172                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11173                if ("activity".equals(type)) {
11174                    final PackageSetting ps =
11175                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11176                    final List<PackageParser.Activity> systemActivities =
11177                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11178                    adjustPriority(systemActivities, intent);
11179                }
11180                if (DEBUG_SHOW_INFO) {
11181                    Log.v(TAG, "    IntentFilter:");
11182                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11183                }
11184                if (!intent.debugCheck()) {
11185                    Log.w(TAG, "==> For Activity " + a.info.name);
11186                }
11187                addFilter(intent);
11188            }
11189        }
11190
11191        public final void removeActivity(PackageParser.Activity a, String type) {
11192            mActivities.remove(a.getComponentName());
11193            if (DEBUG_SHOW_INFO) {
11194                Log.v(TAG, "  " + type + " "
11195                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11196                                : a.info.name) + ":");
11197                Log.v(TAG, "    Class=" + a.info.name);
11198            }
11199            final int NI = a.intents.size();
11200            for (int j=0; j<NI; j++) {
11201                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11202                if (DEBUG_SHOW_INFO) {
11203                    Log.v(TAG, "    IntentFilter:");
11204                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11205                }
11206                removeFilter(intent);
11207            }
11208        }
11209
11210        @Override
11211        protected boolean allowFilterResult(
11212                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11213            ActivityInfo filterAi = filter.activity.info;
11214            for (int i=dest.size()-1; i>=0; i--) {
11215                ActivityInfo destAi = dest.get(i).activityInfo;
11216                if (destAi.name == filterAi.name
11217                        && destAi.packageName == filterAi.packageName) {
11218                    return false;
11219                }
11220            }
11221            return true;
11222        }
11223
11224        @Override
11225        protected ActivityIntentInfo[] newArray(int size) {
11226            return new ActivityIntentInfo[size];
11227        }
11228
11229        @Override
11230        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
11231            if (!sUserManager.exists(userId)) return true;
11232            PackageParser.Package p = filter.activity.owner;
11233            if (p != null) {
11234                PackageSetting ps = (PackageSetting)p.mExtras;
11235                if (ps != null) {
11236                    // System apps are never considered stopped for purposes of
11237                    // filtering, because there may be no way for the user to
11238                    // actually re-launch them.
11239                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
11240                            && ps.getStopped(userId);
11241                }
11242            }
11243            return false;
11244        }
11245
11246        @Override
11247        protected boolean isPackageForFilter(String packageName,
11248                PackageParser.ActivityIntentInfo info) {
11249            return packageName.equals(info.activity.owner.packageName);
11250        }
11251
11252        @Override
11253        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
11254                int match, int userId) {
11255            if (!sUserManager.exists(userId)) return null;
11256            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
11257                return null;
11258            }
11259            final PackageParser.Activity activity = info.activity;
11260            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
11261            if (ps == null) {
11262                return null;
11263            }
11264            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
11265                    ps.readUserState(userId), userId);
11266            if (ai == null) {
11267                return null;
11268            }
11269            final ResolveInfo res = new ResolveInfo();
11270            res.activityInfo = ai;
11271            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11272                res.filter = info;
11273            }
11274            if (info != null) {
11275                res.handleAllWebDataURI = info.handleAllWebDataURI();
11276            }
11277            res.priority = info.getPriority();
11278            res.preferredOrder = activity.owner.mPreferredOrder;
11279            //System.out.println("Result: " + res.activityInfo.className +
11280            //                   " = " + res.priority);
11281            res.match = match;
11282            res.isDefault = info.hasDefault;
11283            res.labelRes = info.labelRes;
11284            res.nonLocalizedLabel = info.nonLocalizedLabel;
11285            if (userNeedsBadging(userId)) {
11286                res.noResourceId = true;
11287            } else {
11288                res.icon = info.icon;
11289            }
11290            res.iconResourceId = info.icon;
11291            res.system = res.activityInfo.applicationInfo.isSystemApp();
11292            return res;
11293        }
11294
11295        @Override
11296        protected void sortResults(List<ResolveInfo> results) {
11297            Collections.sort(results, mResolvePrioritySorter);
11298        }
11299
11300        @Override
11301        protected void dumpFilter(PrintWriter out, String prefix,
11302                PackageParser.ActivityIntentInfo filter) {
11303            out.print(prefix); out.print(
11304                    Integer.toHexString(System.identityHashCode(filter.activity)));
11305                    out.print(' ');
11306                    filter.activity.printComponentShortName(out);
11307                    out.print(" filter ");
11308                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11309        }
11310
11311        @Override
11312        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
11313            return filter.activity;
11314        }
11315
11316        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11317            PackageParser.Activity activity = (PackageParser.Activity)label;
11318            out.print(prefix); out.print(
11319                    Integer.toHexString(System.identityHashCode(activity)));
11320                    out.print(' ');
11321                    activity.printComponentShortName(out);
11322            if (count > 1) {
11323                out.print(" ("); out.print(count); out.print(" filters)");
11324            }
11325            out.println();
11326        }
11327
11328        // Keys are String (activity class name), values are Activity.
11329        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
11330                = new ArrayMap<ComponentName, PackageParser.Activity>();
11331        private int mFlags;
11332    }
11333
11334    private final class ServiceIntentResolver
11335            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
11336        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11337                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11338            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11339            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11340                    isEphemeral, userId);
11341        }
11342
11343        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11344                int userId) {
11345            if (!sUserManager.exists(userId)) return null;
11346            mFlags = flags;
11347            return super.queryIntent(intent, resolvedType,
11348                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11349                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11350                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11351        }
11352
11353        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11354                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
11355            if (!sUserManager.exists(userId)) return null;
11356            if (packageServices == null) {
11357                return null;
11358            }
11359            mFlags = flags;
11360            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
11361            final boolean vislbleToEphemeral =
11362                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11363            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11364            final int N = packageServices.size();
11365            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
11366                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
11367
11368            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
11369            for (int i = 0; i < N; ++i) {
11370                intentFilters = packageServices.get(i).intents;
11371                if (intentFilters != null && intentFilters.size() > 0) {
11372                    PackageParser.ServiceIntentInfo[] array =
11373                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
11374                    intentFilters.toArray(array);
11375                    listCut.add(array);
11376                }
11377            }
11378            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11379                    vislbleToEphemeral, isEphemeral, listCut, userId);
11380        }
11381
11382        public final void addService(PackageParser.Service s) {
11383            mServices.put(s.getComponentName(), s);
11384            if (DEBUG_SHOW_INFO) {
11385                Log.v(TAG, "  "
11386                        + (s.info.nonLocalizedLabel != null
11387                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11388                Log.v(TAG, "    Class=" + s.info.name);
11389            }
11390            final int NI = s.intents.size();
11391            int j;
11392            for (j=0; j<NI; j++) {
11393                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11394                if (DEBUG_SHOW_INFO) {
11395                    Log.v(TAG, "    IntentFilter:");
11396                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11397                }
11398                if (!intent.debugCheck()) {
11399                    Log.w(TAG, "==> For Service " + s.info.name);
11400                }
11401                addFilter(intent);
11402            }
11403        }
11404
11405        public final void removeService(PackageParser.Service s) {
11406            mServices.remove(s.getComponentName());
11407            if (DEBUG_SHOW_INFO) {
11408                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
11409                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
11410                Log.v(TAG, "    Class=" + s.info.name);
11411            }
11412            final int NI = s.intents.size();
11413            int j;
11414            for (j=0; j<NI; j++) {
11415                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11416                if (DEBUG_SHOW_INFO) {
11417                    Log.v(TAG, "    IntentFilter:");
11418                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11419                }
11420                removeFilter(intent);
11421            }
11422        }
11423
11424        @Override
11425        protected boolean allowFilterResult(
11426                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11427            ServiceInfo filterSi = filter.service.info;
11428            for (int i=dest.size()-1; i>=0; i--) {
11429                ServiceInfo destAi = dest.get(i).serviceInfo;
11430                if (destAi.name == filterSi.name
11431                        && destAi.packageName == filterSi.packageName) {
11432                    return false;
11433                }
11434            }
11435            return true;
11436        }
11437
11438        @Override
11439        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11440            return new PackageParser.ServiceIntentInfo[size];
11441        }
11442
11443        @Override
11444        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11445            if (!sUserManager.exists(userId)) return true;
11446            PackageParser.Package p = filter.service.owner;
11447            if (p != null) {
11448                PackageSetting ps = (PackageSetting)p.mExtras;
11449                if (ps != null) {
11450                    // System apps are never considered stopped for purposes of
11451                    // filtering, because there may be no way for the user to
11452                    // actually re-launch them.
11453                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11454                            && ps.getStopped(userId);
11455                }
11456            }
11457            return false;
11458        }
11459
11460        @Override
11461        protected boolean isPackageForFilter(String packageName,
11462                PackageParser.ServiceIntentInfo info) {
11463            return packageName.equals(info.service.owner.packageName);
11464        }
11465
11466        @Override
11467        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11468                int match, int userId) {
11469            if (!sUserManager.exists(userId)) return null;
11470            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11471            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11472                return null;
11473            }
11474            final PackageParser.Service service = info.service;
11475            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11476            if (ps == null) {
11477                return null;
11478            }
11479            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11480                    ps.readUserState(userId), userId);
11481            if (si == null) {
11482                return null;
11483            }
11484            final ResolveInfo res = new ResolveInfo();
11485            res.serviceInfo = si;
11486            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11487                res.filter = filter;
11488            }
11489            res.priority = info.getPriority();
11490            res.preferredOrder = service.owner.mPreferredOrder;
11491            res.match = match;
11492            res.isDefault = info.hasDefault;
11493            res.labelRes = info.labelRes;
11494            res.nonLocalizedLabel = info.nonLocalizedLabel;
11495            res.icon = info.icon;
11496            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11497            return res;
11498        }
11499
11500        @Override
11501        protected void sortResults(List<ResolveInfo> results) {
11502            Collections.sort(results, mResolvePrioritySorter);
11503        }
11504
11505        @Override
11506        protected void dumpFilter(PrintWriter out, String prefix,
11507                PackageParser.ServiceIntentInfo filter) {
11508            out.print(prefix); out.print(
11509                    Integer.toHexString(System.identityHashCode(filter.service)));
11510                    out.print(' ');
11511                    filter.service.printComponentShortName(out);
11512                    out.print(" filter ");
11513                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11514        }
11515
11516        @Override
11517        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11518            return filter.service;
11519        }
11520
11521        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11522            PackageParser.Service service = (PackageParser.Service)label;
11523            out.print(prefix); out.print(
11524                    Integer.toHexString(System.identityHashCode(service)));
11525                    out.print(' ');
11526                    service.printComponentShortName(out);
11527            if (count > 1) {
11528                out.print(" ("); out.print(count); out.print(" filters)");
11529            }
11530            out.println();
11531        }
11532
11533//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11534//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11535//            final List<ResolveInfo> retList = Lists.newArrayList();
11536//            while (i.hasNext()) {
11537//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11538//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11539//                    retList.add(resolveInfo);
11540//                }
11541//            }
11542//            return retList;
11543//        }
11544
11545        // Keys are String (activity class name), values are Activity.
11546        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11547                = new ArrayMap<ComponentName, PackageParser.Service>();
11548        private int mFlags;
11549    }
11550
11551    private final class ProviderIntentResolver
11552            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11553        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11554                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11555            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11556            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11557                    isEphemeral, userId);
11558        }
11559
11560        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11561                int userId) {
11562            if (!sUserManager.exists(userId))
11563                return null;
11564            mFlags = flags;
11565            return super.queryIntent(intent, resolvedType,
11566                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11567                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11568                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11569        }
11570
11571        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11572                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11573            if (!sUserManager.exists(userId))
11574                return null;
11575            if (packageProviders == null) {
11576                return null;
11577            }
11578            mFlags = flags;
11579            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11580            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
11581            final boolean vislbleToEphemeral =
11582                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11583            final int N = packageProviders.size();
11584            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11585                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11586
11587            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11588            for (int i = 0; i < N; ++i) {
11589                intentFilters = packageProviders.get(i).intents;
11590                if (intentFilters != null && intentFilters.size() > 0) {
11591                    PackageParser.ProviderIntentInfo[] array =
11592                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11593                    intentFilters.toArray(array);
11594                    listCut.add(array);
11595                }
11596            }
11597            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11598                    vislbleToEphemeral, isEphemeral, listCut, userId);
11599        }
11600
11601        public final void addProvider(PackageParser.Provider p) {
11602            if (mProviders.containsKey(p.getComponentName())) {
11603                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11604                return;
11605            }
11606
11607            mProviders.put(p.getComponentName(), p);
11608            if (DEBUG_SHOW_INFO) {
11609                Log.v(TAG, "  "
11610                        + (p.info.nonLocalizedLabel != null
11611                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11612                Log.v(TAG, "    Class=" + p.info.name);
11613            }
11614            final int NI = p.intents.size();
11615            int j;
11616            for (j = 0; j < NI; j++) {
11617                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11618                if (DEBUG_SHOW_INFO) {
11619                    Log.v(TAG, "    IntentFilter:");
11620                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11621                }
11622                if (!intent.debugCheck()) {
11623                    Log.w(TAG, "==> For Provider " + p.info.name);
11624                }
11625                addFilter(intent);
11626            }
11627        }
11628
11629        public final void removeProvider(PackageParser.Provider p) {
11630            mProviders.remove(p.getComponentName());
11631            if (DEBUG_SHOW_INFO) {
11632                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11633                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11634                Log.v(TAG, "    Class=" + p.info.name);
11635            }
11636            final int NI = p.intents.size();
11637            int j;
11638            for (j = 0; j < NI; j++) {
11639                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11640                if (DEBUG_SHOW_INFO) {
11641                    Log.v(TAG, "    IntentFilter:");
11642                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11643                }
11644                removeFilter(intent);
11645            }
11646        }
11647
11648        @Override
11649        protected boolean allowFilterResult(
11650                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11651            ProviderInfo filterPi = filter.provider.info;
11652            for (int i = dest.size() - 1; i >= 0; i--) {
11653                ProviderInfo destPi = dest.get(i).providerInfo;
11654                if (destPi.name == filterPi.name
11655                        && destPi.packageName == filterPi.packageName) {
11656                    return false;
11657                }
11658            }
11659            return true;
11660        }
11661
11662        @Override
11663        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11664            return new PackageParser.ProviderIntentInfo[size];
11665        }
11666
11667        @Override
11668        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11669            if (!sUserManager.exists(userId))
11670                return true;
11671            PackageParser.Package p = filter.provider.owner;
11672            if (p != null) {
11673                PackageSetting ps = (PackageSetting) p.mExtras;
11674                if (ps != null) {
11675                    // System apps are never considered stopped for purposes of
11676                    // filtering, because there may be no way for the user to
11677                    // actually re-launch them.
11678                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11679                            && ps.getStopped(userId);
11680                }
11681            }
11682            return false;
11683        }
11684
11685        @Override
11686        protected boolean isPackageForFilter(String packageName,
11687                PackageParser.ProviderIntentInfo info) {
11688            return packageName.equals(info.provider.owner.packageName);
11689        }
11690
11691        @Override
11692        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11693                int match, int userId) {
11694            if (!sUserManager.exists(userId))
11695                return null;
11696            final PackageParser.ProviderIntentInfo info = filter;
11697            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11698                return null;
11699            }
11700            final PackageParser.Provider provider = info.provider;
11701            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11702            if (ps == null) {
11703                return null;
11704            }
11705            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11706                    ps.readUserState(userId), userId);
11707            if (pi == null) {
11708                return null;
11709            }
11710            final ResolveInfo res = new ResolveInfo();
11711            res.providerInfo = pi;
11712            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11713                res.filter = filter;
11714            }
11715            res.priority = info.getPriority();
11716            res.preferredOrder = provider.owner.mPreferredOrder;
11717            res.match = match;
11718            res.isDefault = info.hasDefault;
11719            res.labelRes = info.labelRes;
11720            res.nonLocalizedLabel = info.nonLocalizedLabel;
11721            res.icon = info.icon;
11722            res.system = res.providerInfo.applicationInfo.isSystemApp();
11723            return res;
11724        }
11725
11726        @Override
11727        protected void sortResults(List<ResolveInfo> results) {
11728            Collections.sort(results, mResolvePrioritySorter);
11729        }
11730
11731        @Override
11732        protected void dumpFilter(PrintWriter out, String prefix,
11733                PackageParser.ProviderIntentInfo filter) {
11734            out.print(prefix);
11735            out.print(
11736                    Integer.toHexString(System.identityHashCode(filter.provider)));
11737            out.print(' ');
11738            filter.provider.printComponentShortName(out);
11739            out.print(" filter ");
11740            out.println(Integer.toHexString(System.identityHashCode(filter)));
11741        }
11742
11743        @Override
11744        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11745            return filter.provider;
11746        }
11747
11748        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11749            PackageParser.Provider provider = (PackageParser.Provider)label;
11750            out.print(prefix); out.print(
11751                    Integer.toHexString(System.identityHashCode(provider)));
11752                    out.print(' ');
11753                    provider.printComponentShortName(out);
11754            if (count > 1) {
11755                out.print(" ("); out.print(count); out.print(" filters)");
11756            }
11757            out.println();
11758        }
11759
11760        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11761                = new ArrayMap<ComponentName, PackageParser.Provider>();
11762        private int mFlags;
11763    }
11764
11765    static final class EphemeralIntentResolver
11766            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
11767        /**
11768         * The result that has the highest defined order. Ordering applies on a
11769         * per-package basis. Mapping is from package name to Pair of order and
11770         * EphemeralResolveInfo.
11771         * <p>
11772         * NOTE: This is implemented as a field variable for convenience and efficiency.
11773         * By having a field variable, we're able to track filter ordering as soon as
11774         * a non-zero order is defined. Otherwise, multiple loops across the result set
11775         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11776         * this needs to be contained entirely within {@link #filterResults()}.
11777         */
11778        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11779
11780        @Override
11781        protected EphemeralResponse[] newArray(int size) {
11782            return new EphemeralResponse[size];
11783        }
11784
11785        @Override
11786        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
11787            return true;
11788        }
11789
11790        @Override
11791        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
11792                int userId) {
11793            if (!sUserManager.exists(userId)) {
11794                return null;
11795            }
11796            final String packageName = responseObj.resolveInfo.getPackageName();
11797            final Integer order = responseObj.getOrder();
11798            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11799                    mOrderResult.get(packageName);
11800            // ordering is enabled and this item's order isn't high enough
11801            if (lastOrderResult != null && lastOrderResult.first >= order) {
11802                return null;
11803            }
11804            final EphemeralResolveInfo res = responseObj.resolveInfo;
11805            if (order > 0) {
11806                // non-zero order, enable ordering
11807                mOrderResult.put(packageName, new Pair<>(order, res));
11808            }
11809            return responseObj;
11810        }
11811
11812        @Override
11813        protected void filterResults(List<EphemeralResponse> results) {
11814            // only do work if ordering is enabled [most of the time it won't be]
11815            if (mOrderResult.size() == 0) {
11816                return;
11817            }
11818            int resultSize = results.size();
11819            for (int i = 0; i < resultSize; i++) {
11820                final EphemeralResolveInfo info = results.get(i).resolveInfo;
11821                final String packageName = info.getPackageName();
11822                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11823                if (savedInfo == null) {
11824                    // package doesn't having ordering
11825                    continue;
11826                }
11827                if (savedInfo.second == info) {
11828                    // circled back to the highest ordered item; remove from order list
11829                    mOrderResult.remove(savedInfo);
11830                    if (mOrderResult.size() == 0) {
11831                        // no more ordered items
11832                        break;
11833                    }
11834                    continue;
11835                }
11836                // item has a worse order, remove it from the result list
11837                results.remove(i);
11838                resultSize--;
11839                i--;
11840            }
11841        }
11842    }
11843
11844    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11845            new Comparator<ResolveInfo>() {
11846        public int compare(ResolveInfo r1, ResolveInfo r2) {
11847            int v1 = r1.priority;
11848            int v2 = r2.priority;
11849            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11850            if (v1 != v2) {
11851                return (v1 > v2) ? -1 : 1;
11852            }
11853            v1 = r1.preferredOrder;
11854            v2 = r2.preferredOrder;
11855            if (v1 != v2) {
11856                return (v1 > v2) ? -1 : 1;
11857            }
11858            if (r1.isDefault != r2.isDefault) {
11859                return r1.isDefault ? -1 : 1;
11860            }
11861            v1 = r1.match;
11862            v2 = r2.match;
11863            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11864            if (v1 != v2) {
11865                return (v1 > v2) ? -1 : 1;
11866            }
11867            if (r1.system != r2.system) {
11868                return r1.system ? -1 : 1;
11869            }
11870            if (r1.activityInfo != null) {
11871                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11872            }
11873            if (r1.serviceInfo != null) {
11874                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11875            }
11876            if (r1.providerInfo != null) {
11877                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11878            }
11879            return 0;
11880        }
11881    };
11882
11883    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11884            new Comparator<ProviderInfo>() {
11885        public int compare(ProviderInfo p1, ProviderInfo p2) {
11886            final int v1 = p1.initOrder;
11887            final int v2 = p2.initOrder;
11888            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11889        }
11890    };
11891
11892    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11893            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11894            final int[] userIds) {
11895        mHandler.post(new Runnable() {
11896            @Override
11897            public void run() {
11898                try {
11899                    final IActivityManager am = ActivityManager.getService();
11900                    if (am == null) return;
11901                    final int[] resolvedUserIds;
11902                    if (userIds == null) {
11903                        resolvedUserIds = am.getRunningUserIds();
11904                    } else {
11905                        resolvedUserIds = userIds;
11906                    }
11907                    for (int id : resolvedUserIds) {
11908                        final Intent intent = new Intent(action,
11909                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11910                        if (extras != null) {
11911                            intent.putExtras(extras);
11912                        }
11913                        if (targetPkg != null) {
11914                            intent.setPackage(targetPkg);
11915                        }
11916                        // Modify the UID when posting to other users
11917                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11918                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11919                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11920                            intent.putExtra(Intent.EXTRA_UID, uid);
11921                        }
11922                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11923                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11924                        if (DEBUG_BROADCASTS) {
11925                            RuntimeException here = new RuntimeException("here");
11926                            here.fillInStackTrace();
11927                            Slog.d(TAG, "Sending to user " + id + ": "
11928                                    + intent.toShortString(false, true, false, false)
11929                                    + " " + intent.getExtras(), here);
11930                        }
11931                        am.broadcastIntent(null, intent, null, finishedReceiver,
11932                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11933                                null, finishedReceiver != null, false, id);
11934                    }
11935                } catch (RemoteException ex) {
11936                }
11937            }
11938        });
11939    }
11940
11941    /**
11942     * Check if the external storage media is available. This is true if there
11943     * is a mounted external storage medium or if the external storage is
11944     * emulated.
11945     */
11946    private boolean isExternalMediaAvailable() {
11947        return mMediaMounted || Environment.isExternalStorageEmulated();
11948    }
11949
11950    @Override
11951    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11952        // writer
11953        synchronized (mPackages) {
11954            if (!isExternalMediaAvailable()) {
11955                // If the external storage is no longer mounted at this point,
11956                // the caller may not have been able to delete all of this
11957                // packages files and can not delete any more.  Bail.
11958                return null;
11959            }
11960            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11961            if (lastPackage != null) {
11962                pkgs.remove(lastPackage);
11963            }
11964            if (pkgs.size() > 0) {
11965                return pkgs.get(0);
11966            }
11967        }
11968        return null;
11969    }
11970
11971    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11972        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11973                userId, andCode ? 1 : 0, packageName);
11974        if (mSystemReady) {
11975            msg.sendToTarget();
11976        } else {
11977            if (mPostSystemReadyMessages == null) {
11978                mPostSystemReadyMessages = new ArrayList<>();
11979            }
11980            mPostSystemReadyMessages.add(msg);
11981        }
11982    }
11983
11984    void startCleaningPackages() {
11985        // reader
11986        if (!isExternalMediaAvailable()) {
11987            return;
11988        }
11989        synchronized (mPackages) {
11990            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11991                return;
11992            }
11993        }
11994        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11995        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11996        IActivityManager am = ActivityManager.getService();
11997        if (am != null) {
11998            try {
11999                am.startService(null, intent, null, mContext.getOpPackageName(),
12000                        UserHandle.USER_SYSTEM);
12001            } catch (RemoteException e) {
12002            }
12003        }
12004    }
12005
12006    @Override
12007    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12008            int installFlags, String installerPackageName, int userId) {
12009        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12010
12011        final int callingUid = Binder.getCallingUid();
12012        enforceCrossUserPermission(callingUid, userId,
12013                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12014
12015        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12016            try {
12017                if (observer != null) {
12018                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12019                }
12020            } catch (RemoteException re) {
12021            }
12022            return;
12023        }
12024
12025        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12026            installFlags |= PackageManager.INSTALL_FROM_ADB;
12027
12028        } else {
12029            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12030            // about installerPackageName.
12031
12032            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12033            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12034        }
12035
12036        UserHandle user;
12037        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12038            user = UserHandle.ALL;
12039        } else {
12040            user = new UserHandle(userId);
12041        }
12042
12043        // Only system components can circumvent runtime permissions when installing.
12044        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12045                && mContext.checkCallingOrSelfPermission(Manifest.permission
12046                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12047            throw new SecurityException("You need the "
12048                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12049                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12050        }
12051
12052        final File originFile = new File(originPath);
12053        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12054
12055        final Message msg = mHandler.obtainMessage(INIT_COPY);
12056        final VerificationInfo verificationInfo = new VerificationInfo(
12057                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12058        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12059                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12060                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12061                null /*certificates*/);
12062        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12063        msg.obj = params;
12064
12065        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12066                System.identityHashCode(msg.obj));
12067        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12068                System.identityHashCode(msg.obj));
12069
12070        mHandler.sendMessage(msg);
12071    }
12072
12073    void installStage(String packageName, File stagedDir, String stagedCid,
12074            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12075            String installerPackageName, int installerUid, UserHandle user,
12076            Certificate[][] certificates) {
12077        if (DEBUG_EPHEMERAL) {
12078            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12079                Slog.d(TAG, "Ephemeral install of " + packageName);
12080            }
12081        }
12082        final VerificationInfo verificationInfo = new VerificationInfo(
12083                sessionParams.originatingUri, sessionParams.referrerUri,
12084                sessionParams.originatingUid, installerUid);
12085
12086        final OriginInfo origin;
12087        if (stagedDir != null) {
12088            origin = OriginInfo.fromStagedFile(stagedDir);
12089        } else {
12090            origin = OriginInfo.fromStagedContainer(stagedCid);
12091        }
12092
12093        final Message msg = mHandler.obtainMessage(INIT_COPY);
12094        final InstallParams params = new InstallParams(origin, null, observer,
12095                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
12096                verificationInfo, user, sessionParams.abiOverride,
12097                sessionParams.grantedRuntimePermissions, certificates);
12098        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
12099        msg.obj = params;
12100
12101        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
12102                System.identityHashCode(msg.obj));
12103        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12104                System.identityHashCode(msg.obj));
12105
12106        mHandler.sendMessage(msg);
12107    }
12108
12109    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
12110            int userId) {
12111        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
12112        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
12113    }
12114
12115    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
12116            int appId, int... userIds) {
12117        if (ArrayUtils.isEmpty(userIds)) {
12118            return;
12119        }
12120        Bundle extras = new Bundle(1);
12121        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
12122        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
12123
12124        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
12125                packageName, extras, 0, null, null, userIds);
12126        if (isSystem) {
12127            mHandler.post(() -> {
12128                        for (int userId : userIds) {
12129                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
12130                        }
12131                    }
12132            );
12133        }
12134    }
12135
12136    /**
12137     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
12138     * automatically without needing an explicit launch.
12139     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
12140     */
12141    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
12142        // If user is not running, the app didn't miss any broadcast
12143        if (!mUserManagerInternal.isUserRunning(userId)) {
12144            return;
12145        }
12146        final IActivityManager am = ActivityManager.getService();
12147        try {
12148            // Deliver LOCKED_BOOT_COMPLETED first
12149            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
12150                    .setPackage(packageName);
12151            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
12152            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
12153                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12154
12155            // Deliver BOOT_COMPLETED only if user is unlocked
12156            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
12157                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
12158                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
12159                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
12160            }
12161        } catch (RemoteException e) {
12162            throw e.rethrowFromSystemServer();
12163        }
12164    }
12165
12166    @Override
12167    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
12168            int userId) {
12169        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12170        PackageSetting pkgSetting;
12171        final int uid = Binder.getCallingUid();
12172        enforceCrossUserPermission(uid, userId,
12173                true /* requireFullPermission */, true /* checkShell */,
12174                "setApplicationHiddenSetting for user " + userId);
12175
12176        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
12177            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
12178            return false;
12179        }
12180
12181        long callingId = Binder.clearCallingIdentity();
12182        try {
12183            boolean sendAdded = false;
12184            boolean sendRemoved = false;
12185            // writer
12186            synchronized (mPackages) {
12187                pkgSetting = mSettings.mPackages.get(packageName);
12188                if (pkgSetting == null) {
12189                    return false;
12190                }
12191                // Do not allow "android" is being disabled
12192                if ("android".equals(packageName)) {
12193                    Slog.w(TAG, "Cannot hide package: android");
12194                    return false;
12195                }
12196                // Only allow protected packages to hide themselves.
12197                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
12198                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12199                    Slog.w(TAG, "Not hiding protected package: " + packageName);
12200                    return false;
12201                }
12202
12203                if (pkgSetting.getHidden(userId) != hidden) {
12204                    pkgSetting.setHidden(hidden, userId);
12205                    mSettings.writePackageRestrictionsLPr(userId);
12206                    if (hidden) {
12207                        sendRemoved = true;
12208                    } else {
12209                        sendAdded = true;
12210                    }
12211                }
12212            }
12213            if (sendAdded) {
12214                sendPackageAddedForUser(packageName, pkgSetting, userId);
12215                return true;
12216            }
12217            if (sendRemoved) {
12218                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
12219                        "hiding pkg");
12220                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
12221                return true;
12222            }
12223        } finally {
12224            Binder.restoreCallingIdentity(callingId);
12225        }
12226        return false;
12227    }
12228
12229    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
12230            int userId) {
12231        final PackageRemovedInfo info = new PackageRemovedInfo();
12232        info.removedPackage = packageName;
12233        info.removedUsers = new int[] {userId};
12234        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
12235        info.sendPackageRemovedBroadcasts(true /*killApp*/);
12236    }
12237
12238    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
12239        if (pkgList.length > 0) {
12240            Bundle extras = new Bundle(1);
12241            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
12242
12243            sendPackageBroadcast(
12244                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
12245                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
12246                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
12247                    new int[] {userId});
12248        }
12249    }
12250
12251    /**
12252     * Returns true if application is not found or there was an error. Otherwise it returns
12253     * the hidden state of the package for the given user.
12254     */
12255    @Override
12256    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
12257        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12258        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12259                true /* requireFullPermission */, false /* checkShell */,
12260                "getApplicationHidden for user " + userId);
12261        PackageSetting pkgSetting;
12262        long callingId = Binder.clearCallingIdentity();
12263        try {
12264            // writer
12265            synchronized (mPackages) {
12266                pkgSetting = mSettings.mPackages.get(packageName);
12267                if (pkgSetting == null) {
12268                    return true;
12269                }
12270                return pkgSetting.getHidden(userId);
12271            }
12272        } finally {
12273            Binder.restoreCallingIdentity(callingId);
12274        }
12275    }
12276
12277    /**
12278     * @hide
12279     */
12280    @Override
12281    public int installExistingPackageAsUser(String packageName, int userId) {
12282        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
12283                null);
12284        PackageSetting pkgSetting;
12285        final int uid = Binder.getCallingUid();
12286        enforceCrossUserPermission(uid, userId,
12287                true /* requireFullPermission */, true /* checkShell */,
12288                "installExistingPackage for user " + userId);
12289        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12290            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
12291        }
12292
12293        long callingId = Binder.clearCallingIdentity();
12294        try {
12295            boolean installed = false;
12296
12297            // writer
12298            synchronized (mPackages) {
12299                pkgSetting = mSettings.mPackages.get(packageName);
12300                if (pkgSetting == null) {
12301                    return PackageManager.INSTALL_FAILED_INVALID_URI;
12302                }
12303                if (!pkgSetting.getInstalled(userId)) {
12304                    pkgSetting.setInstalled(true, userId);
12305                    pkgSetting.setHidden(false, userId);
12306                    mSettings.writePackageRestrictionsLPr(userId);
12307                    installed = true;
12308                }
12309            }
12310
12311            if (installed) {
12312                if (pkgSetting.pkg != null) {
12313                    synchronized (mInstallLock) {
12314                        // We don't need to freeze for a brand new install
12315                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
12316                    }
12317                }
12318                sendPackageAddedForUser(packageName, pkgSetting, userId);
12319            }
12320        } finally {
12321            Binder.restoreCallingIdentity(callingId);
12322        }
12323
12324        return PackageManager.INSTALL_SUCCEEDED;
12325    }
12326
12327    boolean isUserRestricted(int userId, String restrictionKey) {
12328        Bundle restrictions = sUserManager.getUserRestrictions(userId);
12329        if (restrictions.getBoolean(restrictionKey, false)) {
12330            Log.w(TAG, "User is restricted: " + restrictionKey);
12331            return true;
12332        }
12333        return false;
12334    }
12335
12336    @Override
12337    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
12338            int userId) {
12339        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
12340        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12341                true /* requireFullPermission */, true /* checkShell */,
12342                "setPackagesSuspended for user " + userId);
12343
12344        if (ArrayUtils.isEmpty(packageNames)) {
12345            return packageNames;
12346        }
12347
12348        // List of package names for whom the suspended state has changed.
12349        List<String> changedPackages = new ArrayList<>(packageNames.length);
12350        // List of package names for whom the suspended state is not set as requested in this
12351        // method.
12352        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
12353        long callingId = Binder.clearCallingIdentity();
12354        try {
12355            for (int i = 0; i < packageNames.length; i++) {
12356                String packageName = packageNames[i];
12357                boolean changed = false;
12358                final int appId;
12359                synchronized (mPackages) {
12360                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12361                    if (pkgSetting == null) {
12362                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
12363                                + "\". Skipping suspending/un-suspending.");
12364                        unactionedPackages.add(packageName);
12365                        continue;
12366                    }
12367                    appId = pkgSetting.appId;
12368                    if (pkgSetting.getSuspended(userId) != suspended) {
12369                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
12370                            unactionedPackages.add(packageName);
12371                            continue;
12372                        }
12373                        pkgSetting.setSuspended(suspended, userId);
12374                        mSettings.writePackageRestrictionsLPr(userId);
12375                        changed = true;
12376                        changedPackages.add(packageName);
12377                    }
12378                }
12379
12380                if (changed && suspended) {
12381                    killApplication(packageName, UserHandle.getUid(userId, appId),
12382                            "suspending package");
12383                }
12384            }
12385        } finally {
12386            Binder.restoreCallingIdentity(callingId);
12387        }
12388
12389        if (!changedPackages.isEmpty()) {
12390            sendPackagesSuspendedForUser(changedPackages.toArray(
12391                    new String[changedPackages.size()]), userId, suspended);
12392        }
12393
12394        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
12395    }
12396
12397    @Override
12398    public boolean isPackageSuspendedForUser(String packageName, int userId) {
12399        enforceCrossUserPermission(Binder.getCallingUid(), userId,
12400                true /* requireFullPermission */, false /* checkShell */,
12401                "isPackageSuspendedForUser for user " + userId);
12402        synchronized (mPackages) {
12403            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
12404            if (pkgSetting == null) {
12405                throw new IllegalArgumentException("Unknown target package: " + packageName);
12406            }
12407            return pkgSetting.getSuspended(userId);
12408        }
12409    }
12410
12411    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
12412        if (isPackageDeviceAdmin(packageName, userId)) {
12413            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12414                    + "\": has an active device admin");
12415            return false;
12416        }
12417
12418        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
12419        if (packageName.equals(activeLauncherPackageName)) {
12420            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12421                    + "\": contains the active launcher");
12422            return false;
12423        }
12424
12425        if (packageName.equals(mRequiredInstallerPackage)) {
12426            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12427                    + "\": required for package installation");
12428            return false;
12429        }
12430
12431        if (packageName.equals(mRequiredUninstallerPackage)) {
12432            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12433                    + "\": required for package uninstallation");
12434            return false;
12435        }
12436
12437        if (packageName.equals(mRequiredVerifierPackage)) {
12438            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12439                    + "\": required for package verification");
12440            return false;
12441        }
12442
12443        if (packageName.equals(getDefaultDialerPackageName(userId))) {
12444            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12445                    + "\": is the default dialer");
12446            return false;
12447        }
12448
12449        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12450            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12451                    + "\": protected package");
12452            return false;
12453        }
12454
12455        return true;
12456    }
12457
12458    private String getActiveLauncherPackageName(int userId) {
12459        Intent intent = new Intent(Intent.ACTION_MAIN);
12460        intent.addCategory(Intent.CATEGORY_HOME);
12461        ResolveInfo resolveInfo = resolveIntent(
12462                intent,
12463                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12464                PackageManager.MATCH_DEFAULT_ONLY,
12465                userId);
12466
12467        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12468    }
12469
12470    private String getDefaultDialerPackageName(int userId) {
12471        synchronized (mPackages) {
12472            return mSettings.getDefaultDialerPackageNameLPw(userId);
12473        }
12474    }
12475
12476    @Override
12477    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12478        mContext.enforceCallingOrSelfPermission(
12479                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12480                "Only package verification agents can verify applications");
12481
12482        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12483        final PackageVerificationResponse response = new PackageVerificationResponse(
12484                verificationCode, Binder.getCallingUid());
12485        msg.arg1 = id;
12486        msg.obj = response;
12487        mHandler.sendMessage(msg);
12488    }
12489
12490    @Override
12491    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12492            long millisecondsToDelay) {
12493        mContext.enforceCallingOrSelfPermission(
12494                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12495                "Only package verification agents can extend verification timeouts");
12496
12497        final PackageVerificationState state = mPendingVerification.get(id);
12498        final PackageVerificationResponse response = new PackageVerificationResponse(
12499                verificationCodeAtTimeout, Binder.getCallingUid());
12500
12501        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12502            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12503        }
12504        if (millisecondsToDelay < 0) {
12505            millisecondsToDelay = 0;
12506        }
12507        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12508                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12509            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12510        }
12511
12512        if ((state != null) && !state.timeoutExtended()) {
12513            state.extendTimeout();
12514
12515            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12516            msg.arg1 = id;
12517            msg.obj = response;
12518            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12519        }
12520    }
12521
12522    private void broadcastPackageVerified(int verificationId, Uri packageUri,
12523            int verificationCode, UserHandle user) {
12524        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12525        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12526        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12527        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12528        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12529
12530        mContext.sendBroadcastAsUser(intent, user,
12531                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12532    }
12533
12534    private ComponentName matchComponentForVerifier(String packageName,
12535            List<ResolveInfo> receivers) {
12536        ActivityInfo targetReceiver = null;
12537
12538        final int NR = receivers.size();
12539        for (int i = 0; i < NR; i++) {
12540            final ResolveInfo info = receivers.get(i);
12541            if (info.activityInfo == null) {
12542                continue;
12543            }
12544
12545            if (packageName.equals(info.activityInfo.packageName)) {
12546                targetReceiver = info.activityInfo;
12547                break;
12548            }
12549        }
12550
12551        if (targetReceiver == null) {
12552            return null;
12553        }
12554
12555        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12556    }
12557
12558    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12559            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12560        if (pkgInfo.verifiers.length == 0) {
12561            return null;
12562        }
12563
12564        final int N = pkgInfo.verifiers.length;
12565        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12566        for (int i = 0; i < N; i++) {
12567            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12568
12569            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12570                    receivers);
12571            if (comp == null) {
12572                continue;
12573            }
12574
12575            final int verifierUid = getUidForVerifier(verifierInfo);
12576            if (verifierUid == -1) {
12577                continue;
12578            }
12579
12580            if (DEBUG_VERIFY) {
12581                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12582                        + " with the correct signature");
12583            }
12584            sufficientVerifiers.add(comp);
12585            verificationState.addSufficientVerifier(verifierUid);
12586        }
12587
12588        return sufficientVerifiers;
12589    }
12590
12591    private int getUidForVerifier(VerifierInfo verifierInfo) {
12592        synchronized (mPackages) {
12593            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12594            if (pkg == null) {
12595                return -1;
12596            } else if (pkg.mSignatures.length != 1) {
12597                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12598                        + " has more than one signature; ignoring");
12599                return -1;
12600            }
12601
12602            /*
12603             * If the public key of the package's signature does not match
12604             * our expected public key, then this is a different package and
12605             * we should skip.
12606             */
12607
12608            final byte[] expectedPublicKey;
12609            try {
12610                final Signature verifierSig = pkg.mSignatures[0];
12611                final PublicKey publicKey = verifierSig.getPublicKey();
12612                expectedPublicKey = publicKey.getEncoded();
12613            } catch (CertificateException e) {
12614                return -1;
12615            }
12616
12617            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12618
12619            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12620                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12621                        + " does not have the expected public key; ignoring");
12622                return -1;
12623            }
12624
12625            return pkg.applicationInfo.uid;
12626        }
12627    }
12628
12629    @Override
12630    public void finishPackageInstall(int token, boolean didLaunch) {
12631        enforceSystemOrRoot("Only the system is allowed to finish installs");
12632
12633        if (DEBUG_INSTALL) {
12634            Slog.v(TAG, "BM finishing package install for " + token);
12635        }
12636        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12637
12638        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12639        mHandler.sendMessage(msg);
12640    }
12641
12642    /**
12643     * Get the verification agent timeout.
12644     *
12645     * @return verification timeout in milliseconds
12646     */
12647    private long getVerificationTimeout() {
12648        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12649                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12650                DEFAULT_VERIFICATION_TIMEOUT);
12651    }
12652
12653    /**
12654     * Get the default verification agent response code.
12655     *
12656     * @return default verification response code
12657     */
12658    private int getDefaultVerificationResponse() {
12659        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12660                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12661                DEFAULT_VERIFICATION_RESPONSE);
12662    }
12663
12664    /**
12665     * Check whether or not package verification has been enabled.
12666     *
12667     * @return true if verification should be performed
12668     */
12669    private boolean isVerificationEnabled(int userId, int installFlags) {
12670        if (!DEFAULT_VERIFY_ENABLE) {
12671            return false;
12672        }
12673        // Ephemeral apps don't get the full verification treatment
12674        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12675            if (DEBUG_EPHEMERAL) {
12676                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12677            }
12678            return false;
12679        }
12680
12681        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12682
12683        // Check if installing from ADB
12684        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12685            // Do not run verification in a test harness environment
12686            if (ActivityManager.isRunningInTestHarness()) {
12687                return false;
12688            }
12689            if (ensureVerifyAppsEnabled) {
12690                return true;
12691            }
12692            // Check if the developer does not want package verification for ADB installs
12693            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12694                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12695                return false;
12696            }
12697        }
12698
12699        if (ensureVerifyAppsEnabled) {
12700            return true;
12701        }
12702
12703        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12704                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12705    }
12706
12707    @Override
12708    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12709            throws RemoteException {
12710        mContext.enforceCallingOrSelfPermission(
12711                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12712                "Only intentfilter verification agents can verify applications");
12713
12714        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12715        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12716                Binder.getCallingUid(), verificationCode, failedDomains);
12717        msg.arg1 = id;
12718        msg.obj = response;
12719        mHandler.sendMessage(msg);
12720    }
12721
12722    @Override
12723    public int getIntentVerificationStatus(String packageName, int userId) {
12724        synchronized (mPackages) {
12725            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12726        }
12727    }
12728
12729    @Override
12730    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12731        mContext.enforceCallingOrSelfPermission(
12732                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12733
12734        boolean result = false;
12735        synchronized (mPackages) {
12736            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12737        }
12738        if (result) {
12739            scheduleWritePackageRestrictionsLocked(userId);
12740        }
12741        return result;
12742    }
12743
12744    @Override
12745    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12746            String packageName) {
12747        synchronized (mPackages) {
12748            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12749        }
12750    }
12751
12752    @Override
12753    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12754        if (TextUtils.isEmpty(packageName)) {
12755            return ParceledListSlice.emptyList();
12756        }
12757        synchronized (mPackages) {
12758            PackageParser.Package pkg = mPackages.get(packageName);
12759            if (pkg == null || pkg.activities == null) {
12760                return ParceledListSlice.emptyList();
12761            }
12762            final int count = pkg.activities.size();
12763            ArrayList<IntentFilter> result = new ArrayList<>();
12764            for (int n=0; n<count; n++) {
12765                PackageParser.Activity activity = pkg.activities.get(n);
12766                if (activity.intents != null && activity.intents.size() > 0) {
12767                    result.addAll(activity.intents);
12768                }
12769            }
12770            return new ParceledListSlice<>(result);
12771        }
12772    }
12773
12774    @Override
12775    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12776        mContext.enforceCallingOrSelfPermission(
12777                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12778
12779        synchronized (mPackages) {
12780            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12781            if (packageName != null) {
12782                result |= updateIntentVerificationStatus(packageName,
12783                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12784                        userId);
12785                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12786                        packageName, userId);
12787            }
12788            return result;
12789        }
12790    }
12791
12792    @Override
12793    public String getDefaultBrowserPackageName(int userId) {
12794        synchronized (mPackages) {
12795            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12796        }
12797    }
12798
12799    /**
12800     * Get the "allow unknown sources" setting.
12801     *
12802     * @return the current "allow unknown sources" setting
12803     */
12804    private int getUnknownSourcesSettings() {
12805        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12806                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12807                -1);
12808    }
12809
12810    @Override
12811    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12812        final int uid = Binder.getCallingUid();
12813        // writer
12814        synchronized (mPackages) {
12815            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12816            if (targetPackageSetting == null) {
12817                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12818            }
12819
12820            PackageSetting installerPackageSetting;
12821            if (installerPackageName != null) {
12822                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12823                if (installerPackageSetting == null) {
12824                    throw new IllegalArgumentException("Unknown installer package: "
12825                            + installerPackageName);
12826                }
12827            } else {
12828                installerPackageSetting = null;
12829            }
12830
12831            Signature[] callerSignature;
12832            Object obj = mSettings.getUserIdLPr(uid);
12833            if (obj != null) {
12834                if (obj instanceof SharedUserSetting) {
12835                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12836                } else if (obj instanceof PackageSetting) {
12837                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12838                } else {
12839                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12840                }
12841            } else {
12842                throw new SecurityException("Unknown calling UID: " + uid);
12843            }
12844
12845            // Verify: can't set installerPackageName to a package that is
12846            // not signed with the same cert as the caller.
12847            if (installerPackageSetting != null) {
12848                if (compareSignatures(callerSignature,
12849                        installerPackageSetting.signatures.mSignatures)
12850                        != PackageManager.SIGNATURE_MATCH) {
12851                    throw new SecurityException(
12852                            "Caller does not have same cert as new installer package "
12853                            + installerPackageName);
12854                }
12855            }
12856
12857            // Verify: if target already has an installer package, it must
12858            // be signed with the same cert as the caller.
12859            if (targetPackageSetting.installerPackageName != null) {
12860                PackageSetting setting = mSettings.mPackages.get(
12861                        targetPackageSetting.installerPackageName);
12862                // If the currently set package isn't valid, then it's always
12863                // okay to change it.
12864                if (setting != null) {
12865                    if (compareSignatures(callerSignature,
12866                            setting.signatures.mSignatures)
12867                            != PackageManager.SIGNATURE_MATCH) {
12868                        throw new SecurityException(
12869                                "Caller does not have same cert as old installer package "
12870                                + targetPackageSetting.installerPackageName);
12871                    }
12872                }
12873            }
12874
12875            // Okay!
12876            targetPackageSetting.installerPackageName = installerPackageName;
12877            if (installerPackageName != null) {
12878                mSettings.mInstallerPackages.add(installerPackageName);
12879            }
12880            scheduleWriteSettingsLocked();
12881        }
12882    }
12883
12884    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12885        // Queue up an async operation since the package installation may take a little while.
12886        mHandler.post(new Runnable() {
12887            public void run() {
12888                mHandler.removeCallbacks(this);
12889                 // Result object to be returned
12890                PackageInstalledInfo res = new PackageInstalledInfo();
12891                res.setReturnCode(currentStatus);
12892                res.uid = -1;
12893                res.pkg = null;
12894                res.removedInfo = null;
12895                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12896                    args.doPreInstall(res.returnCode);
12897                    synchronized (mInstallLock) {
12898                        installPackageTracedLI(args, res);
12899                    }
12900                    args.doPostInstall(res.returnCode, res.uid);
12901                }
12902
12903                // A restore should be performed at this point if (a) the install
12904                // succeeded, (b) the operation is not an update, and (c) the new
12905                // package has not opted out of backup participation.
12906                final boolean update = res.removedInfo != null
12907                        && res.removedInfo.removedPackage != null;
12908                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12909                boolean doRestore = !update
12910                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12911
12912                // Set up the post-install work request bookkeeping.  This will be used
12913                // and cleaned up by the post-install event handling regardless of whether
12914                // there's a restore pass performed.  Token values are >= 1.
12915                int token;
12916                if (mNextInstallToken < 0) mNextInstallToken = 1;
12917                token = mNextInstallToken++;
12918
12919                PostInstallData data = new PostInstallData(args, res);
12920                mRunningInstalls.put(token, data);
12921                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12922
12923                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12924                    // Pass responsibility to the Backup Manager.  It will perform a
12925                    // restore if appropriate, then pass responsibility back to the
12926                    // Package Manager to run the post-install observer callbacks
12927                    // and broadcasts.
12928                    IBackupManager bm = IBackupManager.Stub.asInterface(
12929                            ServiceManager.getService(Context.BACKUP_SERVICE));
12930                    if (bm != null) {
12931                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12932                                + " to BM for possible restore");
12933                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12934                        try {
12935                            // TODO: http://b/22388012
12936                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12937                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12938                            } else {
12939                                doRestore = false;
12940                            }
12941                        } catch (RemoteException e) {
12942                            // can't happen; the backup manager is local
12943                        } catch (Exception e) {
12944                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12945                            doRestore = false;
12946                        }
12947                    } else {
12948                        Slog.e(TAG, "Backup Manager not found!");
12949                        doRestore = false;
12950                    }
12951                }
12952
12953                if (!doRestore) {
12954                    // No restore possible, or the Backup Manager was mysteriously not
12955                    // available -- just fire the post-install work request directly.
12956                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12957
12958                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12959
12960                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12961                    mHandler.sendMessage(msg);
12962                }
12963            }
12964        });
12965    }
12966
12967    /**
12968     * Callback from PackageSettings whenever an app is first transitioned out of the
12969     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12970     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12971     * here whether the app is the target of an ongoing install, and only send the
12972     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12973     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12974     * handling.
12975     */
12976    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12977        // Serialize this with the rest of the install-process message chain.  In the
12978        // restore-at-install case, this Runnable will necessarily run before the
12979        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12980        // are coherent.  In the non-restore case, the app has already completed install
12981        // and been launched through some other means, so it is not in a problematic
12982        // state for observers to see the FIRST_LAUNCH signal.
12983        mHandler.post(new Runnable() {
12984            @Override
12985            public void run() {
12986                for (int i = 0; i < mRunningInstalls.size(); i++) {
12987                    final PostInstallData data = mRunningInstalls.valueAt(i);
12988                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12989                        continue;
12990                    }
12991                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12992                        // right package; but is it for the right user?
12993                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12994                            if (userId == data.res.newUsers[uIndex]) {
12995                                if (DEBUG_BACKUP) {
12996                                    Slog.i(TAG, "Package " + pkgName
12997                                            + " being restored so deferring FIRST_LAUNCH");
12998                                }
12999                                return;
13000                            }
13001                        }
13002                    }
13003                }
13004                // didn't find it, so not being restored
13005                if (DEBUG_BACKUP) {
13006                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13007                }
13008                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13009            }
13010        });
13011    }
13012
13013    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13014        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13015                installerPkg, null, userIds);
13016    }
13017
13018    private abstract class HandlerParams {
13019        private static final int MAX_RETRIES = 4;
13020
13021        /**
13022         * Number of times startCopy() has been attempted and had a non-fatal
13023         * error.
13024         */
13025        private int mRetries = 0;
13026
13027        /** User handle for the user requesting the information or installation. */
13028        private final UserHandle mUser;
13029        String traceMethod;
13030        int traceCookie;
13031
13032        HandlerParams(UserHandle user) {
13033            mUser = user;
13034        }
13035
13036        UserHandle getUser() {
13037            return mUser;
13038        }
13039
13040        HandlerParams setTraceMethod(String traceMethod) {
13041            this.traceMethod = traceMethod;
13042            return this;
13043        }
13044
13045        HandlerParams setTraceCookie(int traceCookie) {
13046            this.traceCookie = traceCookie;
13047            return this;
13048        }
13049
13050        final boolean startCopy() {
13051            boolean res;
13052            try {
13053                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
13054
13055                if (++mRetries > MAX_RETRIES) {
13056                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
13057                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
13058                    handleServiceError();
13059                    return false;
13060                } else {
13061                    handleStartCopy();
13062                    res = true;
13063                }
13064            } catch (RemoteException e) {
13065                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
13066                mHandler.sendEmptyMessage(MCS_RECONNECT);
13067                res = false;
13068            }
13069            handleReturnCode();
13070            return res;
13071        }
13072
13073        final void serviceError() {
13074            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
13075            handleServiceError();
13076            handleReturnCode();
13077        }
13078
13079        abstract void handleStartCopy() throws RemoteException;
13080        abstract void handleServiceError();
13081        abstract void handleReturnCode();
13082    }
13083
13084    class MeasureParams extends HandlerParams {
13085        private final PackageStats mStats;
13086        private boolean mSuccess;
13087
13088        private final IPackageStatsObserver mObserver;
13089
13090        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
13091            super(new UserHandle(stats.userHandle));
13092            mObserver = observer;
13093            mStats = stats;
13094        }
13095
13096        @Override
13097        public String toString() {
13098            return "MeasureParams{"
13099                + Integer.toHexString(System.identityHashCode(this))
13100                + " " + mStats.packageName + "}";
13101        }
13102
13103        @Override
13104        void handleStartCopy() throws RemoteException {
13105            synchronized (mInstallLock) {
13106                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
13107            }
13108
13109            if (mSuccess) {
13110                boolean mounted = false;
13111                try {
13112                    final String status = Environment.getExternalStorageState();
13113                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
13114                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
13115                } catch (Exception e) {
13116                }
13117
13118                if (mounted) {
13119                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
13120
13121                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
13122                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
13123
13124                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
13125                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
13126
13127                    // Always subtract cache size, since it's a subdirectory
13128                    mStats.externalDataSize -= mStats.externalCacheSize;
13129
13130                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
13131                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
13132
13133                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
13134                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
13135                }
13136            }
13137        }
13138
13139        @Override
13140        void handleReturnCode() {
13141            if (mObserver != null) {
13142                try {
13143                    mObserver.onGetStatsCompleted(mStats, mSuccess);
13144                } catch (RemoteException e) {
13145                    Slog.i(TAG, "Observer no longer exists.");
13146                }
13147            }
13148        }
13149
13150        @Override
13151        void handleServiceError() {
13152            Slog.e(TAG, "Could not measure application " + mStats.packageName
13153                            + " external storage");
13154        }
13155    }
13156
13157    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
13158            throws RemoteException {
13159        long result = 0;
13160        for (File path : paths) {
13161            result += mcs.calculateDirectorySize(path.getAbsolutePath());
13162        }
13163        return result;
13164    }
13165
13166    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
13167        for (File path : paths) {
13168            try {
13169                mcs.clearDirectory(path.getAbsolutePath());
13170            } catch (RemoteException e) {
13171            }
13172        }
13173    }
13174
13175    static class OriginInfo {
13176        /**
13177         * Location where install is coming from, before it has been
13178         * copied/renamed into place. This could be a single monolithic APK
13179         * file, or a cluster directory. This location may be untrusted.
13180         */
13181        final File file;
13182        final String cid;
13183
13184        /**
13185         * Flag indicating that {@link #file} or {@link #cid} has already been
13186         * staged, meaning downstream users don't need to defensively copy the
13187         * contents.
13188         */
13189        final boolean staged;
13190
13191        /**
13192         * Flag indicating that {@link #file} or {@link #cid} is an already
13193         * installed app that is being moved.
13194         */
13195        final boolean existing;
13196
13197        final String resolvedPath;
13198        final File resolvedFile;
13199
13200        static OriginInfo fromNothing() {
13201            return new OriginInfo(null, null, false, false);
13202        }
13203
13204        static OriginInfo fromUntrustedFile(File file) {
13205            return new OriginInfo(file, null, false, false);
13206        }
13207
13208        static OriginInfo fromExistingFile(File file) {
13209            return new OriginInfo(file, null, false, true);
13210        }
13211
13212        static OriginInfo fromStagedFile(File file) {
13213            return new OriginInfo(file, null, true, false);
13214        }
13215
13216        static OriginInfo fromStagedContainer(String cid) {
13217            return new OriginInfo(null, cid, true, false);
13218        }
13219
13220        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
13221            this.file = file;
13222            this.cid = cid;
13223            this.staged = staged;
13224            this.existing = existing;
13225
13226            if (cid != null) {
13227                resolvedPath = PackageHelper.getSdDir(cid);
13228                resolvedFile = new File(resolvedPath);
13229            } else if (file != null) {
13230                resolvedPath = file.getAbsolutePath();
13231                resolvedFile = file;
13232            } else {
13233                resolvedPath = null;
13234                resolvedFile = null;
13235            }
13236        }
13237    }
13238
13239    static class MoveInfo {
13240        final int moveId;
13241        final String fromUuid;
13242        final String toUuid;
13243        final String packageName;
13244        final String dataAppName;
13245        final int appId;
13246        final String seinfo;
13247        final int targetSdkVersion;
13248
13249        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
13250                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
13251            this.moveId = moveId;
13252            this.fromUuid = fromUuid;
13253            this.toUuid = toUuid;
13254            this.packageName = packageName;
13255            this.dataAppName = dataAppName;
13256            this.appId = appId;
13257            this.seinfo = seinfo;
13258            this.targetSdkVersion = targetSdkVersion;
13259        }
13260    }
13261
13262    static class VerificationInfo {
13263        /** A constant used to indicate that a uid value is not present. */
13264        public static final int NO_UID = -1;
13265
13266        /** URI referencing where the package was downloaded from. */
13267        final Uri originatingUri;
13268
13269        /** HTTP referrer URI associated with the originatingURI. */
13270        final Uri referrer;
13271
13272        /** UID of the application that the install request originated from. */
13273        final int originatingUid;
13274
13275        /** UID of application requesting the install */
13276        final int installerUid;
13277
13278        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
13279            this.originatingUri = originatingUri;
13280            this.referrer = referrer;
13281            this.originatingUid = originatingUid;
13282            this.installerUid = installerUid;
13283        }
13284    }
13285
13286    class InstallParams extends HandlerParams {
13287        final OriginInfo origin;
13288        final MoveInfo move;
13289        final IPackageInstallObserver2 observer;
13290        int installFlags;
13291        final String installerPackageName;
13292        final String volumeUuid;
13293        private InstallArgs mArgs;
13294        private int mRet;
13295        final String packageAbiOverride;
13296        final String[] grantedRuntimePermissions;
13297        final VerificationInfo verificationInfo;
13298        final Certificate[][] certificates;
13299
13300        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13301                int installFlags, String installerPackageName, String volumeUuid,
13302                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
13303                String[] grantedPermissions, Certificate[][] certificates) {
13304            super(user);
13305            this.origin = origin;
13306            this.move = move;
13307            this.observer = observer;
13308            this.installFlags = installFlags;
13309            this.installerPackageName = installerPackageName;
13310            this.volumeUuid = volumeUuid;
13311            this.verificationInfo = verificationInfo;
13312            this.packageAbiOverride = packageAbiOverride;
13313            this.grantedRuntimePermissions = grantedPermissions;
13314            this.certificates = certificates;
13315        }
13316
13317        @Override
13318        public String toString() {
13319            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
13320                    + " file=" + origin.file + " cid=" + origin.cid + "}";
13321        }
13322
13323        private int installLocationPolicy(PackageInfoLite pkgLite) {
13324            String packageName = pkgLite.packageName;
13325            int installLocation = pkgLite.installLocation;
13326            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13327            // reader
13328            synchronized (mPackages) {
13329                // Currently installed package which the new package is attempting to replace or
13330                // null if no such package is installed.
13331                PackageParser.Package installedPkg = mPackages.get(packageName);
13332                // Package which currently owns the data which the new package will own if installed.
13333                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
13334                // will be null whereas dataOwnerPkg will contain information about the package
13335                // which was uninstalled while keeping its data.
13336                PackageParser.Package dataOwnerPkg = installedPkg;
13337                if (dataOwnerPkg  == null) {
13338                    PackageSetting ps = mSettings.mPackages.get(packageName);
13339                    if (ps != null) {
13340                        dataOwnerPkg = ps.pkg;
13341                    }
13342                }
13343
13344                if (dataOwnerPkg != null) {
13345                    // If installed, the package will get access to data left on the device by its
13346                    // predecessor. As a security measure, this is permited only if this is not a
13347                    // version downgrade or if the predecessor package is marked as debuggable and
13348                    // a downgrade is explicitly requested.
13349                    //
13350                    // On debuggable platform builds, downgrades are permitted even for
13351                    // non-debuggable packages to make testing easier. Debuggable platform builds do
13352                    // not offer security guarantees and thus it's OK to disable some security
13353                    // mechanisms to make debugging/testing easier on those builds. However, even on
13354                    // debuggable builds downgrades of packages are permitted only if requested via
13355                    // installFlags. This is because we aim to keep the behavior of debuggable
13356                    // platform builds as close as possible to the behavior of non-debuggable
13357                    // platform builds.
13358                    final boolean downgradeRequested =
13359                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
13360                    final boolean packageDebuggable =
13361                                (dataOwnerPkg.applicationInfo.flags
13362                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
13363                    final boolean downgradePermitted =
13364                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
13365                    if (!downgradePermitted) {
13366                        try {
13367                            checkDowngrade(dataOwnerPkg, pkgLite);
13368                        } catch (PackageManagerException e) {
13369                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
13370                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
13371                        }
13372                    }
13373                }
13374
13375                if (installedPkg != null) {
13376                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13377                        // Check for updated system application.
13378                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13379                            if (onSd) {
13380                                Slog.w(TAG, "Cannot install update to system app on sdcard");
13381                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
13382                            }
13383                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13384                        } else {
13385                            if (onSd) {
13386                                // Install flag overrides everything.
13387                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13388                            }
13389                            // If current upgrade specifies particular preference
13390                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
13391                                // Application explicitly specified internal.
13392                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13393                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
13394                                // App explictly prefers external. Let policy decide
13395                            } else {
13396                                // Prefer previous location
13397                                if (isExternal(installedPkg)) {
13398                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13399                                }
13400                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
13401                            }
13402                        }
13403                    } else {
13404                        // Invalid install. Return error code
13405                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
13406                    }
13407                }
13408            }
13409            // All the special cases have been taken care of.
13410            // Return result based on recommended install location.
13411            if (onSd) {
13412                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
13413            }
13414            return pkgLite.recommendedInstallLocation;
13415        }
13416
13417        /*
13418         * Invoke remote method to get package information and install
13419         * location values. Override install location based on default
13420         * policy if needed and then create install arguments based
13421         * on the install location.
13422         */
13423        public void handleStartCopy() throws RemoteException {
13424            int ret = PackageManager.INSTALL_SUCCEEDED;
13425
13426            // If we're already staged, we've firmly committed to an install location
13427            if (origin.staged) {
13428                if (origin.file != null) {
13429                    installFlags |= PackageManager.INSTALL_INTERNAL;
13430                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13431                } else if (origin.cid != null) {
13432                    installFlags |= PackageManager.INSTALL_EXTERNAL;
13433                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
13434                } else {
13435                    throw new IllegalStateException("Invalid stage location");
13436                }
13437            }
13438
13439            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13440            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
13441            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13442            PackageInfoLite pkgLite = null;
13443
13444            if (onInt && onSd) {
13445                // Check if both bits are set.
13446                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13447                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13448            } else if (onSd && ephemeral) {
13449                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13450                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13451            } else {
13452                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13453                        packageAbiOverride);
13454
13455                if (DEBUG_EPHEMERAL && ephemeral) {
13456                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
13457                }
13458
13459                /*
13460                 * If we have too little free space, try to free cache
13461                 * before giving up.
13462                 */
13463                if (!origin.staged && pkgLite.recommendedInstallLocation
13464                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13465                    // TODO: focus freeing disk space on the target device
13466                    final StorageManager storage = StorageManager.from(mContext);
13467                    final long lowThreshold = storage.getStorageLowBytes(
13468                            Environment.getDataDirectory());
13469
13470                    final long sizeBytes = mContainerService.calculateInstalledSize(
13471                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13472
13473                    try {
13474                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
13475                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13476                                installFlags, packageAbiOverride);
13477                    } catch (InstallerException e) {
13478                        Slog.w(TAG, "Failed to free cache", e);
13479                    }
13480
13481                    /*
13482                     * The cache free must have deleted the file we
13483                     * downloaded to install.
13484                     *
13485                     * TODO: fix the "freeCache" call to not delete
13486                     *       the file we care about.
13487                     */
13488                    if (pkgLite.recommendedInstallLocation
13489                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13490                        pkgLite.recommendedInstallLocation
13491                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13492                    }
13493                }
13494            }
13495
13496            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13497                int loc = pkgLite.recommendedInstallLocation;
13498                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13499                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13500                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13501                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13502                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13503                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13504                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13505                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13506                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13507                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13508                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13509                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13510                } else {
13511                    // Override with defaults if needed.
13512                    loc = installLocationPolicy(pkgLite);
13513                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13514                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13515                    } else if (!onSd && !onInt) {
13516                        // Override install location with flags
13517                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13518                            // Set the flag to install on external media.
13519                            installFlags |= PackageManager.INSTALL_EXTERNAL;
13520                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
13521                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13522                            if (DEBUG_EPHEMERAL) {
13523                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13524                            }
13525                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13526                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13527                                    |PackageManager.INSTALL_INTERNAL);
13528                        } else {
13529                            // Make sure the flag for installing on external
13530                            // media is unset
13531                            installFlags |= PackageManager.INSTALL_INTERNAL;
13532                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13533                        }
13534                    }
13535                }
13536            }
13537
13538            final InstallArgs args = createInstallArgs(this);
13539            mArgs = args;
13540
13541            if (ret == PackageManager.INSTALL_SUCCEEDED) {
13542                // TODO: http://b/22976637
13543                // Apps installed for "all" users use the device owner to verify the app
13544                UserHandle verifierUser = getUser();
13545                if (verifierUser == UserHandle.ALL) {
13546                    verifierUser = UserHandle.SYSTEM;
13547                }
13548
13549                /*
13550                 * Determine if we have any installed package verifiers. If we
13551                 * do, then we'll defer to them to verify the packages.
13552                 */
13553                final int requiredUid = mRequiredVerifierPackage == null ? -1
13554                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13555                                verifierUser.getIdentifier());
13556                if (!origin.existing && requiredUid != -1
13557                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13558                    final Intent verification = new Intent(
13559                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13560                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13561                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13562                            PACKAGE_MIME_TYPE);
13563                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13564
13565                    // Query all live verifiers based on current user state
13566                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13567                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13568
13569                    if (DEBUG_VERIFY) {
13570                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13571                                + verification.toString() + " with " + pkgLite.verifiers.length
13572                                + " optional verifiers");
13573                    }
13574
13575                    final int verificationId = mPendingVerificationToken++;
13576
13577                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13578
13579                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13580                            installerPackageName);
13581
13582                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13583                            installFlags);
13584
13585                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13586                            pkgLite.packageName);
13587
13588                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13589                            pkgLite.versionCode);
13590
13591                    if (verificationInfo != null) {
13592                        if (verificationInfo.originatingUri != null) {
13593                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13594                                    verificationInfo.originatingUri);
13595                        }
13596                        if (verificationInfo.referrer != null) {
13597                            verification.putExtra(Intent.EXTRA_REFERRER,
13598                                    verificationInfo.referrer);
13599                        }
13600                        if (verificationInfo.originatingUid >= 0) {
13601                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13602                                    verificationInfo.originatingUid);
13603                        }
13604                        if (verificationInfo.installerUid >= 0) {
13605                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13606                                    verificationInfo.installerUid);
13607                        }
13608                    }
13609
13610                    final PackageVerificationState verificationState = new PackageVerificationState(
13611                            requiredUid, args);
13612
13613                    mPendingVerification.append(verificationId, verificationState);
13614
13615                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13616                            receivers, verificationState);
13617
13618                    /*
13619                     * If any sufficient verifiers were listed in the package
13620                     * manifest, attempt to ask them.
13621                     */
13622                    if (sufficientVerifiers != null) {
13623                        final int N = sufficientVerifiers.size();
13624                        if (N == 0) {
13625                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13626                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13627                        } else {
13628                            for (int i = 0; i < N; i++) {
13629                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13630
13631                                final Intent sufficientIntent = new Intent(verification);
13632                                sufficientIntent.setComponent(verifierComponent);
13633                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13634                            }
13635                        }
13636                    }
13637
13638                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13639                            mRequiredVerifierPackage, receivers);
13640                    if (ret == PackageManager.INSTALL_SUCCEEDED
13641                            && mRequiredVerifierPackage != null) {
13642                        Trace.asyncTraceBegin(
13643                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13644                        /*
13645                         * Send the intent to the required verification agent,
13646                         * but only start the verification timeout after the
13647                         * target BroadcastReceivers have run.
13648                         */
13649                        verification.setComponent(requiredVerifierComponent);
13650                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13651                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13652                                new BroadcastReceiver() {
13653                                    @Override
13654                                    public void onReceive(Context context, Intent intent) {
13655                                        final Message msg = mHandler
13656                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13657                                        msg.arg1 = verificationId;
13658                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13659                                    }
13660                                }, null, 0, null, null);
13661
13662                        /*
13663                         * We don't want the copy to proceed until verification
13664                         * succeeds, so null out this field.
13665                         */
13666                        mArgs = null;
13667                    }
13668                } else {
13669                    /*
13670                     * No package verification is enabled, so immediately start
13671                     * the remote call to initiate copy using temporary file.
13672                     */
13673                    ret = args.copyApk(mContainerService, true);
13674                }
13675            }
13676
13677            mRet = ret;
13678        }
13679
13680        @Override
13681        void handleReturnCode() {
13682            // If mArgs is null, then MCS couldn't be reached. When it
13683            // reconnects, it will try again to install. At that point, this
13684            // will succeed.
13685            if (mArgs != null) {
13686                processPendingInstall(mArgs, mRet);
13687            }
13688        }
13689
13690        @Override
13691        void handleServiceError() {
13692            mArgs = createInstallArgs(this);
13693            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13694        }
13695
13696        public boolean isForwardLocked() {
13697            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13698        }
13699    }
13700
13701    /**
13702     * Used during creation of InstallArgs
13703     *
13704     * @param installFlags package installation flags
13705     * @return true if should be installed on external storage
13706     */
13707    private static boolean installOnExternalAsec(int installFlags) {
13708        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13709            return false;
13710        }
13711        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13712            return true;
13713        }
13714        return false;
13715    }
13716
13717    /**
13718     * Used during creation of InstallArgs
13719     *
13720     * @param installFlags package installation flags
13721     * @return true if should be installed as forward locked
13722     */
13723    private static boolean installForwardLocked(int installFlags) {
13724        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13725    }
13726
13727    private InstallArgs createInstallArgs(InstallParams params) {
13728        if (params.move != null) {
13729            return new MoveInstallArgs(params);
13730        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13731            return new AsecInstallArgs(params);
13732        } else {
13733            return new FileInstallArgs(params);
13734        }
13735    }
13736
13737    /**
13738     * Create args that describe an existing installed package. Typically used
13739     * when cleaning up old installs, or used as a move source.
13740     */
13741    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13742            String resourcePath, String[] instructionSets) {
13743        final boolean isInAsec;
13744        if (installOnExternalAsec(installFlags)) {
13745            /* Apps on SD card are always in ASEC containers. */
13746            isInAsec = true;
13747        } else if (installForwardLocked(installFlags)
13748                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13749            /*
13750             * Forward-locked apps are only in ASEC containers if they're the
13751             * new style
13752             */
13753            isInAsec = true;
13754        } else {
13755            isInAsec = false;
13756        }
13757
13758        if (isInAsec) {
13759            return new AsecInstallArgs(codePath, instructionSets,
13760                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13761        } else {
13762            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13763        }
13764    }
13765
13766    static abstract class InstallArgs {
13767        /** @see InstallParams#origin */
13768        final OriginInfo origin;
13769        /** @see InstallParams#move */
13770        final MoveInfo move;
13771
13772        final IPackageInstallObserver2 observer;
13773        // Always refers to PackageManager flags only
13774        final int installFlags;
13775        final String installerPackageName;
13776        final String volumeUuid;
13777        final UserHandle user;
13778        final String abiOverride;
13779        final String[] installGrantPermissions;
13780        /** If non-null, drop an async trace when the install completes */
13781        final String traceMethod;
13782        final int traceCookie;
13783        final Certificate[][] certificates;
13784
13785        // The list of instruction sets supported by this app. This is currently
13786        // only used during the rmdex() phase to clean up resources. We can get rid of this
13787        // if we move dex files under the common app path.
13788        /* nullable */ String[] instructionSets;
13789
13790        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13791                int installFlags, String installerPackageName, String volumeUuid,
13792                UserHandle user, String[] instructionSets,
13793                String abiOverride, String[] installGrantPermissions,
13794                String traceMethod, int traceCookie, Certificate[][] certificates) {
13795            this.origin = origin;
13796            this.move = move;
13797            this.installFlags = installFlags;
13798            this.observer = observer;
13799            this.installerPackageName = installerPackageName;
13800            this.volumeUuid = volumeUuid;
13801            this.user = user;
13802            this.instructionSets = instructionSets;
13803            this.abiOverride = abiOverride;
13804            this.installGrantPermissions = installGrantPermissions;
13805            this.traceMethod = traceMethod;
13806            this.traceCookie = traceCookie;
13807            this.certificates = certificates;
13808        }
13809
13810        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13811        abstract int doPreInstall(int status);
13812
13813        /**
13814         * Rename package into final resting place. All paths on the given
13815         * scanned package should be updated to reflect the rename.
13816         */
13817        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13818        abstract int doPostInstall(int status, int uid);
13819
13820        /** @see PackageSettingBase#codePathString */
13821        abstract String getCodePath();
13822        /** @see PackageSettingBase#resourcePathString */
13823        abstract String getResourcePath();
13824
13825        // Need installer lock especially for dex file removal.
13826        abstract void cleanUpResourcesLI();
13827        abstract boolean doPostDeleteLI(boolean delete);
13828
13829        /**
13830         * Called before the source arguments are copied. This is used mostly
13831         * for MoveParams when it needs to read the source file to put it in the
13832         * destination.
13833         */
13834        int doPreCopy() {
13835            return PackageManager.INSTALL_SUCCEEDED;
13836        }
13837
13838        /**
13839         * Called after the source arguments are copied. This is used mostly for
13840         * MoveParams when it needs to read the source file to put it in the
13841         * destination.
13842         */
13843        int doPostCopy(int uid) {
13844            return PackageManager.INSTALL_SUCCEEDED;
13845        }
13846
13847        protected boolean isFwdLocked() {
13848            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13849        }
13850
13851        protected boolean isExternalAsec() {
13852            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13853        }
13854
13855        protected boolean isEphemeral() {
13856            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13857        }
13858
13859        UserHandle getUser() {
13860            return user;
13861        }
13862    }
13863
13864    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13865        if (!allCodePaths.isEmpty()) {
13866            if (instructionSets == null) {
13867                throw new IllegalStateException("instructionSet == null");
13868            }
13869            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13870            for (String codePath : allCodePaths) {
13871                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13872                    try {
13873                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13874                    } catch (InstallerException ignored) {
13875                    }
13876                }
13877            }
13878        }
13879    }
13880
13881    /**
13882     * Logic to handle installation of non-ASEC applications, including copying
13883     * and renaming logic.
13884     */
13885    class FileInstallArgs extends InstallArgs {
13886        private File codeFile;
13887        private File resourceFile;
13888
13889        // Example topology:
13890        // /data/app/com.example/base.apk
13891        // /data/app/com.example/split_foo.apk
13892        // /data/app/com.example/lib/arm/libfoo.so
13893        // /data/app/com.example/lib/arm64/libfoo.so
13894        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13895
13896        /** New install */
13897        FileInstallArgs(InstallParams params) {
13898            super(params.origin, params.move, params.observer, params.installFlags,
13899                    params.installerPackageName, params.volumeUuid,
13900                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13901                    params.grantedRuntimePermissions,
13902                    params.traceMethod, params.traceCookie, params.certificates);
13903            if (isFwdLocked()) {
13904                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13905            }
13906        }
13907
13908        /** Existing install */
13909        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13910            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13911                    null, null, null, 0, null /*certificates*/);
13912            this.codeFile = (codePath != null) ? new File(codePath) : null;
13913            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13914        }
13915
13916        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13917            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13918            try {
13919                return doCopyApk(imcs, temp);
13920            } finally {
13921                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13922            }
13923        }
13924
13925        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13926            if (origin.staged) {
13927                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13928                codeFile = origin.file;
13929                resourceFile = origin.file;
13930                return PackageManager.INSTALL_SUCCEEDED;
13931            }
13932
13933            try {
13934                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13935                final File tempDir =
13936                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13937                codeFile = tempDir;
13938                resourceFile = tempDir;
13939            } catch (IOException e) {
13940                Slog.w(TAG, "Failed to create copy file: " + e);
13941                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13942            }
13943
13944            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13945                @Override
13946                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13947                    if (!FileUtils.isValidExtFilename(name)) {
13948                        throw new IllegalArgumentException("Invalid filename: " + name);
13949                    }
13950                    try {
13951                        final File file = new File(codeFile, name);
13952                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13953                                O_RDWR | O_CREAT, 0644);
13954                        Os.chmod(file.getAbsolutePath(), 0644);
13955                        return new ParcelFileDescriptor(fd);
13956                    } catch (ErrnoException e) {
13957                        throw new RemoteException("Failed to open: " + e.getMessage());
13958                    }
13959                }
13960            };
13961
13962            int ret = PackageManager.INSTALL_SUCCEEDED;
13963            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13964            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13965                Slog.e(TAG, "Failed to copy package");
13966                return ret;
13967            }
13968
13969            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13970            NativeLibraryHelper.Handle handle = null;
13971            try {
13972                handle = NativeLibraryHelper.Handle.create(codeFile);
13973                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13974                        abiOverride);
13975            } catch (IOException e) {
13976                Slog.e(TAG, "Copying native libraries failed", e);
13977                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13978            } finally {
13979                IoUtils.closeQuietly(handle);
13980            }
13981
13982            return ret;
13983        }
13984
13985        int doPreInstall(int status) {
13986            if (status != PackageManager.INSTALL_SUCCEEDED) {
13987                cleanUp();
13988            }
13989            return status;
13990        }
13991
13992        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13993            if (status != PackageManager.INSTALL_SUCCEEDED) {
13994                cleanUp();
13995                return false;
13996            }
13997
13998            final File targetDir = codeFile.getParentFile();
13999            final File beforeCodeFile = codeFile;
14000            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14001
14002            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14003            try {
14004                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14005            } catch (ErrnoException e) {
14006                Slog.w(TAG, "Failed to rename", e);
14007                return false;
14008            }
14009
14010            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14011                Slog.w(TAG, "Failed to restorecon");
14012                return false;
14013            }
14014
14015            // Reflect the rename internally
14016            codeFile = afterCodeFile;
14017            resourceFile = afterCodeFile;
14018
14019            // Reflect the rename in scanned details
14020            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14021            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14022                    afterCodeFile, pkg.baseCodePath));
14023            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14024                    afterCodeFile, pkg.splitCodePaths));
14025
14026            // Reflect the rename in app info
14027            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14028            pkg.setApplicationInfoCodePath(pkg.codePath);
14029            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14030            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14031            pkg.setApplicationInfoResourcePath(pkg.codePath);
14032            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14033            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14034
14035            return true;
14036        }
14037
14038        int doPostInstall(int status, int uid) {
14039            if (status != PackageManager.INSTALL_SUCCEEDED) {
14040                cleanUp();
14041            }
14042            return status;
14043        }
14044
14045        @Override
14046        String getCodePath() {
14047            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14048        }
14049
14050        @Override
14051        String getResourcePath() {
14052            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14053        }
14054
14055        private boolean cleanUp() {
14056            if (codeFile == null || !codeFile.exists()) {
14057                return false;
14058            }
14059
14060            removeCodePathLI(codeFile);
14061
14062            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
14063                resourceFile.delete();
14064            }
14065
14066            return true;
14067        }
14068
14069        void cleanUpResourcesLI() {
14070            // Try enumerating all code paths before deleting
14071            List<String> allCodePaths = Collections.EMPTY_LIST;
14072            if (codeFile != null && codeFile.exists()) {
14073                try {
14074                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14075                    allCodePaths = pkg.getAllCodePaths();
14076                } catch (PackageParserException e) {
14077                    // Ignored; we tried our best
14078                }
14079            }
14080
14081            cleanUp();
14082            removeDexFiles(allCodePaths, instructionSets);
14083        }
14084
14085        boolean doPostDeleteLI(boolean delete) {
14086            // XXX err, shouldn't we respect the delete flag?
14087            cleanUpResourcesLI();
14088            return true;
14089        }
14090    }
14091
14092    private boolean isAsecExternal(String cid) {
14093        final String asecPath = PackageHelper.getSdFilesystem(cid);
14094        return !asecPath.startsWith(mAsecInternalPath);
14095    }
14096
14097    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
14098            PackageManagerException {
14099        if (copyRet < 0) {
14100            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
14101                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
14102                throw new PackageManagerException(copyRet, message);
14103            }
14104        }
14105    }
14106
14107    /**
14108     * Extract the StorageManagerService "container ID" from the full code path of an
14109     * .apk.
14110     */
14111    static String cidFromCodePath(String fullCodePath) {
14112        int eidx = fullCodePath.lastIndexOf("/");
14113        String subStr1 = fullCodePath.substring(0, eidx);
14114        int sidx = subStr1.lastIndexOf("/");
14115        return subStr1.substring(sidx+1, eidx);
14116    }
14117
14118    /**
14119     * Logic to handle installation of ASEC applications, including copying and
14120     * renaming logic.
14121     */
14122    class AsecInstallArgs extends InstallArgs {
14123        static final String RES_FILE_NAME = "pkg.apk";
14124        static final String PUBLIC_RES_FILE_NAME = "res.zip";
14125
14126        String cid;
14127        String packagePath;
14128        String resourcePath;
14129
14130        /** New install */
14131        AsecInstallArgs(InstallParams params) {
14132            super(params.origin, params.move, params.observer, params.installFlags,
14133                    params.installerPackageName, params.volumeUuid,
14134                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14135                    params.grantedRuntimePermissions,
14136                    params.traceMethod, params.traceCookie, params.certificates);
14137        }
14138
14139        /** Existing install */
14140        AsecInstallArgs(String fullCodePath, String[] instructionSets,
14141                        boolean isExternal, boolean isForwardLocked) {
14142            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
14143              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14144                    instructionSets, null, null, null, 0, null /*certificates*/);
14145            // Hackily pretend we're still looking at a full code path
14146            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
14147                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
14148            }
14149
14150            // Extract cid from fullCodePath
14151            int eidx = fullCodePath.lastIndexOf("/");
14152            String subStr1 = fullCodePath.substring(0, eidx);
14153            int sidx = subStr1.lastIndexOf("/");
14154            cid = subStr1.substring(sidx+1, eidx);
14155            setMountPath(subStr1);
14156        }
14157
14158        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
14159            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
14160              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
14161                    instructionSets, null, null, null, 0, null /*certificates*/);
14162            this.cid = cid;
14163            setMountPath(PackageHelper.getSdDir(cid));
14164        }
14165
14166        void createCopyFile() {
14167            cid = mInstallerService.allocateExternalStageCidLegacy();
14168        }
14169
14170        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14171            if (origin.staged && origin.cid != null) {
14172                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
14173                cid = origin.cid;
14174                setMountPath(PackageHelper.getSdDir(cid));
14175                return PackageManager.INSTALL_SUCCEEDED;
14176            }
14177
14178            if (temp) {
14179                createCopyFile();
14180            } else {
14181                /*
14182                 * Pre-emptively destroy the container since it's destroyed if
14183                 * copying fails due to it existing anyway.
14184                 */
14185                PackageHelper.destroySdDir(cid);
14186            }
14187
14188            final String newMountPath = imcs.copyPackageToContainer(
14189                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
14190                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
14191
14192            if (newMountPath != null) {
14193                setMountPath(newMountPath);
14194                return PackageManager.INSTALL_SUCCEEDED;
14195            } else {
14196                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14197            }
14198        }
14199
14200        @Override
14201        String getCodePath() {
14202            return packagePath;
14203        }
14204
14205        @Override
14206        String getResourcePath() {
14207            return resourcePath;
14208        }
14209
14210        int doPreInstall(int status) {
14211            if (status != PackageManager.INSTALL_SUCCEEDED) {
14212                // Destroy container
14213                PackageHelper.destroySdDir(cid);
14214            } else {
14215                boolean mounted = PackageHelper.isContainerMounted(cid);
14216                if (!mounted) {
14217                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
14218                            Process.SYSTEM_UID);
14219                    if (newMountPath != null) {
14220                        setMountPath(newMountPath);
14221                    } else {
14222                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14223                    }
14224                }
14225            }
14226            return status;
14227        }
14228
14229        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14230            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
14231            String newMountPath = null;
14232            if (PackageHelper.isContainerMounted(cid)) {
14233                // Unmount the container
14234                if (!PackageHelper.unMountSdDir(cid)) {
14235                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
14236                    return false;
14237                }
14238            }
14239            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14240                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
14241                        " which might be stale. Will try to clean up.");
14242                // Clean up the stale container and proceed to recreate.
14243                if (!PackageHelper.destroySdDir(newCacheId)) {
14244                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
14245                    return false;
14246                }
14247                // Successfully cleaned up stale container. Try to rename again.
14248                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
14249                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
14250                            + " inspite of cleaning it up.");
14251                    return false;
14252                }
14253            }
14254            if (!PackageHelper.isContainerMounted(newCacheId)) {
14255                Slog.w(TAG, "Mounting container " + newCacheId);
14256                newMountPath = PackageHelper.mountSdDir(newCacheId,
14257                        getEncryptKey(), Process.SYSTEM_UID);
14258            } else {
14259                newMountPath = PackageHelper.getSdDir(newCacheId);
14260            }
14261            if (newMountPath == null) {
14262                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
14263                return false;
14264            }
14265            Log.i(TAG, "Succesfully renamed " + cid +
14266                    " to " + newCacheId +
14267                    " at new path: " + newMountPath);
14268            cid = newCacheId;
14269
14270            final File beforeCodeFile = new File(packagePath);
14271            setMountPath(newMountPath);
14272            final File afterCodeFile = new File(packagePath);
14273
14274            // Reflect the rename in scanned details
14275            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14276            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14277                    afterCodeFile, pkg.baseCodePath));
14278            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14279                    afterCodeFile, pkg.splitCodePaths));
14280
14281            // Reflect the rename in app info
14282            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14283            pkg.setApplicationInfoCodePath(pkg.codePath);
14284            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14285            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14286            pkg.setApplicationInfoResourcePath(pkg.codePath);
14287            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14288            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14289
14290            return true;
14291        }
14292
14293        private void setMountPath(String mountPath) {
14294            final File mountFile = new File(mountPath);
14295
14296            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
14297            if (monolithicFile.exists()) {
14298                packagePath = monolithicFile.getAbsolutePath();
14299                if (isFwdLocked()) {
14300                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
14301                } else {
14302                    resourcePath = packagePath;
14303                }
14304            } else {
14305                packagePath = mountFile.getAbsolutePath();
14306                resourcePath = packagePath;
14307            }
14308        }
14309
14310        int doPostInstall(int status, int uid) {
14311            if (status != PackageManager.INSTALL_SUCCEEDED) {
14312                cleanUp();
14313            } else {
14314                final int groupOwner;
14315                final String protectedFile;
14316                if (isFwdLocked()) {
14317                    groupOwner = UserHandle.getSharedAppGid(uid);
14318                    protectedFile = RES_FILE_NAME;
14319                } else {
14320                    groupOwner = -1;
14321                    protectedFile = null;
14322                }
14323
14324                if (uid < Process.FIRST_APPLICATION_UID
14325                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
14326                    Slog.e(TAG, "Failed to finalize " + cid);
14327                    PackageHelper.destroySdDir(cid);
14328                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14329                }
14330
14331                boolean mounted = PackageHelper.isContainerMounted(cid);
14332                if (!mounted) {
14333                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
14334                }
14335            }
14336            return status;
14337        }
14338
14339        private void cleanUp() {
14340            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
14341
14342            // Destroy secure container
14343            PackageHelper.destroySdDir(cid);
14344        }
14345
14346        private List<String> getAllCodePaths() {
14347            final File codeFile = new File(getCodePath());
14348            if (codeFile != null && codeFile.exists()) {
14349                try {
14350                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
14351                    return pkg.getAllCodePaths();
14352                } catch (PackageParserException e) {
14353                    // Ignored; we tried our best
14354                }
14355            }
14356            return Collections.EMPTY_LIST;
14357        }
14358
14359        void cleanUpResourcesLI() {
14360            // Enumerate all code paths before deleting
14361            cleanUpResourcesLI(getAllCodePaths());
14362        }
14363
14364        private void cleanUpResourcesLI(List<String> allCodePaths) {
14365            cleanUp();
14366            removeDexFiles(allCodePaths, instructionSets);
14367        }
14368
14369        String getPackageName() {
14370            return getAsecPackageName(cid);
14371        }
14372
14373        boolean doPostDeleteLI(boolean delete) {
14374            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
14375            final List<String> allCodePaths = getAllCodePaths();
14376            boolean mounted = PackageHelper.isContainerMounted(cid);
14377            if (mounted) {
14378                // Unmount first
14379                if (PackageHelper.unMountSdDir(cid)) {
14380                    mounted = false;
14381                }
14382            }
14383            if (!mounted && delete) {
14384                cleanUpResourcesLI(allCodePaths);
14385            }
14386            return !mounted;
14387        }
14388
14389        @Override
14390        int doPreCopy() {
14391            if (isFwdLocked()) {
14392                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
14393                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
14394                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14395                }
14396            }
14397
14398            return PackageManager.INSTALL_SUCCEEDED;
14399        }
14400
14401        @Override
14402        int doPostCopy(int uid) {
14403            if (isFwdLocked()) {
14404                if (uid < Process.FIRST_APPLICATION_UID
14405                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
14406                                RES_FILE_NAME)) {
14407                    Slog.e(TAG, "Failed to finalize " + cid);
14408                    PackageHelper.destroySdDir(cid);
14409                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14410                }
14411            }
14412
14413            return PackageManager.INSTALL_SUCCEEDED;
14414        }
14415    }
14416
14417    /**
14418     * Logic to handle movement of existing installed applications.
14419     */
14420    class MoveInstallArgs extends InstallArgs {
14421        private File codeFile;
14422        private File resourceFile;
14423
14424        /** New install */
14425        MoveInstallArgs(InstallParams params) {
14426            super(params.origin, params.move, params.observer, params.installFlags,
14427                    params.installerPackageName, params.volumeUuid,
14428                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
14429                    params.grantedRuntimePermissions,
14430                    params.traceMethod, params.traceCookie, params.certificates);
14431        }
14432
14433        int copyApk(IMediaContainerService imcs, boolean temp) {
14434            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
14435                    + move.fromUuid + " to " + move.toUuid);
14436            synchronized (mInstaller) {
14437                try {
14438                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
14439                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
14440                } catch (InstallerException e) {
14441                    Slog.w(TAG, "Failed to move app", e);
14442                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14443                }
14444            }
14445
14446            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14447            resourceFile = codeFile;
14448            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14449
14450            return PackageManager.INSTALL_SUCCEEDED;
14451        }
14452
14453        int doPreInstall(int status) {
14454            if (status != PackageManager.INSTALL_SUCCEEDED) {
14455                cleanUp(move.toUuid);
14456            }
14457            return status;
14458        }
14459
14460        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14461            if (status != PackageManager.INSTALL_SUCCEEDED) {
14462                cleanUp(move.toUuid);
14463                return false;
14464            }
14465
14466            // Reflect the move in app info
14467            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14468            pkg.setApplicationInfoCodePath(pkg.codePath);
14469            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14470            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14471            pkg.setApplicationInfoResourcePath(pkg.codePath);
14472            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14473            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14474
14475            return true;
14476        }
14477
14478        int doPostInstall(int status, int uid) {
14479            if (status == PackageManager.INSTALL_SUCCEEDED) {
14480                cleanUp(move.fromUuid);
14481            } else {
14482                cleanUp(move.toUuid);
14483            }
14484            return status;
14485        }
14486
14487        @Override
14488        String getCodePath() {
14489            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14490        }
14491
14492        @Override
14493        String getResourcePath() {
14494            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14495        }
14496
14497        private boolean cleanUp(String volumeUuid) {
14498            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14499                    move.dataAppName);
14500            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14501            final int[] userIds = sUserManager.getUserIds();
14502            synchronized (mInstallLock) {
14503                // Clean up both app data and code
14504                // All package moves are frozen until finished
14505                for (int userId : userIds) {
14506                    try {
14507                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14508                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14509                    } catch (InstallerException e) {
14510                        Slog.w(TAG, String.valueOf(e));
14511                    }
14512                }
14513                removeCodePathLI(codeFile);
14514            }
14515            return true;
14516        }
14517
14518        void cleanUpResourcesLI() {
14519            throw new UnsupportedOperationException();
14520        }
14521
14522        boolean doPostDeleteLI(boolean delete) {
14523            throw new UnsupportedOperationException();
14524        }
14525    }
14526
14527    static String getAsecPackageName(String packageCid) {
14528        int idx = packageCid.lastIndexOf("-");
14529        if (idx == -1) {
14530            return packageCid;
14531        }
14532        return packageCid.substring(0, idx);
14533    }
14534
14535    // Utility method used to create code paths based on package name and available index.
14536    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14537        String idxStr = "";
14538        int idx = 1;
14539        // Fall back to default value of idx=1 if prefix is not
14540        // part of oldCodePath
14541        if (oldCodePath != null) {
14542            String subStr = oldCodePath;
14543            // Drop the suffix right away
14544            if (suffix != null && subStr.endsWith(suffix)) {
14545                subStr = subStr.substring(0, subStr.length() - suffix.length());
14546            }
14547            // If oldCodePath already contains prefix find out the
14548            // ending index to either increment or decrement.
14549            int sidx = subStr.lastIndexOf(prefix);
14550            if (sidx != -1) {
14551                subStr = subStr.substring(sidx + prefix.length());
14552                if (subStr != null) {
14553                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14554                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14555                    }
14556                    try {
14557                        idx = Integer.parseInt(subStr);
14558                        if (idx <= 1) {
14559                            idx++;
14560                        } else {
14561                            idx--;
14562                        }
14563                    } catch(NumberFormatException e) {
14564                    }
14565                }
14566            }
14567        }
14568        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14569        return prefix + idxStr;
14570    }
14571
14572    private File getNextCodePath(File targetDir, String packageName) {
14573        File result;
14574        SecureRandom random = new SecureRandom();
14575        byte[] bytes = new byte[16];
14576        do {
14577            random.nextBytes(bytes);
14578            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
14579            result = new File(targetDir, packageName + "-" + suffix);
14580        } while (result.exists());
14581        return result;
14582    }
14583
14584    // Utility method that returns the relative package path with respect
14585    // to the installation directory. Like say for /data/data/com.test-1.apk
14586    // string com.test-1 is returned.
14587    static String deriveCodePathName(String codePath) {
14588        if (codePath == null) {
14589            return null;
14590        }
14591        final File codeFile = new File(codePath);
14592        final String name = codeFile.getName();
14593        if (codeFile.isDirectory()) {
14594            return name;
14595        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14596            final int lastDot = name.lastIndexOf('.');
14597            return name.substring(0, lastDot);
14598        } else {
14599            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14600            return null;
14601        }
14602    }
14603
14604    static class PackageInstalledInfo {
14605        String name;
14606        int uid;
14607        // The set of users that originally had this package installed.
14608        int[] origUsers;
14609        // The set of users that now have this package installed.
14610        int[] newUsers;
14611        PackageParser.Package pkg;
14612        int returnCode;
14613        String returnMsg;
14614        PackageRemovedInfo removedInfo;
14615        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14616
14617        public void setError(int code, String msg) {
14618            setReturnCode(code);
14619            setReturnMessage(msg);
14620            Slog.w(TAG, msg);
14621        }
14622
14623        public void setError(String msg, PackageParserException e) {
14624            setReturnCode(e.error);
14625            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14626            Slog.w(TAG, msg, e);
14627        }
14628
14629        public void setError(String msg, PackageManagerException e) {
14630            returnCode = e.error;
14631            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14632            Slog.w(TAG, msg, e);
14633        }
14634
14635        public void setReturnCode(int returnCode) {
14636            this.returnCode = returnCode;
14637            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14638            for (int i = 0; i < childCount; i++) {
14639                addedChildPackages.valueAt(i).returnCode = returnCode;
14640            }
14641        }
14642
14643        private void setReturnMessage(String returnMsg) {
14644            this.returnMsg = returnMsg;
14645            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14646            for (int i = 0; i < childCount; i++) {
14647                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14648            }
14649        }
14650
14651        // In some error cases we want to convey more info back to the observer
14652        String origPackage;
14653        String origPermission;
14654    }
14655
14656    /*
14657     * Install a non-existing package.
14658     */
14659    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14660            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14661            PackageInstalledInfo res) {
14662        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14663
14664        // Remember this for later, in case we need to rollback this install
14665        String pkgName = pkg.packageName;
14666
14667        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14668
14669        synchronized(mPackages) {
14670            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
14671            if (renamedPackage != null) {
14672                // A package with the same name is already installed, though
14673                // it has been renamed to an older name.  The package we
14674                // are trying to install should be installed as an update to
14675                // the existing one, but that has not been requested, so bail.
14676                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14677                        + " without first uninstalling package running as "
14678                        + renamedPackage);
14679                return;
14680            }
14681            if (mPackages.containsKey(pkgName)) {
14682                // Don't allow installation over an existing package with the same name.
14683                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14684                        + " without first uninstalling.");
14685                return;
14686            }
14687        }
14688
14689        try {
14690            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14691                    System.currentTimeMillis(), user);
14692
14693            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14694
14695            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14696                prepareAppDataAfterInstallLIF(newPackage);
14697
14698            } else {
14699                // Remove package from internal structures, but keep around any
14700                // data that might have already existed
14701                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14702                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14703            }
14704        } catch (PackageManagerException e) {
14705            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14706        }
14707
14708        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14709    }
14710
14711    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14712        // Can't rotate keys during boot or if sharedUser.
14713        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14714                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14715            return false;
14716        }
14717        // app is using upgradeKeySets; make sure all are valid
14718        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14719        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14720        for (int i = 0; i < upgradeKeySets.length; i++) {
14721            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14722                Slog.wtf(TAG, "Package "
14723                         + (oldPs.name != null ? oldPs.name : "<null>")
14724                         + " contains upgrade-key-set reference to unknown key-set: "
14725                         + upgradeKeySets[i]
14726                         + " reverting to signatures check.");
14727                return false;
14728            }
14729        }
14730        return true;
14731    }
14732
14733    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14734        // Upgrade keysets are being used.  Determine if new package has a superset of the
14735        // required keys.
14736        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14737        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14738        for (int i = 0; i < upgradeKeySets.length; i++) {
14739            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14740            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14741                return true;
14742            }
14743        }
14744        return false;
14745    }
14746
14747    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14748        try (DigestInputStream digestStream =
14749                new DigestInputStream(new FileInputStream(file), digest)) {
14750            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14751        }
14752    }
14753
14754    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14755            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14756        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14757
14758        final PackageParser.Package oldPackage;
14759        final String pkgName = pkg.packageName;
14760        final int[] allUsers;
14761        final int[] installedUsers;
14762
14763        synchronized(mPackages) {
14764            oldPackage = mPackages.get(pkgName);
14765            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14766
14767            // don't allow upgrade to target a release SDK from a pre-release SDK
14768            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14769                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14770            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14771                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14772            if (oldTargetsPreRelease
14773                    && !newTargetsPreRelease
14774                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14775                Slog.w(TAG, "Can't install package targeting released sdk");
14776                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14777                return;
14778            }
14779
14780            // don't allow an upgrade from full to ephemeral
14781            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14782            if (isEphemeral && !oldIsEphemeral) {
14783                // can't downgrade from full to ephemeral
14784                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14785                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14786                return;
14787            }
14788
14789            // verify signatures are valid
14790            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14791            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14792                if (!checkUpgradeKeySetLP(ps, pkg)) {
14793                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14794                            "New package not signed by keys specified by upgrade-keysets: "
14795                                    + pkgName);
14796                    return;
14797                }
14798            } else {
14799                // default to original signature matching
14800                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14801                        != PackageManager.SIGNATURE_MATCH) {
14802                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14803                            "New package has a different signature: " + pkgName);
14804                    return;
14805                }
14806            }
14807
14808            // don't allow a system upgrade unless the upgrade hash matches
14809            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14810                byte[] digestBytes = null;
14811                try {
14812                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14813                    updateDigest(digest, new File(pkg.baseCodePath));
14814                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14815                        for (String path : pkg.splitCodePaths) {
14816                            updateDigest(digest, new File(path));
14817                        }
14818                    }
14819                    digestBytes = digest.digest();
14820                } catch (NoSuchAlgorithmException | IOException e) {
14821                    res.setError(INSTALL_FAILED_INVALID_APK,
14822                            "Could not compute hash: " + pkgName);
14823                    return;
14824                }
14825                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14826                    res.setError(INSTALL_FAILED_INVALID_APK,
14827                            "New package fails restrict-update check: " + pkgName);
14828                    return;
14829                }
14830                // retain upgrade restriction
14831                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14832            }
14833
14834            // Check for shared user id changes
14835            String invalidPackageName =
14836                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14837            if (invalidPackageName != null) {
14838                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14839                        "Package " + invalidPackageName + " tried to change user "
14840                                + oldPackage.mSharedUserId);
14841                return;
14842            }
14843
14844            // In case of rollback, remember per-user/profile install state
14845            allUsers = sUserManager.getUserIds();
14846            installedUsers = ps.queryInstalledUsers(allUsers, true);
14847        }
14848
14849        // Update what is removed
14850        res.removedInfo = new PackageRemovedInfo();
14851        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14852        res.removedInfo.removedPackage = oldPackage.packageName;
14853        res.removedInfo.isUpdate = true;
14854        res.removedInfo.origUsers = installedUsers;
14855        final int childCount = (oldPackage.childPackages != null)
14856                ? oldPackage.childPackages.size() : 0;
14857        for (int i = 0; i < childCount; i++) {
14858            boolean childPackageUpdated = false;
14859            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14860            if (res.addedChildPackages != null) {
14861                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14862                if (childRes != null) {
14863                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14864                    childRes.removedInfo.removedPackage = childPkg.packageName;
14865                    childRes.removedInfo.isUpdate = true;
14866                    childPackageUpdated = true;
14867                }
14868            }
14869            if (!childPackageUpdated) {
14870                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14871                childRemovedRes.removedPackage = childPkg.packageName;
14872                childRemovedRes.isUpdate = false;
14873                childRemovedRes.dataRemoved = true;
14874                synchronized (mPackages) {
14875                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
14876                    if (childPs != null) {
14877                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14878                    }
14879                }
14880                if (res.removedInfo.removedChildPackages == null) {
14881                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14882                }
14883                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14884            }
14885        }
14886
14887        boolean sysPkg = (isSystemApp(oldPackage));
14888        if (sysPkg) {
14889            // Set the system/privileged flags as needed
14890            final boolean privileged =
14891                    (oldPackage.applicationInfo.privateFlags
14892                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14893            final int systemPolicyFlags = policyFlags
14894                    | PackageParser.PARSE_IS_SYSTEM
14895                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14896
14897            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14898                    user, allUsers, installerPackageName, res);
14899        } else {
14900            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14901                    user, allUsers, installerPackageName, res);
14902        }
14903    }
14904
14905    public List<String> getPreviousCodePaths(String packageName) {
14906        final PackageSetting ps = mSettings.mPackages.get(packageName);
14907        final List<String> result = new ArrayList<String>();
14908        if (ps != null && ps.oldCodePaths != null) {
14909            result.addAll(ps.oldCodePaths);
14910        }
14911        return result;
14912    }
14913
14914    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14915            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14916            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14917        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14918                + deletedPackage);
14919
14920        String pkgName = deletedPackage.packageName;
14921        boolean deletedPkg = true;
14922        boolean addedPkg = false;
14923        boolean updatedSettings = false;
14924        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14925        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14926                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14927
14928        final long origUpdateTime = (pkg.mExtras != null)
14929                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14930
14931        // First delete the existing package while retaining the data directory
14932        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14933                res.removedInfo, true, pkg)) {
14934            // If the existing package wasn't successfully deleted
14935            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14936            deletedPkg = false;
14937        } else {
14938            // Successfully deleted the old package; proceed with replace.
14939
14940            // If deleted package lived in a container, give users a chance to
14941            // relinquish resources before killing.
14942            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14943                if (DEBUG_INSTALL) {
14944                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14945                }
14946                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14947                final ArrayList<String> pkgList = new ArrayList<String>(1);
14948                pkgList.add(deletedPackage.applicationInfo.packageName);
14949                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14950            }
14951
14952            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14953                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14954            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14955
14956            try {
14957                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14958                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14959                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14960
14961                // Update the in-memory copy of the previous code paths.
14962                PackageSetting ps = mSettings.mPackages.get(pkgName);
14963                if (!killApp) {
14964                    if (ps.oldCodePaths == null) {
14965                        ps.oldCodePaths = new ArraySet<>();
14966                    }
14967                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14968                    if (deletedPackage.splitCodePaths != null) {
14969                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14970                    }
14971                } else {
14972                    ps.oldCodePaths = null;
14973                }
14974                if (ps.childPackageNames != null) {
14975                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14976                        final String childPkgName = ps.childPackageNames.get(i);
14977                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14978                        childPs.oldCodePaths = ps.oldCodePaths;
14979                    }
14980                }
14981                prepareAppDataAfterInstallLIF(newPackage);
14982                addedPkg = true;
14983            } catch (PackageManagerException e) {
14984                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14985            }
14986        }
14987
14988        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14989            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14990
14991            // Revert all internal state mutations and added folders for the failed install
14992            if (addedPkg) {
14993                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14994                        res.removedInfo, true, null);
14995            }
14996
14997            // Restore the old package
14998            if (deletedPkg) {
14999                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15000                File restoreFile = new File(deletedPackage.codePath);
15001                // Parse old package
15002                boolean oldExternal = isExternal(deletedPackage);
15003                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15004                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15005                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15006                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15007                try {
15008                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15009                            null);
15010                } catch (PackageManagerException e) {
15011                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15012                            + e.getMessage());
15013                    return;
15014                }
15015
15016                synchronized (mPackages) {
15017                    // Ensure the installer package name up to date
15018                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15019
15020                    // Update permissions for restored package
15021                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15022
15023                    mSettings.writeLPr();
15024                }
15025
15026                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15027            }
15028        } else {
15029            synchronized (mPackages) {
15030                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15031                if (ps != null) {
15032                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15033                    if (res.removedInfo.removedChildPackages != null) {
15034                        final int childCount = res.removedInfo.removedChildPackages.size();
15035                        // Iterate in reverse as we may modify the collection
15036                        for (int i = childCount - 1; i >= 0; i--) {
15037                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15038                            if (res.addedChildPackages.containsKey(childPackageName)) {
15039                                res.removedInfo.removedChildPackages.removeAt(i);
15040                            } else {
15041                                PackageRemovedInfo childInfo = res.removedInfo
15042                                        .removedChildPackages.valueAt(i);
15043                                childInfo.removedForAllUsers = mPackages.get(
15044                                        childInfo.removedPackage) == null;
15045                            }
15046                        }
15047                    }
15048                }
15049            }
15050        }
15051    }
15052
15053    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15054            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15055            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
15056        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15057                + ", old=" + deletedPackage);
15058
15059        final boolean disabledSystem;
15060
15061        // Remove existing system package
15062        removePackageLI(deletedPackage, true);
15063
15064        synchronized (mPackages) {
15065            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15066        }
15067        if (!disabledSystem) {
15068            // We didn't need to disable the .apk as a current system package,
15069            // which means we are replacing another update that is already
15070            // installed.  We need to make sure to delete the older one's .apk.
15071            res.removedInfo.args = createInstallArgsForExisting(0,
15072                    deletedPackage.applicationInfo.getCodePath(),
15073                    deletedPackage.applicationInfo.getResourcePath(),
15074                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15075        } else {
15076            res.removedInfo.args = null;
15077        }
15078
15079        // Successfully disabled the old package. Now proceed with re-installation
15080        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15081                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15082        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15083
15084        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15085        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15086                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15087
15088        PackageParser.Package newPackage = null;
15089        try {
15090            // Add the package to the internal data structures
15091            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15092
15093            // Set the update and install times
15094            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15095            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15096                    System.currentTimeMillis());
15097
15098            // Update the package dynamic state if succeeded
15099            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15100                // Now that the install succeeded make sure we remove data
15101                // directories for any child package the update removed.
15102                final int deletedChildCount = (deletedPackage.childPackages != null)
15103                        ? deletedPackage.childPackages.size() : 0;
15104                final int newChildCount = (newPackage.childPackages != null)
15105                        ? newPackage.childPackages.size() : 0;
15106                for (int i = 0; i < deletedChildCount; i++) {
15107                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15108                    boolean childPackageDeleted = true;
15109                    for (int j = 0; j < newChildCount; j++) {
15110                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15111                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15112                            childPackageDeleted = false;
15113                            break;
15114                        }
15115                    }
15116                    if (childPackageDeleted) {
15117                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15118                                deletedChildPkg.packageName);
15119                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15120                            PackageRemovedInfo removedChildRes = res.removedInfo
15121                                    .removedChildPackages.get(deletedChildPkg.packageName);
15122                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15123                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15124                        }
15125                    }
15126                }
15127
15128                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
15129                prepareAppDataAfterInstallLIF(newPackage);
15130            }
15131        } catch (PackageManagerException e) {
15132            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15133            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15134        }
15135
15136        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15137            // Re installation failed. Restore old information
15138            // Remove new pkg information
15139            if (newPackage != null) {
15140                removeInstalledPackageLI(newPackage, true);
15141            }
15142            // Add back the old system package
15143            try {
15144                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15145            } catch (PackageManagerException e) {
15146                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15147            }
15148
15149            synchronized (mPackages) {
15150                if (disabledSystem) {
15151                    enableSystemPackageLPw(deletedPackage);
15152                }
15153
15154                // Ensure the installer package name up to date
15155                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15156
15157                // Update permissions for restored package
15158                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
15159
15160                mSettings.writeLPr();
15161            }
15162
15163            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15164                    + " after failed upgrade");
15165        }
15166    }
15167
15168    /**
15169     * Checks whether the parent or any of the child packages have a change shared
15170     * user. For a package to be a valid update the shred users of the parent and
15171     * the children should match. We may later support changing child shared users.
15172     * @param oldPkg The updated package.
15173     * @param newPkg The update package.
15174     * @return The shared user that change between the versions.
15175     */
15176    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15177            PackageParser.Package newPkg) {
15178        // Check parent shared user
15179        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15180            return newPkg.packageName;
15181        }
15182        // Check child shared users
15183        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15184        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15185        for (int i = 0; i < newChildCount; i++) {
15186            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15187            // If this child was present, did it have the same shared user?
15188            for (int j = 0; j < oldChildCount; j++) {
15189                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15190                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15191                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15192                    return newChildPkg.packageName;
15193                }
15194            }
15195        }
15196        return null;
15197    }
15198
15199    private void removeNativeBinariesLI(PackageSetting ps) {
15200        // Remove the lib path for the parent package
15201        if (ps != null) {
15202            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15203            // Remove the lib path for the child packages
15204            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15205            for (int i = 0; i < childCount; i++) {
15206                PackageSetting childPs = null;
15207                synchronized (mPackages) {
15208                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15209                }
15210                if (childPs != null) {
15211                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15212                            .legacyNativeLibraryPathString);
15213                }
15214            }
15215        }
15216    }
15217
15218    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15219        // Enable the parent package
15220        mSettings.enableSystemPackageLPw(pkg.packageName);
15221        // Enable the child packages
15222        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15223        for (int i = 0; i < childCount; i++) {
15224            PackageParser.Package childPkg = pkg.childPackages.get(i);
15225            mSettings.enableSystemPackageLPw(childPkg.packageName);
15226        }
15227    }
15228
15229    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15230            PackageParser.Package newPkg) {
15231        // Disable the parent package (parent always replaced)
15232        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15233        // Disable the child packages
15234        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15235        for (int i = 0; i < childCount; i++) {
15236            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15237            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15238            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15239        }
15240        return disabled;
15241    }
15242
15243    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15244            String installerPackageName) {
15245        // Enable the parent package
15246        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15247        // Enable the child packages
15248        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15249        for (int i = 0; i < childCount; i++) {
15250            PackageParser.Package childPkg = pkg.childPackages.get(i);
15251            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15252        }
15253    }
15254
15255    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
15256        // Collect all used permissions in the UID
15257        ArraySet<String> usedPermissions = new ArraySet<>();
15258        final int packageCount = su.packages.size();
15259        for (int i = 0; i < packageCount; i++) {
15260            PackageSetting ps = su.packages.valueAt(i);
15261            if (ps.pkg == null) {
15262                continue;
15263            }
15264            final int requestedPermCount = ps.pkg.requestedPermissions.size();
15265            for (int j = 0; j < requestedPermCount; j++) {
15266                String permission = ps.pkg.requestedPermissions.get(j);
15267                BasePermission bp = mSettings.mPermissions.get(permission);
15268                if (bp != null) {
15269                    usedPermissions.add(permission);
15270                }
15271            }
15272        }
15273
15274        PermissionsState permissionsState = su.getPermissionsState();
15275        // Prune install permissions
15276        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
15277        final int installPermCount = installPermStates.size();
15278        for (int i = installPermCount - 1; i >= 0;  i--) {
15279            PermissionState permissionState = installPermStates.get(i);
15280            if (!usedPermissions.contains(permissionState.getName())) {
15281                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15282                if (bp != null) {
15283                    permissionsState.revokeInstallPermission(bp);
15284                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
15285                            PackageManager.MASK_PERMISSION_FLAGS, 0);
15286                }
15287            }
15288        }
15289
15290        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
15291
15292        // Prune runtime permissions
15293        for (int userId : allUserIds) {
15294            List<PermissionState> runtimePermStates = permissionsState
15295                    .getRuntimePermissionStates(userId);
15296            final int runtimePermCount = runtimePermStates.size();
15297            for (int i = runtimePermCount - 1; i >= 0; i--) {
15298                PermissionState permissionState = runtimePermStates.get(i);
15299                if (!usedPermissions.contains(permissionState.getName())) {
15300                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
15301                    if (bp != null) {
15302                        permissionsState.revokeRuntimePermission(bp, userId);
15303                        permissionsState.updatePermissionFlags(bp, userId,
15304                                PackageManager.MASK_PERMISSION_FLAGS, 0);
15305                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
15306                                runtimePermissionChangedUserIds, userId);
15307                    }
15308                }
15309            }
15310        }
15311
15312        return runtimePermissionChangedUserIds;
15313    }
15314
15315    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15316            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
15317        // Update the parent package setting
15318        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15319                res, user);
15320        // Update the child packages setting
15321        final int childCount = (newPackage.childPackages != null)
15322                ? newPackage.childPackages.size() : 0;
15323        for (int i = 0; i < childCount; i++) {
15324            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15325            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15326            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15327                    childRes.origUsers, childRes, user);
15328        }
15329    }
15330
15331    private void updateSettingsInternalLI(PackageParser.Package newPackage,
15332            String installerPackageName, int[] allUsers, int[] installedForUsers,
15333            PackageInstalledInfo res, UserHandle user) {
15334        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15335
15336        String pkgName = newPackage.packageName;
15337        synchronized (mPackages) {
15338            //write settings. the installStatus will be incomplete at this stage.
15339            //note that the new package setting would have already been
15340            //added to mPackages. It hasn't been persisted yet.
15341            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15342            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15343            mSettings.writeLPr();
15344            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15345        }
15346
15347        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
15348        synchronized (mPackages) {
15349            updatePermissionsLPw(newPackage.packageName, newPackage,
15350                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
15351                            ? UPDATE_PERMISSIONS_ALL : 0));
15352            // For system-bundled packages, we assume that installing an upgraded version
15353            // of the package implies that the user actually wants to run that new code,
15354            // so we enable the package.
15355            PackageSetting ps = mSettings.mPackages.get(pkgName);
15356            final int userId = user.getIdentifier();
15357            if (ps != null) {
15358                if (isSystemApp(newPackage)) {
15359                    if (DEBUG_INSTALL) {
15360                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
15361                    }
15362                    // Enable system package for requested users
15363                    if (res.origUsers != null) {
15364                        for (int origUserId : res.origUsers) {
15365                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
15366                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
15367                                        origUserId, installerPackageName);
15368                            }
15369                        }
15370                    }
15371                    // Also convey the prior install/uninstall state
15372                    if (allUsers != null && installedForUsers != null) {
15373                        for (int currentUserId : allUsers) {
15374                            final boolean installed = ArrayUtils.contains(
15375                                    installedForUsers, currentUserId);
15376                            if (DEBUG_INSTALL) {
15377                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
15378                            }
15379                            ps.setInstalled(installed, currentUserId);
15380                        }
15381                        // these install state changes will be persisted in the
15382                        // upcoming call to mSettings.writeLPr().
15383                    }
15384                }
15385                // It's implied that when a user requests installation, they want the app to be
15386                // installed and enabled.
15387                if (userId != UserHandle.USER_ALL) {
15388                    ps.setInstalled(true, userId);
15389                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
15390                }
15391            }
15392            res.name = pkgName;
15393            res.uid = newPackage.applicationInfo.uid;
15394            res.pkg = newPackage;
15395            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
15396            mSettings.setInstallerPackageName(pkgName, installerPackageName);
15397            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15398            //to update install status
15399            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15400            mSettings.writeLPr();
15401            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15402        }
15403
15404        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15405    }
15406
15407    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
15408        try {
15409            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
15410            installPackageLI(args, res);
15411        } finally {
15412            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15413        }
15414    }
15415
15416    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
15417        final int installFlags = args.installFlags;
15418        final String installerPackageName = args.installerPackageName;
15419        final String volumeUuid = args.volumeUuid;
15420        final File tmpPackageFile = new File(args.getCodePath());
15421        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
15422        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
15423                || (args.volumeUuid != null));
15424        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
15425        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
15426        boolean replace = false;
15427        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
15428        if (args.move != null) {
15429            // moving a complete application; perform an initial scan on the new install location
15430            scanFlags |= SCAN_INITIAL;
15431        }
15432        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
15433            scanFlags |= SCAN_DONT_KILL_APP;
15434        }
15435
15436        // Result object to be returned
15437        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15438
15439        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
15440
15441        // Sanity check
15442        if (ephemeral && (forwardLocked || onExternal)) {
15443            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
15444                    + " external=" + onExternal);
15445            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15446            return;
15447        }
15448
15449        // Retrieve PackageSettings and parse package
15450        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15451                | PackageParser.PARSE_ENFORCE_CODE
15452                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15453                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15454                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15455                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15456        PackageParser pp = new PackageParser();
15457        pp.setSeparateProcesses(mSeparateProcesses);
15458        pp.setDisplayMetrics(mMetrics);
15459
15460        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15461        final PackageParser.Package pkg;
15462        try {
15463            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15464        } catch (PackageParserException e) {
15465            res.setError("Failed parse during installPackageLI", e);
15466            return;
15467        } finally {
15468            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15469        }
15470
15471        // Ephemeral apps must have target SDK >= O.
15472        // TODO: Update conditional and error message when O gets locked down
15473        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
15474            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
15475                    "Ephemeral apps must have target SDK version of at least O");
15476            return;
15477        }
15478
15479        // If we are installing a clustered package add results for the children
15480        if (pkg.childPackages != null) {
15481            synchronized (mPackages) {
15482                final int childCount = pkg.childPackages.size();
15483                for (int i = 0; i < childCount; i++) {
15484                    PackageParser.Package childPkg = pkg.childPackages.get(i);
15485                    PackageInstalledInfo childRes = new PackageInstalledInfo();
15486                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15487                    childRes.pkg = childPkg;
15488                    childRes.name = childPkg.packageName;
15489                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15490                    if (childPs != null) {
15491                        childRes.origUsers = childPs.queryInstalledUsers(
15492                                sUserManager.getUserIds(), true);
15493                    }
15494                    if ((mPackages.containsKey(childPkg.packageName))) {
15495                        childRes.removedInfo = new PackageRemovedInfo();
15496                        childRes.removedInfo.removedPackage = childPkg.packageName;
15497                    }
15498                    if (res.addedChildPackages == null) {
15499                        res.addedChildPackages = new ArrayMap<>();
15500                    }
15501                    res.addedChildPackages.put(childPkg.packageName, childRes);
15502                }
15503            }
15504        }
15505
15506        // If package doesn't declare API override, mark that we have an install
15507        // time CPU ABI override.
15508        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15509            pkg.cpuAbiOverride = args.abiOverride;
15510        }
15511
15512        String pkgName = res.name = pkg.packageName;
15513        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15514            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15515                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15516                return;
15517            }
15518        }
15519
15520        try {
15521            // either use what we've been given or parse directly from the APK
15522            if (args.certificates != null) {
15523                try {
15524                    PackageParser.populateCertificates(pkg, args.certificates);
15525                } catch (PackageParserException e) {
15526                    // there was something wrong with the certificates we were given;
15527                    // try to pull them from the APK
15528                    PackageParser.collectCertificates(pkg, parseFlags);
15529                }
15530            } else {
15531                PackageParser.collectCertificates(pkg, parseFlags);
15532            }
15533        } catch (PackageParserException e) {
15534            res.setError("Failed collect during installPackageLI", e);
15535            return;
15536        }
15537
15538        // Get rid of all references to package scan path via parser.
15539        pp = null;
15540        String oldCodePath = null;
15541        boolean systemApp = false;
15542        synchronized (mPackages) {
15543            // Check if installing already existing package
15544            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15545                String oldName = mSettings.getRenamedPackageLPr(pkgName);
15546                if (pkg.mOriginalPackages != null
15547                        && pkg.mOriginalPackages.contains(oldName)
15548                        && mPackages.containsKey(oldName)) {
15549                    // This package is derived from an original package,
15550                    // and this device has been updating from that original
15551                    // name.  We must continue using the original name, so
15552                    // rename the new package here.
15553                    pkg.setPackageName(oldName);
15554                    pkgName = pkg.packageName;
15555                    replace = true;
15556                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15557                            + oldName + " pkgName=" + pkgName);
15558                } else if (mPackages.containsKey(pkgName)) {
15559                    // This package, under its official name, already exists
15560                    // on the device; we should replace it.
15561                    replace = true;
15562                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15563                }
15564
15565                // Child packages are installed through the parent package
15566                if (pkg.parentPackage != null) {
15567                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15568                            "Package " + pkg.packageName + " is child of package "
15569                                    + pkg.parentPackage.parentPackage + ". Child packages "
15570                                    + "can be updated only through the parent package.");
15571                    return;
15572                }
15573
15574                if (replace) {
15575                    // Prevent apps opting out from runtime permissions
15576                    PackageParser.Package oldPackage = mPackages.get(pkgName);
15577                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15578                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15579                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15580                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15581                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15582                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15583                                        + " doesn't support runtime permissions but the old"
15584                                        + " target SDK " + oldTargetSdk + " does.");
15585                        return;
15586                    }
15587
15588                    // Prevent installing of child packages
15589                    if (oldPackage.parentPackage != null) {
15590                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15591                                "Package " + pkg.packageName + " is child of package "
15592                                        + oldPackage.parentPackage + ". Child packages "
15593                                        + "can be updated only through the parent package.");
15594                        return;
15595                    }
15596                }
15597            }
15598
15599            PackageSetting ps = mSettings.mPackages.get(pkgName);
15600            if (ps != null) {
15601                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15602
15603                // Quick sanity check that we're signed correctly if updating;
15604                // we'll check this again later when scanning, but we want to
15605                // bail early here before tripping over redefined permissions.
15606                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15607                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15608                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15609                                + pkg.packageName + " upgrade keys do not match the "
15610                                + "previously installed version");
15611                        return;
15612                    }
15613                } else {
15614                    try {
15615                        verifySignaturesLP(ps, pkg);
15616                    } catch (PackageManagerException e) {
15617                        res.setError(e.error, e.getMessage());
15618                        return;
15619                    }
15620                }
15621
15622                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15623                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15624                    systemApp = (ps.pkg.applicationInfo.flags &
15625                            ApplicationInfo.FLAG_SYSTEM) != 0;
15626                }
15627                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15628            }
15629
15630            // Check whether the newly-scanned package wants to define an already-defined perm
15631            int N = pkg.permissions.size();
15632            for (int i = N-1; i >= 0; i--) {
15633                PackageParser.Permission perm = pkg.permissions.get(i);
15634                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15635                if (bp != null) {
15636                    // If the defining package is signed with our cert, it's okay.  This
15637                    // also includes the "updating the same package" case, of course.
15638                    // "updating same package" could also involve key-rotation.
15639                    final boolean sigsOk;
15640                    if (bp.sourcePackage.equals(pkg.packageName)
15641                            && (bp.packageSetting instanceof PackageSetting)
15642                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15643                                    scanFlags))) {
15644                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15645                    } else {
15646                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15647                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15648                    }
15649                    if (!sigsOk) {
15650                        // If the owning package is the system itself, we log but allow
15651                        // install to proceed; we fail the install on all other permission
15652                        // redefinitions.
15653                        if (!bp.sourcePackage.equals("android")) {
15654                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15655                                    + pkg.packageName + " attempting to redeclare permission "
15656                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15657                            res.origPermission = perm.info.name;
15658                            res.origPackage = bp.sourcePackage;
15659                            return;
15660                        } else {
15661                            Slog.w(TAG, "Package " + pkg.packageName
15662                                    + " attempting to redeclare system permission "
15663                                    + perm.info.name + "; ignoring new declaration");
15664                            pkg.permissions.remove(i);
15665                        }
15666                    }
15667                }
15668            }
15669        }
15670
15671        if (systemApp) {
15672            if (onExternal) {
15673                // Abort update; system app can't be replaced with app on sdcard
15674                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15675                        "Cannot install updates to system apps on sdcard");
15676                return;
15677            } else if (ephemeral) {
15678                // Abort update; system app can't be replaced with an ephemeral app
15679                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15680                        "Cannot update a system app with an ephemeral app");
15681                return;
15682            }
15683        }
15684
15685        if (args.move != null) {
15686            // We did an in-place move, so dex is ready to roll
15687            scanFlags |= SCAN_NO_DEX;
15688            scanFlags |= SCAN_MOVE;
15689
15690            synchronized (mPackages) {
15691                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15692                if (ps == null) {
15693                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15694                            "Missing settings for moved package " + pkgName);
15695                }
15696
15697                // We moved the entire application as-is, so bring over the
15698                // previously derived ABI information.
15699                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15700                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15701            }
15702
15703        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15704            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15705            scanFlags |= SCAN_NO_DEX;
15706
15707            try {
15708                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15709                    args.abiOverride : pkg.cpuAbiOverride);
15710                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15711                        true /*extractLibs*/, mAppLib32InstallDir);
15712            } catch (PackageManagerException pme) {
15713                Slog.e(TAG, "Error deriving application ABI", pme);
15714                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15715                return;
15716            }
15717
15718            // Shared libraries for the package need to be updated.
15719            synchronized (mPackages) {
15720                try {
15721                    updateSharedLibrariesLPr(pkg, null);
15722                } catch (PackageManagerException e) {
15723                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15724                }
15725            }
15726            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15727            // Do not run PackageDexOptimizer through the local performDexOpt
15728            // method because `pkg` may not be in `mPackages` yet.
15729            //
15730            // Also, don't fail application installs if the dexopt step fails.
15731            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15732                    null /* instructionSets */, false /* checkProfiles */,
15733                    getCompilerFilterForReason(REASON_INSTALL),
15734                    getOrCreateCompilerPackageStats(pkg));
15735            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15736
15737            // Notify BackgroundDexOptService that the package has been changed.
15738            // If this is an update of a package which used to fail to compile,
15739            // BDOS will remove it from its blacklist.
15740            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15741        }
15742
15743        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15744            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15745            return;
15746        }
15747
15748        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15749
15750        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15751                "installPackageLI")) {
15752            if (replace) {
15753                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15754                        installerPackageName, res);
15755            } else {
15756                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15757                        args.user, installerPackageName, volumeUuid, res);
15758            }
15759        }
15760        synchronized (mPackages) {
15761            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15762            if (ps != null) {
15763                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15764            }
15765
15766            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15767            for (int i = 0; i < childCount; i++) {
15768                PackageParser.Package childPkg = pkg.childPackages.get(i);
15769                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15770                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15771                if (childPs != null) {
15772                    childRes.newUsers = childPs.queryInstalledUsers(
15773                            sUserManager.getUserIds(), true);
15774                }
15775            }
15776        }
15777    }
15778
15779    private void startIntentFilterVerifications(int userId, boolean replacing,
15780            PackageParser.Package pkg) {
15781        if (mIntentFilterVerifierComponent == null) {
15782            Slog.w(TAG, "No IntentFilter verification will not be done as "
15783                    + "there is no IntentFilterVerifier available!");
15784            return;
15785        }
15786
15787        final int verifierUid = getPackageUid(
15788                mIntentFilterVerifierComponent.getPackageName(),
15789                MATCH_DEBUG_TRIAGED_MISSING,
15790                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15791
15792        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15793        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15794        mHandler.sendMessage(msg);
15795
15796        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15797        for (int i = 0; i < childCount; i++) {
15798            PackageParser.Package childPkg = pkg.childPackages.get(i);
15799            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15800            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15801            mHandler.sendMessage(msg);
15802        }
15803    }
15804
15805    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15806            PackageParser.Package pkg) {
15807        int size = pkg.activities.size();
15808        if (size == 0) {
15809            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15810                    "No activity, so no need to verify any IntentFilter!");
15811            return;
15812        }
15813
15814        final boolean hasDomainURLs = hasDomainURLs(pkg);
15815        if (!hasDomainURLs) {
15816            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15817                    "No domain URLs, so no need to verify any IntentFilter!");
15818            return;
15819        }
15820
15821        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15822                + " if any IntentFilter from the " + size
15823                + " Activities needs verification ...");
15824
15825        int count = 0;
15826        final String packageName = pkg.packageName;
15827
15828        synchronized (mPackages) {
15829            // If this is a new install and we see that we've already run verification for this
15830            // package, we have nothing to do: it means the state was restored from backup.
15831            if (!replacing) {
15832                IntentFilterVerificationInfo ivi =
15833                        mSettings.getIntentFilterVerificationLPr(packageName);
15834                if (ivi != null) {
15835                    if (DEBUG_DOMAIN_VERIFICATION) {
15836                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15837                                + ivi.getStatusString());
15838                    }
15839                    return;
15840                }
15841            }
15842
15843            // If any filters need to be verified, then all need to be.
15844            boolean needToVerify = false;
15845            for (PackageParser.Activity a : pkg.activities) {
15846                for (ActivityIntentInfo filter : a.intents) {
15847                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15848                        if (DEBUG_DOMAIN_VERIFICATION) {
15849                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15850                        }
15851                        needToVerify = true;
15852                        break;
15853                    }
15854                }
15855            }
15856
15857            if (needToVerify) {
15858                final int verificationId = mIntentFilterVerificationToken++;
15859                for (PackageParser.Activity a : pkg.activities) {
15860                    for (ActivityIntentInfo filter : a.intents) {
15861                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15862                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15863                                    "Verification needed for IntentFilter:" + filter.toString());
15864                            mIntentFilterVerifier.addOneIntentFilterVerification(
15865                                    verifierUid, userId, verificationId, filter, packageName);
15866                            count++;
15867                        }
15868                    }
15869                }
15870            }
15871        }
15872
15873        if (count > 0) {
15874            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15875                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15876                    +  " for userId:" + userId);
15877            mIntentFilterVerifier.startVerifications(userId);
15878        } else {
15879            if (DEBUG_DOMAIN_VERIFICATION) {
15880                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15881            }
15882        }
15883    }
15884
15885    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15886        final ComponentName cn  = filter.activity.getComponentName();
15887        final String packageName = cn.getPackageName();
15888
15889        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15890                packageName);
15891        if (ivi == null) {
15892            return true;
15893        }
15894        int status = ivi.getStatus();
15895        switch (status) {
15896            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15897            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15898                return true;
15899
15900            default:
15901                // Nothing to do
15902                return false;
15903        }
15904    }
15905
15906    private static boolean isMultiArch(ApplicationInfo info) {
15907        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15908    }
15909
15910    private static boolean isExternal(PackageParser.Package pkg) {
15911        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15912    }
15913
15914    private static boolean isExternal(PackageSetting ps) {
15915        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15916    }
15917
15918    private static boolean isEphemeral(PackageParser.Package pkg) {
15919        return pkg.applicationInfo.isEphemeralApp();
15920    }
15921
15922    private static boolean isEphemeral(PackageSetting ps) {
15923        return ps.pkg != null && isEphemeral(ps.pkg);
15924    }
15925
15926    private static boolean isSystemApp(PackageParser.Package pkg) {
15927        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15928    }
15929
15930    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15931        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15932    }
15933
15934    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15935        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15936    }
15937
15938    private static boolean isSystemApp(PackageSetting ps) {
15939        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15940    }
15941
15942    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15943        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15944    }
15945
15946    private int packageFlagsToInstallFlags(PackageSetting ps) {
15947        int installFlags = 0;
15948        if (isEphemeral(ps)) {
15949            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15950        }
15951        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15952            // This existing package was an external ASEC install when we have
15953            // the external flag without a UUID
15954            installFlags |= PackageManager.INSTALL_EXTERNAL;
15955        }
15956        if (ps.isForwardLocked()) {
15957            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15958        }
15959        return installFlags;
15960    }
15961
15962    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15963        if (isExternal(pkg)) {
15964            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15965                return StorageManager.UUID_PRIMARY_PHYSICAL;
15966            } else {
15967                return pkg.volumeUuid;
15968            }
15969        } else {
15970            return StorageManager.UUID_PRIVATE_INTERNAL;
15971        }
15972    }
15973
15974    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15975        if (isExternal(pkg)) {
15976            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15977                return mSettings.getExternalVersion();
15978            } else {
15979                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15980            }
15981        } else {
15982            return mSettings.getInternalVersion();
15983        }
15984    }
15985
15986    private void deleteTempPackageFiles() {
15987        final FilenameFilter filter = new FilenameFilter() {
15988            public boolean accept(File dir, String name) {
15989                return name.startsWith("vmdl") && name.endsWith(".tmp");
15990            }
15991        };
15992        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15993            file.delete();
15994        }
15995    }
15996
15997    @Override
15998    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15999            int flags) {
16000        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
16001                flags);
16002    }
16003
16004    @Override
16005    public void deletePackage(final String packageName,
16006            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16007        mContext.enforceCallingOrSelfPermission(
16008                android.Manifest.permission.DELETE_PACKAGES, null);
16009        Preconditions.checkNotNull(packageName);
16010        Preconditions.checkNotNull(observer);
16011        final int uid = Binder.getCallingUid();
16012        if (!isOrphaned(packageName)
16013                && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
16014            try {
16015                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16016                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16017                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16018                observer.onUserActionRequired(intent);
16019            } catch (RemoteException re) {
16020            }
16021            return;
16022        }
16023        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16024        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16025        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16026            mContext.enforceCallingOrSelfPermission(
16027                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16028                    "deletePackage for user " + userId);
16029        }
16030
16031        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16032            try {
16033                observer.onPackageDeleted(packageName,
16034                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16035            } catch (RemoteException re) {
16036            }
16037            return;
16038        }
16039
16040        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
16041            try {
16042                observer.onPackageDeleted(packageName,
16043                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16044            } catch (RemoteException re) {
16045            }
16046            return;
16047        }
16048
16049        if (DEBUG_REMOVE) {
16050            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
16051                    + " deleteAllUsers: " + deleteAllUsers );
16052        }
16053        // Queue up an async operation since the package deletion may take a little while.
16054        mHandler.post(new Runnable() {
16055            public void run() {
16056                mHandler.removeCallbacks(this);
16057                int returnCode;
16058                if (!deleteAllUsers) {
16059                    returnCode = deletePackageX(packageName, userId, deleteFlags);
16060                } else {
16061                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
16062                    // If nobody is blocking uninstall, proceed with delete for all users
16063                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16064                        returnCode = deletePackageX(packageName, userId, deleteFlags);
16065                    } else {
16066                        // Otherwise uninstall individually for users with blockUninstalls=false
16067                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16068                        for (int userId : users) {
16069                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16070                                returnCode = deletePackageX(packageName, userId, userFlags);
16071                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16072                                    Slog.w(TAG, "Package delete failed for user " + userId
16073                                            + ", returnCode " + returnCode);
16074                                }
16075                            }
16076                        }
16077                        // The app has only been marked uninstalled for certain users.
16078                        // We still need to report that delete was blocked
16079                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16080                    }
16081                }
16082                try {
16083                    observer.onPackageDeleted(packageName, returnCode, null);
16084                } catch (RemoteException e) {
16085                    Log.i(TAG, "Observer no longer exists.");
16086                } //end catch
16087            } //end run
16088        });
16089    }
16090
16091    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
16092        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
16093              || callingUid == Process.SYSTEM_UID) {
16094            return true;
16095        }
16096        final int callingUserId = UserHandle.getUserId(callingUid);
16097        // If the caller installed the pkgName, then allow it to silently uninstall.
16098        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
16099            return true;
16100        }
16101
16102        // Allow package verifier to silently uninstall.
16103        if (mRequiredVerifierPackage != null &&
16104                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
16105            return true;
16106        }
16107
16108        // Allow package uninstaller to silently uninstall.
16109        if (mRequiredUninstallerPackage != null &&
16110                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
16111            return true;
16112        }
16113
16114        // Allow storage manager to silently uninstall.
16115        if (mStorageManagerPackage != null &&
16116                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
16117            return true;
16118        }
16119        return false;
16120    }
16121
16122    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
16123        int[] result = EMPTY_INT_ARRAY;
16124        for (int userId : userIds) {
16125            if (getBlockUninstallForUser(packageName, userId)) {
16126                result = ArrayUtils.appendInt(result, userId);
16127            }
16128        }
16129        return result;
16130    }
16131
16132    @Override
16133    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
16134        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
16135    }
16136
16137    private boolean isPackageDeviceAdmin(String packageName, int userId) {
16138        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
16139                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
16140        try {
16141            if (dpm != null) {
16142                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
16143                        /* callingUserOnly =*/ false);
16144                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
16145                        : deviceOwnerComponentName.getPackageName();
16146                // Does the package contains the device owner?
16147                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
16148                // this check is probably not needed, since DO should be registered as a device
16149                // admin on some user too. (Original bug for this: b/17657954)
16150                if (packageName.equals(deviceOwnerPackageName)) {
16151                    return true;
16152                }
16153                // Does it contain a device admin for any user?
16154                int[] users;
16155                if (userId == UserHandle.USER_ALL) {
16156                    users = sUserManager.getUserIds();
16157                } else {
16158                    users = new int[]{userId};
16159                }
16160                for (int i = 0; i < users.length; ++i) {
16161                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
16162                        return true;
16163                    }
16164                }
16165            }
16166        } catch (RemoteException e) {
16167        }
16168        return false;
16169    }
16170
16171    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
16172        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
16173    }
16174
16175    /**
16176     *  This method is an internal method that could be get invoked either
16177     *  to delete an installed package or to clean up a failed installation.
16178     *  After deleting an installed package, a broadcast is sent to notify any
16179     *  listeners that the package has been removed. For cleaning up a failed
16180     *  installation, the broadcast is not necessary since the package's
16181     *  installation wouldn't have sent the initial broadcast either
16182     *  The key steps in deleting a package are
16183     *  deleting the package information in internal structures like mPackages,
16184     *  deleting the packages base directories through installd
16185     *  updating mSettings to reflect current status
16186     *  persisting settings for later use
16187     *  sending a broadcast if necessary
16188     */
16189    private int deletePackageX(String packageName, int userId, int deleteFlags) {
16190        final PackageRemovedInfo info = new PackageRemovedInfo();
16191        final boolean res;
16192
16193        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
16194                ? UserHandle.USER_ALL : userId;
16195
16196        if (isPackageDeviceAdmin(packageName, removeUser)) {
16197            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
16198            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
16199        }
16200
16201        PackageSetting uninstalledPs = null;
16202
16203        // for the uninstall-updates case and restricted profiles, remember the per-
16204        // user handle installed state
16205        int[] allUsers;
16206        synchronized (mPackages) {
16207            uninstalledPs = mSettings.mPackages.get(packageName);
16208            if (uninstalledPs == null) {
16209                Slog.w(TAG, "Not removing non-existent package " + packageName);
16210                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16211            }
16212            allUsers = sUserManager.getUserIds();
16213            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
16214        }
16215
16216        final int freezeUser;
16217        if (isUpdatedSystemApp(uninstalledPs)
16218                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
16219            // We're downgrading a system app, which will apply to all users, so
16220            // freeze them all during the downgrade
16221            freezeUser = UserHandle.USER_ALL;
16222        } else {
16223            freezeUser = removeUser;
16224        }
16225
16226        synchronized (mInstallLock) {
16227            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
16228            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
16229                    deleteFlags, "deletePackageX")) {
16230                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
16231                        deleteFlags | REMOVE_CHATTY, info, true, null);
16232            }
16233            synchronized (mPackages) {
16234                if (res) {
16235                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
16236                }
16237            }
16238        }
16239
16240        if (res) {
16241            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
16242            info.sendPackageRemovedBroadcasts(killApp);
16243            info.sendSystemPackageUpdatedBroadcasts();
16244            info.sendSystemPackageAppearedBroadcasts();
16245        }
16246        // Force a gc here.
16247        Runtime.getRuntime().gc();
16248        // Delete the resources here after sending the broadcast to let
16249        // other processes clean up before deleting resources.
16250        if (info.args != null) {
16251            synchronized (mInstallLock) {
16252                info.args.doPostDeleteLI(true);
16253            }
16254        }
16255
16256        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16257    }
16258
16259    class PackageRemovedInfo {
16260        String removedPackage;
16261        int uid = -1;
16262        int removedAppId = -1;
16263        int[] origUsers;
16264        int[] removedUsers = null;
16265        boolean isRemovedPackageSystemUpdate = false;
16266        boolean isUpdate;
16267        boolean dataRemoved;
16268        boolean removedForAllUsers;
16269        // Clean up resources deleted packages.
16270        InstallArgs args = null;
16271        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
16272        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
16273
16274        void sendPackageRemovedBroadcasts(boolean killApp) {
16275            sendPackageRemovedBroadcastInternal(killApp);
16276            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
16277            for (int i = 0; i < childCount; i++) {
16278                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16279                childInfo.sendPackageRemovedBroadcastInternal(killApp);
16280            }
16281        }
16282
16283        void sendSystemPackageUpdatedBroadcasts() {
16284            if (isRemovedPackageSystemUpdate) {
16285                sendSystemPackageUpdatedBroadcastsInternal();
16286                final int childCount = (removedChildPackages != null)
16287                        ? removedChildPackages.size() : 0;
16288                for (int i = 0; i < childCount; i++) {
16289                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
16290                    if (childInfo.isRemovedPackageSystemUpdate) {
16291                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
16292                    }
16293                }
16294            }
16295        }
16296
16297        void sendSystemPackageAppearedBroadcasts() {
16298            final int packageCount = (appearedChildPackages != null)
16299                    ? appearedChildPackages.size() : 0;
16300            for (int i = 0; i < packageCount; i++) {
16301                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
16302                sendPackageAddedForNewUsers(installedInfo.name, true,
16303                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
16304            }
16305        }
16306
16307        private void sendSystemPackageUpdatedBroadcastsInternal() {
16308            Bundle extras = new Bundle(2);
16309            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
16310            extras.putBoolean(Intent.EXTRA_REPLACING, true);
16311            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
16312                    extras, 0, null, null, null);
16313            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
16314                    extras, 0, null, null, null);
16315            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
16316                    null, 0, removedPackage, null, null);
16317        }
16318
16319        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
16320            Bundle extras = new Bundle(2);
16321            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
16322            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
16323            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
16324            if (isUpdate || isRemovedPackageSystemUpdate) {
16325                extras.putBoolean(Intent.EXTRA_REPLACING, true);
16326            }
16327            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
16328            if (removedPackage != null) {
16329                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
16330                        extras, 0, null, null, removedUsers);
16331                if (dataRemoved && !isRemovedPackageSystemUpdate) {
16332                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
16333                            removedPackage, extras, 0, null, null, removedUsers);
16334                }
16335            }
16336            if (removedAppId >= 0) {
16337                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
16338                        removedUsers);
16339            }
16340        }
16341    }
16342
16343    /*
16344     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
16345     * flag is not set, the data directory is removed as well.
16346     * make sure this flag is set for partially installed apps. If not its meaningless to
16347     * delete a partially installed application.
16348     */
16349    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
16350            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
16351        String packageName = ps.name;
16352        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
16353        // Retrieve object to delete permissions for shared user later on
16354        final PackageParser.Package deletedPkg;
16355        final PackageSetting deletedPs;
16356        // reader
16357        synchronized (mPackages) {
16358            deletedPkg = mPackages.get(packageName);
16359            deletedPs = mSettings.mPackages.get(packageName);
16360            if (outInfo != null) {
16361                outInfo.removedPackage = packageName;
16362                outInfo.removedUsers = deletedPs != null
16363                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
16364                        : null;
16365            }
16366        }
16367
16368        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
16369
16370        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
16371            final PackageParser.Package resolvedPkg;
16372            if (deletedPkg != null) {
16373                resolvedPkg = deletedPkg;
16374            } else {
16375                // We don't have a parsed package when it lives on an ejected
16376                // adopted storage device, so fake something together
16377                resolvedPkg = new PackageParser.Package(ps.name);
16378                resolvedPkg.setVolumeUuid(ps.volumeUuid);
16379            }
16380            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
16381                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16382            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
16383            if (outInfo != null) {
16384                outInfo.dataRemoved = true;
16385            }
16386            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
16387        }
16388
16389        // writer
16390        synchronized (mPackages) {
16391            if (deletedPs != null) {
16392                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
16393                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
16394                    clearDefaultBrowserIfNeeded(packageName);
16395                    if (outInfo != null) {
16396                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
16397                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
16398                    }
16399                    updatePermissionsLPw(deletedPs.name, null, 0);
16400                    if (deletedPs.sharedUser != null) {
16401                        // Remove permissions associated with package. Since runtime
16402                        // permissions are per user we have to kill the removed package
16403                        // or packages running under the shared user of the removed
16404                        // package if revoking the permissions requested only by the removed
16405                        // package is successful and this causes a change in gids.
16406                        for (int userId : UserManagerService.getInstance().getUserIds()) {
16407                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
16408                                    userId);
16409                            if (userIdToKill == UserHandle.USER_ALL
16410                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
16411                                // If gids changed for this user, kill all affected packages.
16412                                mHandler.post(new Runnable() {
16413                                    @Override
16414                                    public void run() {
16415                                        // This has to happen with no lock held.
16416                                        killApplication(deletedPs.name, deletedPs.appId,
16417                                                KILL_APP_REASON_GIDS_CHANGED);
16418                                    }
16419                                });
16420                                break;
16421                            }
16422                        }
16423                    }
16424                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
16425                }
16426                // make sure to preserve per-user disabled state if this removal was just
16427                // a downgrade of a system app to the factory package
16428                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
16429                    if (DEBUG_REMOVE) {
16430                        Slog.d(TAG, "Propagating install state across downgrade");
16431                    }
16432                    for (int userId : allUserHandles) {
16433                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16434                        if (DEBUG_REMOVE) {
16435                            Slog.d(TAG, "    user " + userId + " => " + installed);
16436                        }
16437                        ps.setInstalled(installed, userId);
16438                    }
16439                }
16440            }
16441            // can downgrade to reader
16442            if (writeSettings) {
16443                // Save settings now
16444                mSettings.writeLPr();
16445            }
16446        }
16447        if (outInfo != null) {
16448            // A user ID was deleted here. Go through all users and remove it
16449            // from KeyStore.
16450            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
16451        }
16452    }
16453
16454    static boolean locationIsPrivileged(File path) {
16455        try {
16456            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16457                    .getCanonicalPath();
16458            return path.getCanonicalPath().startsWith(privilegedAppDir);
16459        } catch (IOException e) {
16460            Slog.e(TAG, "Unable to access code path " + path);
16461        }
16462        return false;
16463    }
16464
16465    /*
16466     * Tries to delete system package.
16467     */
16468    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16469            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16470            boolean writeSettings) {
16471        if (deletedPs.parentPackageName != null) {
16472            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16473            return false;
16474        }
16475
16476        final boolean applyUserRestrictions
16477                = (allUserHandles != null) && (outInfo.origUsers != null);
16478        final PackageSetting disabledPs;
16479        // Confirm if the system package has been updated
16480        // An updated system app can be deleted. This will also have to restore
16481        // the system pkg from system partition
16482        // reader
16483        synchronized (mPackages) {
16484            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16485        }
16486
16487        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16488                + " disabledPs=" + disabledPs);
16489
16490        if (disabledPs == null) {
16491            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16492            return false;
16493        } else if (DEBUG_REMOVE) {
16494            Slog.d(TAG, "Deleting system pkg from data partition");
16495        }
16496
16497        if (DEBUG_REMOVE) {
16498            if (applyUserRestrictions) {
16499                Slog.d(TAG, "Remembering install states:");
16500                for (int userId : allUserHandles) {
16501                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16502                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16503                }
16504            }
16505        }
16506
16507        // Delete the updated package
16508        outInfo.isRemovedPackageSystemUpdate = true;
16509        if (outInfo.removedChildPackages != null) {
16510            final int childCount = (deletedPs.childPackageNames != null)
16511                    ? deletedPs.childPackageNames.size() : 0;
16512            for (int i = 0; i < childCount; i++) {
16513                String childPackageName = deletedPs.childPackageNames.get(i);
16514                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16515                        .contains(childPackageName)) {
16516                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16517                            childPackageName);
16518                    if (childInfo != null) {
16519                        childInfo.isRemovedPackageSystemUpdate = true;
16520                    }
16521                }
16522            }
16523        }
16524
16525        if (disabledPs.versionCode < deletedPs.versionCode) {
16526            // Delete data for downgrades
16527            flags &= ~PackageManager.DELETE_KEEP_DATA;
16528        } else {
16529            // Preserve data by setting flag
16530            flags |= PackageManager.DELETE_KEEP_DATA;
16531        }
16532
16533        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16534                outInfo, writeSettings, disabledPs.pkg);
16535        if (!ret) {
16536            return false;
16537        }
16538
16539        // writer
16540        synchronized (mPackages) {
16541            // Reinstate the old system package
16542            enableSystemPackageLPw(disabledPs.pkg);
16543            // Remove any native libraries from the upgraded package.
16544            removeNativeBinariesLI(deletedPs);
16545        }
16546
16547        // Install the system package
16548        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16549        int parseFlags = mDefParseFlags
16550                | PackageParser.PARSE_MUST_BE_APK
16551                | PackageParser.PARSE_IS_SYSTEM
16552                | PackageParser.PARSE_IS_SYSTEM_DIR;
16553        if (locationIsPrivileged(disabledPs.codePath)) {
16554            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16555        }
16556
16557        final PackageParser.Package newPkg;
16558        try {
16559            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
16560                0 /* currentTime */, null);
16561        } catch (PackageManagerException e) {
16562            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16563                    + e.getMessage());
16564            return false;
16565        }
16566        try {
16567            // update shared libraries for the newly re-installed system package
16568            updateSharedLibrariesLPr(newPkg, null);
16569        } catch (PackageManagerException e) {
16570            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16571        }
16572
16573        prepareAppDataAfterInstallLIF(newPkg);
16574
16575        // writer
16576        synchronized (mPackages) {
16577            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16578
16579            // Propagate the permissions state as we do not want to drop on the floor
16580            // runtime permissions. The update permissions method below will take
16581            // care of removing obsolete permissions and grant install permissions.
16582            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16583            updatePermissionsLPw(newPkg.packageName, newPkg,
16584                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16585
16586            if (applyUserRestrictions) {
16587                if (DEBUG_REMOVE) {
16588                    Slog.d(TAG, "Propagating install state across reinstall");
16589                }
16590                for (int userId : allUserHandles) {
16591                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16592                    if (DEBUG_REMOVE) {
16593                        Slog.d(TAG, "    user " + userId + " => " + installed);
16594                    }
16595                    ps.setInstalled(installed, userId);
16596
16597                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16598                }
16599                // Regardless of writeSettings we need to ensure that this restriction
16600                // state propagation is persisted
16601                mSettings.writeAllUsersPackageRestrictionsLPr();
16602            }
16603            // can downgrade to reader here
16604            if (writeSettings) {
16605                mSettings.writeLPr();
16606            }
16607        }
16608        return true;
16609    }
16610
16611    private boolean deleteInstalledPackageLIF(PackageSetting ps,
16612            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16613            PackageRemovedInfo outInfo, boolean writeSettings,
16614            PackageParser.Package replacingPackage) {
16615        synchronized (mPackages) {
16616            if (outInfo != null) {
16617                outInfo.uid = ps.appId;
16618            }
16619
16620            if (outInfo != null && outInfo.removedChildPackages != null) {
16621                final int childCount = (ps.childPackageNames != null)
16622                        ? ps.childPackageNames.size() : 0;
16623                for (int i = 0; i < childCount; i++) {
16624                    String childPackageName = ps.childPackageNames.get(i);
16625                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16626                    if (childPs == null) {
16627                        return false;
16628                    }
16629                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16630                            childPackageName);
16631                    if (childInfo != null) {
16632                        childInfo.uid = childPs.appId;
16633                    }
16634                }
16635            }
16636        }
16637
16638        // Delete package data from internal structures and also remove data if flag is set
16639        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16640
16641        // Delete the child packages data
16642        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16643        for (int i = 0; i < childCount; i++) {
16644            PackageSetting childPs;
16645            synchronized (mPackages) {
16646                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16647            }
16648            if (childPs != null) {
16649                PackageRemovedInfo childOutInfo = (outInfo != null
16650                        && outInfo.removedChildPackages != null)
16651                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16652                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16653                        && (replacingPackage != null
16654                        && !replacingPackage.hasChildPackage(childPs.name))
16655                        ? flags & ~DELETE_KEEP_DATA : flags;
16656                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16657                        deleteFlags, writeSettings);
16658            }
16659        }
16660
16661        // Delete application code and resources only for parent packages
16662        if (ps.parentPackageName == null) {
16663            if (deleteCodeAndResources && (outInfo != null)) {
16664                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16665                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16666                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16667            }
16668        }
16669
16670        return true;
16671    }
16672
16673    @Override
16674    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16675            int userId) {
16676        mContext.enforceCallingOrSelfPermission(
16677                android.Manifest.permission.DELETE_PACKAGES, null);
16678        synchronized (mPackages) {
16679            PackageSetting ps = mSettings.mPackages.get(packageName);
16680            if (ps == null) {
16681                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16682                return false;
16683            }
16684            if (!ps.getInstalled(userId)) {
16685                // Can't block uninstall for an app that is not installed or enabled.
16686                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16687                return false;
16688            }
16689            ps.setBlockUninstall(blockUninstall, userId);
16690            mSettings.writePackageRestrictionsLPr(userId);
16691        }
16692        return true;
16693    }
16694
16695    @Override
16696    public boolean getBlockUninstallForUser(String packageName, int userId) {
16697        synchronized (mPackages) {
16698            PackageSetting ps = mSettings.mPackages.get(packageName);
16699            if (ps == null) {
16700                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16701                return false;
16702            }
16703            return ps.getBlockUninstall(userId);
16704        }
16705    }
16706
16707    @Override
16708    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16709        int callingUid = Binder.getCallingUid();
16710        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16711            throw new SecurityException(
16712                    "setRequiredForSystemUser can only be run by the system or root");
16713        }
16714        synchronized (mPackages) {
16715            PackageSetting ps = mSettings.mPackages.get(packageName);
16716            if (ps == null) {
16717                Log.w(TAG, "Package doesn't exist: " + packageName);
16718                return false;
16719            }
16720            if (systemUserApp) {
16721                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16722            } else {
16723                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16724            }
16725            mSettings.writeLPr();
16726        }
16727        return true;
16728    }
16729
16730    /*
16731     * This method handles package deletion in general
16732     */
16733    private boolean deletePackageLIF(String packageName, UserHandle user,
16734            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16735            PackageRemovedInfo outInfo, boolean writeSettings,
16736            PackageParser.Package replacingPackage) {
16737        if (packageName == null) {
16738            Slog.w(TAG, "Attempt to delete null packageName.");
16739            return false;
16740        }
16741
16742        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16743
16744        PackageSetting ps;
16745
16746        synchronized (mPackages) {
16747            ps = mSettings.mPackages.get(packageName);
16748            if (ps == null) {
16749                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16750                return false;
16751            }
16752
16753            if (ps.parentPackageName != null && (!isSystemApp(ps)
16754                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16755                if (DEBUG_REMOVE) {
16756                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16757                            + ((user == null) ? UserHandle.USER_ALL : user));
16758                }
16759                final int removedUserId = (user != null) ? user.getIdentifier()
16760                        : UserHandle.USER_ALL;
16761                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16762                    return false;
16763                }
16764                markPackageUninstalledForUserLPw(ps, user);
16765                scheduleWritePackageRestrictionsLocked(user);
16766                return true;
16767            }
16768        }
16769
16770        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16771                && user.getIdentifier() != UserHandle.USER_ALL)) {
16772            // The caller is asking that the package only be deleted for a single
16773            // user.  To do this, we just mark its uninstalled state and delete
16774            // its data. If this is a system app, we only allow this to happen if
16775            // they have set the special DELETE_SYSTEM_APP which requests different
16776            // semantics than normal for uninstalling system apps.
16777            markPackageUninstalledForUserLPw(ps, user);
16778
16779            if (!isSystemApp(ps)) {
16780                // Do not uninstall the APK if an app should be cached
16781                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16782                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16783                    // Other user still have this package installed, so all
16784                    // we need to do is clear this user's data and save that
16785                    // it is uninstalled.
16786                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16787                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16788                        return false;
16789                    }
16790                    scheduleWritePackageRestrictionsLocked(user);
16791                    return true;
16792                } else {
16793                    // We need to set it back to 'installed' so the uninstall
16794                    // broadcasts will be sent correctly.
16795                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16796                    ps.setInstalled(true, user.getIdentifier());
16797                }
16798            } else {
16799                // This is a system app, so we assume that the
16800                // other users still have this package installed, so all
16801                // we need to do is clear this user's data and save that
16802                // it is uninstalled.
16803                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16804                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16805                    return false;
16806                }
16807                scheduleWritePackageRestrictionsLocked(user);
16808                return true;
16809            }
16810        }
16811
16812        // If we are deleting a composite package for all users, keep track
16813        // of result for each child.
16814        if (ps.childPackageNames != null && outInfo != null) {
16815            synchronized (mPackages) {
16816                final int childCount = ps.childPackageNames.size();
16817                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16818                for (int i = 0; i < childCount; i++) {
16819                    String childPackageName = ps.childPackageNames.get(i);
16820                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16821                    childInfo.removedPackage = childPackageName;
16822                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16823                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16824                    if (childPs != null) {
16825                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16826                    }
16827                }
16828            }
16829        }
16830
16831        boolean ret = false;
16832        if (isSystemApp(ps)) {
16833            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16834            // When an updated system application is deleted we delete the existing resources
16835            // as well and fall back to existing code in system partition
16836            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16837        } else {
16838            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16839            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16840                    outInfo, writeSettings, replacingPackage);
16841        }
16842
16843        // Take a note whether we deleted the package for all users
16844        if (outInfo != null) {
16845            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16846            if (outInfo.removedChildPackages != null) {
16847                synchronized (mPackages) {
16848                    final int childCount = outInfo.removedChildPackages.size();
16849                    for (int i = 0; i < childCount; i++) {
16850                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16851                        if (childInfo != null) {
16852                            childInfo.removedForAllUsers = mPackages.get(
16853                                    childInfo.removedPackage) == null;
16854                        }
16855                    }
16856                }
16857            }
16858            // If we uninstalled an update to a system app there may be some
16859            // child packages that appeared as they are declared in the system
16860            // app but were not declared in the update.
16861            if (isSystemApp(ps)) {
16862                synchronized (mPackages) {
16863                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
16864                    final int childCount = (updatedPs.childPackageNames != null)
16865                            ? updatedPs.childPackageNames.size() : 0;
16866                    for (int i = 0; i < childCount; i++) {
16867                        String childPackageName = updatedPs.childPackageNames.get(i);
16868                        if (outInfo.removedChildPackages == null
16869                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16870                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
16871                            if (childPs == null) {
16872                                continue;
16873                            }
16874                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16875                            installRes.name = childPackageName;
16876                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16877                            installRes.pkg = mPackages.get(childPackageName);
16878                            installRes.uid = childPs.pkg.applicationInfo.uid;
16879                            if (outInfo.appearedChildPackages == null) {
16880                                outInfo.appearedChildPackages = new ArrayMap<>();
16881                            }
16882                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16883                        }
16884                    }
16885                }
16886            }
16887        }
16888
16889        return ret;
16890    }
16891
16892    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16893        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16894                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16895        for (int nextUserId : userIds) {
16896            if (DEBUG_REMOVE) {
16897                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16898            }
16899            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16900                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16901                    false /*hidden*/, false /*suspended*/, null, null, null,
16902                    false /*blockUninstall*/,
16903                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16904        }
16905    }
16906
16907    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16908            PackageRemovedInfo outInfo) {
16909        final PackageParser.Package pkg;
16910        synchronized (mPackages) {
16911            pkg = mPackages.get(ps.name);
16912        }
16913
16914        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16915                : new int[] {userId};
16916        for (int nextUserId : userIds) {
16917            if (DEBUG_REMOVE) {
16918                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16919                        + nextUserId);
16920            }
16921
16922            destroyAppDataLIF(pkg, userId,
16923                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16924            destroyAppProfilesLIF(pkg, userId);
16925            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16926            schedulePackageCleaning(ps.name, nextUserId, false);
16927            synchronized (mPackages) {
16928                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16929                    scheduleWritePackageRestrictionsLocked(nextUserId);
16930                }
16931                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16932            }
16933        }
16934
16935        if (outInfo != null) {
16936            outInfo.removedPackage = ps.name;
16937            outInfo.removedAppId = ps.appId;
16938            outInfo.removedUsers = userIds;
16939        }
16940
16941        return true;
16942    }
16943
16944    private final class ClearStorageConnection implements ServiceConnection {
16945        IMediaContainerService mContainerService;
16946
16947        @Override
16948        public void onServiceConnected(ComponentName name, IBinder service) {
16949            synchronized (this) {
16950                mContainerService = IMediaContainerService.Stub
16951                        .asInterface(Binder.allowBlocking(service));
16952                notifyAll();
16953            }
16954        }
16955
16956        @Override
16957        public void onServiceDisconnected(ComponentName name) {
16958        }
16959    }
16960
16961    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16962        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16963
16964        final boolean mounted;
16965        if (Environment.isExternalStorageEmulated()) {
16966            mounted = true;
16967        } else {
16968            final String status = Environment.getExternalStorageState();
16969
16970            mounted = status.equals(Environment.MEDIA_MOUNTED)
16971                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16972        }
16973
16974        if (!mounted) {
16975            return;
16976        }
16977
16978        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16979        int[] users;
16980        if (userId == UserHandle.USER_ALL) {
16981            users = sUserManager.getUserIds();
16982        } else {
16983            users = new int[] { userId };
16984        }
16985        final ClearStorageConnection conn = new ClearStorageConnection();
16986        if (mContext.bindServiceAsUser(
16987                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16988            try {
16989                for (int curUser : users) {
16990                    long timeout = SystemClock.uptimeMillis() + 5000;
16991                    synchronized (conn) {
16992                        long now;
16993                        while (conn.mContainerService == null &&
16994                                (now = SystemClock.uptimeMillis()) < timeout) {
16995                            try {
16996                                conn.wait(timeout - now);
16997                            } catch (InterruptedException e) {
16998                            }
16999                        }
17000                    }
17001                    if (conn.mContainerService == null) {
17002                        return;
17003                    }
17004
17005                    final UserEnvironment userEnv = new UserEnvironment(curUser);
17006                    clearDirectory(conn.mContainerService,
17007                            userEnv.buildExternalStorageAppCacheDirs(packageName));
17008                    if (allData) {
17009                        clearDirectory(conn.mContainerService,
17010                                userEnv.buildExternalStorageAppDataDirs(packageName));
17011                        clearDirectory(conn.mContainerService,
17012                                userEnv.buildExternalStorageAppMediaDirs(packageName));
17013                    }
17014                }
17015            } finally {
17016                mContext.unbindService(conn);
17017            }
17018        }
17019    }
17020
17021    @Override
17022    public void clearApplicationProfileData(String packageName) {
17023        enforceSystemOrRoot("Only the system can clear all profile data");
17024
17025        final PackageParser.Package pkg;
17026        synchronized (mPackages) {
17027            pkg = mPackages.get(packageName);
17028        }
17029
17030        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
17031            synchronized (mInstallLock) {
17032                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
17033                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
17034                        true /* removeBaseMarker */);
17035            }
17036        }
17037    }
17038
17039    @Override
17040    public void clearApplicationUserData(final String packageName,
17041            final IPackageDataObserver observer, final int userId) {
17042        mContext.enforceCallingOrSelfPermission(
17043                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
17044
17045        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17046                true /* requireFullPermission */, false /* checkShell */, "clear application data");
17047
17048        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
17049            throw new SecurityException("Cannot clear data for a protected package: "
17050                    + packageName);
17051        }
17052        // Queue up an async operation since the package deletion may take a little while.
17053        mHandler.post(new Runnable() {
17054            public void run() {
17055                mHandler.removeCallbacks(this);
17056                final boolean succeeded;
17057                try (PackageFreezer freezer = freezePackage(packageName,
17058                        "clearApplicationUserData")) {
17059                    synchronized (mInstallLock) {
17060                        succeeded = clearApplicationUserDataLIF(packageName, userId);
17061                    }
17062                    clearExternalStorageDataSync(packageName, userId, true);
17063                }
17064                if (succeeded) {
17065                    // invoke DeviceStorageMonitor's update method to clear any notifications
17066                    DeviceStorageMonitorInternal dsm = LocalServices
17067                            .getService(DeviceStorageMonitorInternal.class);
17068                    if (dsm != null) {
17069                        dsm.checkMemory();
17070                    }
17071                }
17072                if(observer != null) {
17073                    try {
17074                        observer.onRemoveCompleted(packageName, succeeded);
17075                    } catch (RemoteException e) {
17076                        Log.i(TAG, "Observer no longer exists.");
17077                    }
17078                } //end if observer
17079            } //end run
17080        });
17081    }
17082
17083    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
17084        if (packageName == null) {
17085            Slog.w(TAG, "Attempt to delete null packageName.");
17086            return false;
17087        }
17088
17089        // Try finding details about the requested package
17090        PackageParser.Package pkg;
17091        synchronized (mPackages) {
17092            pkg = mPackages.get(packageName);
17093            if (pkg == null) {
17094                final PackageSetting ps = mSettings.mPackages.get(packageName);
17095                if (ps != null) {
17096                    pkg = ps.pkg;
17097                }
17098            }
17099
17100            if (pkg == null) {
17101                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17102                return false;
17103            }
17104
17105            PackageSetting ps = (PackageSetting) pkg.mExtras;
17106            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17107        }
17108
17109        clearAppDataLIF(pkg, userId,
17110                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17111
17112        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17113        removeKeystoreDataIfNeeded(userId, appId);
17114
17115        UserManagerInternal umInternal = getUserManagerInternal();
17116        final int flags;
17117        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
17118            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17119        } else if (umInternal.isUserRunning(userId)) {
17120            flags = StorageManager.FLAG_STORAGE_DE;
17121        } else {
17122            flags = 0;
17123        }
17124        prepareAppDataContentsLIF(pkg, userId, flags);
17125
17126        return true;
17127    }
17128
17129    /**
17130     * Reverts user permission state changes (permissions and flags) in
17131     * all packages for a given user.
17132     *
17133     * @param userId The device user for which to do a reset.
17134     */
17135    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
17136        final int packageCount = mPackages.size();
17137        for (int i = 0; i < packageCount; i++) {
17138            PackageParser.Package pkg = mPackages.valueAt(i);
17139            PackageSetting ps = (PackageSetting) pkg.mExtras;
17140            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
17141        }
17142    }
17143
17144    private void resetNetworkPolicies(int userId) {
17145        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
17146    }
17147
17148    /**
17149     * Reverts user permission state changes (permissions and flags).
17150     *
17151     * @param ps The package for which to reset.
17152     * @param userId The device user for which to do a reset.
17153     */
17154    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
17155            final PackageSetting ps, final int userId) {
17156        if (ps.pkg == null) {
17157            return;
17158        }
17159
17160        // These are flags that can change base on user actions.
17161        final int userSettableMask = FLAG_PERMISSION_USER_SET
17162                | FLAG_PERMISSION_USER_FIXED
17163                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
17164                | FLAG_PERMISSION_REVIEW_REQUIRED;
17165
17166        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
17167                | FLAG_PERMISSION_POLICY_FIXED;
17168
17169        boolean writeInstallPermissions = false;
17170        boolean writeRuntimePermissions = false;
17171
17172        final int permissionCount = ps.pkg.requestedPermissions.size();
17173        for (int i = 0; i < permissionCount; i++) {
17174            String permission = ps.pkg.requestedPermissions.get(i);
17175
17176            BasePermission bp = mSettings.mPermissions.get(permission);
17177            if (bp == null) {
17178                continue;
17179            }
17180
17181            // If shared user we just reset the state to which only this app contributed.
17182            if (ps.sharedUser != null) {
17183                boolean used = false;
17184                final int packageCount = ps.sharedUser.packages.size();
17185                for (int j = 0; j < packageCount; j++) {
17186                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
17187                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
17188                            && pkg.pkg.requestedPermissions.contains(permission)) {
17189                        used = true;
17190                        break;
17191                    }
17192                }
17193                if (used) {
17194                    continue;
17195                }
17196            }
17197
17198            PermissionsState permissionsState = ps.getPermissionsState();
17199
17200            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
17201
17202            // Always clear the user settable flags.
17203            final boolean hasInstallState = permissionsState.getInstallPermissionState(
17204                    bp.name) != null;
17205            // If permission review is enabled and this is a legacy app, mark the
17206            // permission as requiring a review as this is the initial state.
17207            int flags = 0;
17208            if (mPermissionReviewRequired
17209                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
17210                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
17211            }
17212            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
17213                if (hasInstallState) {
17214                    writeInstallPermissions = true;
17215                } else {
17216                    writeRuntimePermissions = true;
17217                }
17218            }
17219
17220            // Below is only runtime permission handling.
17221            if (!bp.isRuntime()) {
17222                continue;
17223            }
17224
17225            // Never clobber system or policy.
17226            if ((oldFlags & policyOrSystemFlags) != 0) {
17227                continue;
17228            }
17229
17230            // If this permission was granted by default, make sure it is.
17231            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
17232                if (permissionsState.grantRuntimePermission(bp, userId)
17233                        != PERMISSION_OPERATION_FAILURE) {
17234                    writeRuntimePermissions = true;
17235                }
17236            // If permission review is enabled the permissions for a legacy apps
17237            // are represented as constantly granted runtime ones, so don't revoke.
17238            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
17239                // Otherwise, reset the permission.
17240                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
17241                switch (revokeResult) {
17242                    case PERMISSION_OPERATION_SUCCESS:
17243                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
17244                        writeRuntimePermissions = true;
17245                        final int appId = ps.appId;
17246                        mHandler.post(new Runnable() {
17247                            @Override
17248                            public void run() {
17249                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
17250                            }
17251                        });
17252                    } break;
17253                }
17254            }
17255        }
17256
17257        // Synchronously write as we are taking permissions away.
17258        if (writeRuntimePermissions) {
17259            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
17260        }
17261
17262        // Synchronously write as we are taking permissions away.
17263        if (writeInstallPermissions) {
17264            mSettings.writeLPr();
17265        }
17266    }
17267
17268    /**
17269     * Remove entries from the keystore daemon. Will only remove it if the
17270     * {@code appId} is valid.
17271     */
17272    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
17273        if (appId < 0) {
17274            return;
17275        }
17276
17277        final KeyStore keyStore = KeyStore.getInstance();
17278        if (keyStore != null) {
17279            if (userId == UserHandle.USER_ALL) {
17280                for (final int individual : sUserManager.getUserIds()) {
17281                    keyStore.clearUid(UserHandle.getUid(individual, appId));
17282                }
17283            } else {
17284                keyStore.clearUid(UserHandle.getUid(userId, appId));
17285            }
17286        } else {
17287            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
17288        }
17289    }
17290
17291    @Override
17292    public void deleteApplicationCacheFiles(final String packageName,
17293            final IPackageDataObserver observer) {
17294        final int userId = UserHandle.getCallingUserId();
17295        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
17296    }
17297
17298    @Override
17299    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
17300            final IPackageDataObserver observer) {
17301        mContext.enforceCallingOrSelfPermission(
17302                android.Manifest.permission.DELETE_CACHE_FILES, null);
17303        enforceCrossUserPermission(Binder.getCallingUid(), userId,
17304                /* requireFullPermission= */ true, /* checkShell= */ false,
17305                "delete application cache files");
17306
17307        final PackageParser.Package pkg;
17308        synchronized (mPackages) {
17309            pkg = mPackages.get(packageName);
17310        }
17311
17312        // Queue up an async operation since the package deletion may take a little while.
17313        mHandler.post(new Runnable() {
17314            public void run() {
17315                synchronized (mInstallLock) {
17316                    final int flags = StorageManager.FLAG_STORAGE_DE
17317                            | StorageManager.FLAG_STORAGE_CE;
17318                    // We're only clearing cache files, so we don't care if the
17319                    // app is unfrozen and still able to run
17320                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
17321                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17322                }
17323                clearExternalStorageDataSync(packageName, userId, false);
17324                if (observer != null) {
17325                    try {
17326                        observer.onRemoveCompleted(packageName, true);
17327                    } catch (RemoteException e) {
17328                        Log.i(TAG, "Observer no longer exists.");
17329                    }
17330                }
17331            }
17332        });
17333    }
17334
17335    @Override
17336    public void getPackageSizeInfo(final String packageName, int userHandle,
17337            final IPackageStatsObserver observer) {
17338        mContext.enforceCallingOrSelfPermission(
17339                android.Manifest.permission.GET_PACKAGE_SIZE, null);
17340        if (packageName == null) {
17341            throw new IllegalArgumentException("Attempt to get size of null packageName");
17342        }
17343
17344        PackageStats stats = new PackageStats(packageName, userHandle);
17345
17346        /*
17347         * Queue up an async operation since the package measurement may take a
17348         * little while.
17349         */
17350        Message msg = mHandler.obtainMessage(INIT_COPY);
17351        msg.obj = new MeasureParams(stats, observer);
17352        mHandler.sendMessage(msg);
17353    }
17354
17355    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
17356        final PackageSetting ps;
17357        synchronized (mPackages) {
17358            ps = mSettings.mPackages.get(packageName);
17359            if (ps == null) {
17360                Slog.w(TAG, "Failed to find settings for " + packageName);
17361                return false;
17362            }
17363        }
17364        try {
17365            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
17366                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
17367                    ps.getCeDataInode(userId), ps.codePathString, stats);
17368        } catch (InstallerException e) {
17369            Slog.w(TAG, String.valueOf(e));
17370            return false;
17371        }
17372
17373        // For now, ignore code size of packages on system partition
17374        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
17375            stats.codeSize = 0;
17376        }
17377
17378        return true;
17379    }
17380
17381    private int getUidTargetSdkVersionLockedLPr(int uid) {
17382        Object obj = mSettings.getUserIdLPr(uid);
17383        if (obj instanceof SharedUserSetting) {
17384            final SharedUserSetting sus = (SharedUserSetting) obj;
17385            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
17386            final Iterator<PackageSetting> it = sus.packages.iterator();
17387            while (it.hasNext()) {
17388                final PackageSetting ps = it.next();
17389                if (ps.pkg != null) {
17390                    int v = ps.pkg.applicationInfo.targetSdkVersion;
17391                    if (v < vers) vers = v;
17392                }
17393            }
17394            return vers;
17395        } else if (obj instanceof PackageSetting) {
17396            final PackageSetting ps = (PackageSetting) obj;
17397            if (ps.pkg != null) {
17398                return ps.pkg.applicationInfo.targetSdkVersion;
17399            }
17400        }
17401        return Build.VERSION_CODES.CUR_DEVELOPMENT;
17402    }
17403
17404    @Override
17405    public void addPreferredActivity(IntentFilter filter, int match,
17406            ComponentName[] set, ComponentName activity, int userId) {
17407        addPreferredActivityInternal(filter, match, set, activity, true, userId,
17408                "Adding preferred");
17409    }
17410
17411    private void addPreferredActivityInternal(IntentFilter filter, int match,
17412            ComponentName[] set, ComponentName activity, boolean always, int userId,
17413            String opname) {
17414        // writer
17415        int callingUid = Binder.getCallingUid();
17416        enforceCrossUserPermission(callingUid, userId,
17417                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
17418        if (filter.countActions() == 0) {
17419            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17420            return;
17421        }
17422        synchronized (mPackages) {
17423            if (mContext.checkCallingOrSelfPermission(
17424                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17425                    != PackageManager.PERMISSION_GRANTED) {
17426                if (getUidTargetSdkVersionLockedLPr(callingUid)
17427                        < Build.VERSION_CODES.FROYO) {
17428                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
17429                            + callingUid);
17430                    return;
17431                }
17432                mContext.enforceCallingOrSelfPermission(
17433                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17434            }
17435
17436            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
17437            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
17438                    + userId + ":");
17439            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17440            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
17441            scheduleWritePackageRestrictionsLocked(userId);
17442            postPreferredActivityChangedBroadcast(userId);
17443        }
17444    }
17445
17446    private void postPreferredActivityChangedBroadcast(int userId) {
17447        mHandler.post(() -> {
17448            final IActivityManager am = ActivityManager.getService();
17449            if (am == null) {
17450                return;
17451            }
17452
17453            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
17454            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17455            try {
17456                am.broadcastIntent(null, intent, null, null,
17457                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
17458                        null, false, false, userId);
17459            } catch (RemoteException e) {
17460            }
17461        });
17462    }
17463
17464    @Override
17465    public void replacePreferredActivity(IntentFilter filter, int match,
17466            ComponentName[] set, ComponentName activity, int userId) {
17467        if (filter.countActions() != 1) {
17468            throw new IllegalArgumentException(
17469                    "replacePreferredActivity expects filter to have only 1 action.");
17470        }
17471        if (filter.countDataAuthorities() != 0
17472                || filter.countDataPaths() != 0
17473                || filter.countDataSchemes() > 1
17474                || filter.countDataTypes() != 0) {
17475            throw new IllegalArgumentException(
17476                    "replacePreferredActivity expects filter to have no data authorities, " +
17477                    "paths, or types; and at most one scheme.");
17478        }
17479
17480        final int callingUid = Binder.getCallingUid();
17481        enforceCrossUserPermission(callingUid, userId,
17482                true /* requireFullPermission */, false /* checkShell */,
17483                "replace preferred activity");
17484        synchronized (mPackages) {
17485            if (mContext.checkCallingOrSelfPermission(
17486                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17487                    != PackageManager.PERMISSION_GRANTED) {
17488                if (getUidTargetSdkVersionLockedLPr(callingUid)
17489                        < Build.VERSION_CODES.FROYO) {
17490                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17491                            + Binder.getCallingUid());
17492                    return;
17493                }
17494                mContext.enforceCallingOrSelfPermission(
17495                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17496            }
17497
17498            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17499            if (pir != null) {
17500                // Get all of the existing entries that exactly match this filter.
17501                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17502                if (existing != null && existing.size() == 1) {
17503                    PreferredActivity cur = existing.get(0);
17504                    if (DEBUG_PREFERRED) {
17505                        Slog.i(TAG, "Checking replace of preferred:");
17506                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17507                        if (!cur.mPref.mAlways) {
17508                            Slog.i(TAG, "  -- CUR; not mAlways!");
17509                        } else {
17510                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17511                            Slog.i(TAG, "  -- CUR: mSet="
17512                                    + Arrays.toString(cur.mPref.mSetComponents));
17513                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17514                            Slog.i(TAG, "  -- NEW: mMatch="
17515                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
17516                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17517                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17518                        }
17519                    }
17520                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17521                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17522                            && cur.mPref.sameSet(set)) {
17523                        // Setting the preferred activity to what it happens to be already
17524                        if (DEBUG_PREFERRED) {
17525                            Slog.i(TAG, "Replacing with same preferred activity "
17526                                    + cur.mPref.mShortComponent + " for user "
17527                                    + userId + ":");
17528                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17529                        }
17530                        return;
17531                    }
17532                }
17533
17534                if (existing != null) {
17535                    if (DEBUG_PREFERRED) {
17536                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
17537                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17538                    }
17539                    for (int i = 0; i < existing.size(); i++) {
17540                        PreferredActivity pa = existing.get(i);
17541                        if (DEBUG_PREFERRED) {
17542                            Slog.i(TAG, "Removing existing preferred activity "
17543                                    + pa.mPref.mComponent + ":");
17544                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17545                        }
17546                        pir.removeFilter(pa);
17547                    }
17548                }
17549            }
17550            addPreferredActivityInternal(filter, match, set, activity, true, userId,
17551                    "Replacing preferred");
17552        }
17553    }
17554
17555    @Override
17556    public void clearPackagePreferredActivities(String packageName) {
17557        final int uid = Binder.getCallingUid();
17558        // writer
17559        synchronized (mPackages) {
17560            PackageParser.Package pkg = mPackages.get(packageName);
17561            if (pkg == null || pkg.applicationInfo.uid != uid) {
17562                if (mContext.checkCallingOrSelfPermission(
17563                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17564                        != PackageManager.PERMISSION_GRANTED) {
17565                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17566                            < Build.VERSION_CODES.FROYO) {
17567                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17568                                + Binder.getCallingUid());
17569                        return;
17570                    }
17571                    mContext.enforceCallingOrSelfPermission(
17572                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17573                }
17574            }
17575
17576            int user = UserHandle.getCallingUserId();
17577            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17578                scheduleWritePackageRestrictionsLocked(user);
17579            }
17580        }
17581    }
17582
17583    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17584    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17585        ArrayList<PreferredActivity> removed = null;
17586        boolean changed = false;
17587        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17588            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17589            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17590            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17591                continue;
17592            }
17593            Iterator<PreferredActivity> it = pir.filterIterator();
17594            while (it.hasNext()) {
17595                PreferredActivity pa = it.next();
17596                // Mark entry for removal only if it matches the package name
17597                // and the entry is of type "always".
17598                if (packageName == null ||
17599                        (pa.mPref.mComponent.getPackageName().equals(packageName)
17600                                && pa.mPref.mAlways)) {
17601                    if (removed == null) {
17602                        removed = new ArrayList<PreferredActivity>();
17603                    }
17604                    removed.add(pa);
17605                }
17606            }
17607            if (removed != null) {
17608                for (int j=0; j<removed.size(); j++) {
17609                    PreferredActivity pa = removed.get(j);
17610                    pir.removeFilter(pa);
17611                }
17612                changed = true;
17613            }
17614        }
17615        if (changed) {
17616            postPreferredActivityChangedBroadcast(userId);
17617        }
17618        return changed;
17619    }
17620
17621    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17622    private void clearIntentFilterVerificationsLPw(int userId) {
17623        final int packageCount = mPackages.size();
17624        for (int i = 0; i < packageCount; i++) {
17625            PackageParser.Package pkg = mPackages.valueAt(i);
17626            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17627        }
17628    }
17629
17630    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17631    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17632        if (userId == UserHandle.USER_ALL) {
17633            if (mSettings.removeIntentFilterVerificationLPw(packageName,
17634                    sUserManager.getUserIds())) {
17635                for (int oneUserId : sUserManager.getUserIds()) {
17636                    scheduleWritePackageRestrictionsLocked(oneUserId);
17637                }
17638            }
17639        } else {
17640            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17641                scheduleWritePackageRestrictionsLocked(userId);
17642            }
17643        }
17644    }
17645
17646    void clearDefaultBrowserIfNeeded(String packageName) {
17647        for (int oneUserId : sUserManager.getUserIds()) {
17648            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17649            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17650            if (packageName.equals(defaultBrowserPackageName)) {
17651                setDefaultBrowserPackageName(null, oneUserId);
17652            }
17653        }
17654    }
17655
17656    @Override
17657    public void resetApplicationPreferences(int userId) {
17658        mContext.enforceCallingOrSelfPermission(
17659                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17660        final long identity = Binder.clearCallingIdentity();
17661        // writer
17662        try {
17663            synchronized (mPackages) {
17664                clearPackagePreferredActivitiesLPw(null, userId);
17665                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17666                // TODO: We have to reset the default SMS and Phone. This requires
17667                // significant refactoring to keep all default apps in the package
17668                // manager (cleaner but more work) or have the services provide
17669                // callbacks to the package manager to request a default app reset.
17670                applyFactoryDefaultBrowserLPw(userId);
17671                clearIntentFilterVerificationsLPw(userId);
17672                primeDomainVerificationsLPw(userId);
17673                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17674                scheduleWritePackageRestrictionsLocked(userId);
17675            }
17676            resetNetworkPolicies(userId);
17677        } finally {
17678            Binder.restoreCallingIdentity(identity);
17679        }
17680    }
17681
17682    @Override
17683    public int getPreferredActivities(List<IntentFilter> outFilters,
17684            List<ComponentName> outActivities, String packageName) {
17685
17686        int num = 0;
17687        final int userId = UserHandle.getCallingUserId();
17688        // reader
17689        synchronized (mPackages) {
17690            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17691            if (pir != null) {
17692                final Iterator<PreferredActivity> it = pir.filterIterator();
17693                while (it.hasNext()) {
17694                    final PreferredActivity pa = it.next();
17695                    if (packageName == null
17696                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17697                                    && pa.mPref.mAlways)) {
17698                        if (outFilters != null) {
17699                            outFilters.add(new IntentFilter(pa));
17700                        }
17701                        if (outActivities != null) {
17702                            outActivities.add(pa.mPref.mComponent);
17703                        }
17704                    }
17705                }
17706            }
17707        }
17708
17709        return num;
17710    }
17711
17712    @Override
17713    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17714            int userId) {
17715        int callingUid = Binder.getCallingUid();
17716        if (callingUid != Process.SYSTEM_UID) {
17717            throw new SecurityException(
17718                    "addPersistentPreferredActivity can only be run by the system");
17719        }
17720        if (filter.countActions() == 0) {
17721            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17722            return;
17723        }
17724        synchronized (mPackages) {
17725            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17726                    ":");
17727            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17728            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17729                    new PersistentPreferredActivity(filter, activity));
17730            scheduleWritePackageRestrictionsLocked(userId);
17731            postPreferredActivityChangedBroadcast(userId);
17732        }
17733    }
17734
17735    @Override
17736    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17737        int callingUid = Binder.getCallingUid();
17738        if (callingUid != Process.SYSTEM_UID) {
17739            throw new SecurityException(
17740                    "clearPackagePersistentPreferredActivities can only be run by the system");
17741        }
17742        ArrayList<PersistentPreferredActivity> removed = null;
17743        boolean changed = false;
17744        synchronized (mPackages) {
17745            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17746                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17747                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17748                        .valueAt(i);
17749                if (userId != thisUserId) {
17750                    continue;
17751                }
17752                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17753                while (it.hasNext()) {
17754                    PersistentPreferredActivity ppa = it.next();
17755                    // Mark entry for removal only if it matches the package name.
17756                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17757                        if (removed == null) {
17758                            removed = new ArrayList<PersistentPreferredActivity>();
17759                        }
17760                        removed.add(ppa);
17761                    }
17762                }
17763                if (removed != null) {
17764                    for (int j=0; j<removed.size(); j++) {
17765                        PersistentPreferredActivity ppa = removed.get(j);
17766                        ppir.removeFilter(ppa);
17767                    }
17768                    changed = true;
17769                }
17770            }
17771
17772            if (changed) {
17773                scheduleWritePackageRestrictionsLocked(userId);
17774                postPreferredActivityChangedBroadcast(userId);
17775            }
17776        }
17777    }
17778
17779    /**
17780     * Common machinery for picking apart a restored XML blob and passing
17781     * it to a caller-supplied functor to be applied to the running system.
17782     */
17783    private void restoreFromXml(XmlPullParser parser, int userId,
17784            String expectedStartTag, BlobXmlRestorer functor)
17785            throws IOException, XmlPullParserException {
17786        int type;
17787        while ((type = parser.next()) != XmlPullParser.START_TAG
17788                && type != XmlPullParser.END_DOCUMENT) {
17789        }
17790        if (type != XmlPullParser.START_TAG) {
17791            // oops didn't find a start tag?!
17792            if (DEBUG_BACKUP) {
17793                Slog.e(TAG, "Didn't find start tag during restore");
17794            }
17795            return;
17796        }
17797Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17798        // this is supposed to be TAG_PREFERRED_BACKUP
17799        if (!expectedStartTag.equals(parser.getName())) {
17800            if (DEBUG_BACKUP) {
17801                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17802            }
17803            return;
17804        }
17805
17806        // skip interfering stuff, then we're aligned with the backing implementation
17807        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17808Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17809        functor.apply(parser, userId);
17810    }
17811
17812    private interface BlobXmlRestorer {
17813        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17814    }
17815
17816    /**
17817     * Non-Binder method, support for the backup/restore mechanism: write the
17818     * full set of preferred activities in its canonical XML format.  Returns the
17819     * XML output as a byte array, or null if there is none.
17820     */
17821    @Override
17822    public byte[] getPreferredActivityBackup(int userId) {
17823        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17824            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17825        }
17826
17827        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17828        try {
17829            final XmlSerializer serializer = new FastXmlSerializer();
17830            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17831            serializer.startDocument(null, true);
17832            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17833
17834            synchronized (mPackages) {
17835                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17836            }
17837
17838            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17839            serializer.endDocument();
17840            serializer.flush();
17841        } catch (Exception e) {
17842            if (DEBUG_BACKUP) {
17843                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17844            }
17845            return null;
17846        }
17847
17848        return dataStream.toByteArray();
17849    }
17850
17851    @Override
17852    public void restorePreferredActivities(byte[] backup, int userId) {
17853        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17854            throw new SecurityException("Only the system may call restorePreferredActivities()");
17855        }
17856
17857        try {
17858            final XmlPullParser parser = Xml.newPullParser();
17859            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17860            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17861                    new BlobXmlRestorer() {
17862                        @Override
17863                        public void apply(XmlPullParser parser, int userId)
17864                                throws XmlPullParserException, IOException {
17865                            synchronized (mPackages) {
17866                                mSettings.readPreferredActivitiesLPw(parser, userId);
17867                            }
17868                        }
17869                    } );
17870        } catch (Exception e) {
17871            if (DEBUG_BACKUP) {
17872                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17873            }
17874        }
17875    }
17876
17877    /**
17878     * Non-Binder method, support for the backup/restore mechanism: write the
17879     * default browser (etc) settings in its canonical XML format.  Returns the default
17880     * browser XML representation as a byte array, or null if there is none.
17881     */
17882    @Override
17883    public byte[] getDefaultAppsBackup(int userId) {
17884        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17885            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17886        }
17887
17888        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17889        try {
17890            final XmlSerializer serializer = new FastXmlSerializer();
17891            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17892            serializer.startDocument(null, true);
17893            serializer.startTag(null, TAG_DEFAULT_APPS);
17894
17895            synchronized (mPackages) {
17896                mSettings.writeDefaultAppsLPr(serializer, userId);
17897            }
17898
17899            serializer.endTag(null, TAG_DEFAULT_APPS);
17900            serializer.endDocument();
17901            serializer.flush();
17902        } catch (Exception e) {
17903            if (DEBUG_BACKUP) {
17904                Slog.e(TAG, "Unable to write default apps for backup", e);
17905            }
17906            return null;
17907        }
17908
17909        return dataStream.toByteArray();
17910    }
17911
17912    @Override
17913    public void restoreDefaultApps(byte[] backup, int userId) {
17914        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17915            throw new SecurityException("Only the system may call restoreDefaultApps()");
17916        }
17917
17918        try {
17919            final XmlPullParser parser = Xml.newPullParser();
17920            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17921            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17922                    new BlobXmlRestorer() {
17923                        @Override
17924                        public void apply(XmlPullParser parser, int userId)
17925                                throws XmlPullParserException, IOException {
17926                            synchronized (mPackages) {
17927                                mSettings.readDefaultAppsLPw(parser, userId);
17928                            }
17929                        }
17930                    } );
17931        } catch (Exception e) {
17932            if (DEBUG_BACKUP) {
17933                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17934            }
17935        }
17936    }
17937
17938    @Override
17939    public byte[] getIntentFilterVerificationBackup(int userId) {
17940        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17941            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17942        }
17943
17944        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17945        try {
17946            final XmlSerializer serializer = new FastXmlSerializer();
17947            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17948            serializer.startDocument(null, true);
17949            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17950
17951            synchronized (mPackages) {
17952                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17953            }
17954
17955            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17956            serializer.endDocument();
17957            serializer.flush();
17958        } catch (Exception e) {
17959            if (DEBUG_BACKUP) {
17960                Slog.e(TAG, "Unable to write default apps for backup", e);
17961            }
17962            return null;
17963        }
17964
17965        return dataStream.toByteArray();
17966    }
17967
17968    @Override
17969    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17970        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17971            throw new SecurityException("Only the system may call restorePreferredActivities()");
17972        }
17973
17974        try {
17975            final XmlPullParser parser = Xml.newPullParser();
17976            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17977            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17978                    new BlobXmlRestorer() {
17979                        @Override
17980                        public void apply(XmlPullParser parser, int userId)
17981                                throws XmlPullParserException, IOException {
17982                            synchronized (mPackages) {
17983                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17984                                mSettings.writeLPr();
17985                            }
17986                        }
17987                    } );
17988        } catch (Exception e) {
17989            if (DEBUG_BACKUP) {
17990                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17991            }
17992        }
17993    }
17994
17995    @Override
17996    public byte[] getPermissionGrantBackup(int userId) {
17997        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17998            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17999        }
18000
18001        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18002        try {
18003            final XmlSerializer serializer = new FastXmlSerializer();
18004            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18005            serializer.startDocument(null, true);
18006            serializer.startTag(null, TAG_PERMISSION_BACKUP);
18007
18008            synchronized (mPackages) {
18009                serializeRuntimePermissionGrantsLPr(serializer, userId);
18010            }
18011
18012            serializer.endTag(null, TAG_PERMISSION_BACKUP);
18013            serializer.endDocument();
18014            serializer.flush();
18015        } catch (Exception e) {
18016            if (DEBUG_BACKUP) {
18017                Slog.e(TAG, "Unable to write default apps for backup", e);
18018            }
18019            return null;
18020        }
18021
18022        return dataStream.toByteArray();
18023    }
18024
18025    @Override
18026    public void restorePermissionGrants(byte[] backup, int userId) {
18027        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18028            throw new SecurityException("Only the system may call restorePermissionGrants()");
18029        }
18030
18031        try {
18032            final XmlPullParser parser = Xml.newPullParser();
18033            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18034            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
18035                    new BlobXmlRestorer() {
18036                        @Override
18037                        public void apply(XmlPullParser parser, int userId)
18038                                throws XmlPullParserException, IOException {
18039                            synchronized (mPackages) {
18040                                processRestoredPermissionGrantsLPr(parser, userId);
18041                            }
18042                        }
18043                    } );
18044        } catch (Exception e) {
18045            if (DEBUG_BACKUP) {
18046                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18047            }
18048        }
18049    }
18050
18051    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
18052            throws IOException {
18053        serializer.startTag(null, TAG_ALL_GRANTS);
18054
18055        final int N = mSettings.mPackages.size();
18056        for (int i = 0; i < N; i++) {
18057            final PackageSetting ps = mSettings.mPackages.valueAt(i);
18058            boolean pkgGrantsKnown = false;
18059
18060            PermissionsState packagePerms = ps.getPermissionsState();
18061
18062            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
18063                final int grantFlags = state.getFlags();
18064                // only look at grants that are not system/policy fixed
18065                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
18066                    final boolean isGranted = state.isGranted();
18067                    // And only back up the user-twiddled state bits
18068                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
18069                        final String packageName = mSettings.mPackages.keyAt(i);
18070                        if (!pkgGrantsKnown) {
18071                            serializer.startTag(null, TAG_GRANT);
18072                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
18073                            pkgGrantsKnown = true;
18074                        }
18075
18076                        final boolean userSet =
18077                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
18078                        final boolean userFixed =
18079                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
18080                        final boolean revoke =
18081                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
18082
18083                        serializer.startTag(null, TAG_PERMISSION);
18084                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
18085                        if (isGranted) {
18086                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
18087                        }
18088                        if (userSet) {
18089                            serializer.attribute(null, ATTR_USER_SET, "true");
18090                        }
18091                        if (userFixed) {
18092                            serializer.attribute(null, ATTR_USER_FIXED, "true");
18093                        }
18094                        if (revoke) {
18095                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
18096                        }
18097                        serializer.endTag(null, TAG_PERMISSION);
18098                    }
18099                }
18100            }
18101
18102            if (pkgGrantsKnown) {
18103                serializer.endTag(null, TAG_GRANT);
18104            }
18105        }
18106
18107        serializer.endTag(null, TAG_ALL_GRANTS);
18108    }
18109
18110    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
18111            throws XmlPullParserException, IOException {
18112        String pkgName = null;
18113        int outerDepth = parser.getDepth();
18114        int type;
18115        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
18116                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
18117            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
18118                continue;
18119            }
18120
18121            final String tagName = parser.getName();
18122            if (tagName.equals(TAG_GRANT)) {
18123                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
18124                if (DEBUG_BACKUP) {
18125                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
18126                }
18127            } else if (tagName.equals(TAG_PERMISSION)) {
18128
18129                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
18130                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
18131
18132                int newFlagSet = 0;
18133                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
18134                    newFlagSet |= FLAG_PERMISSION_USER_SET;
18135                }
18136                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
18137                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
18138                }
18139                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
18140                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
18141                }
18142                if (DEBUG_BACKUP) {
18143                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
18144                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
18145                }
18146                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18147                if (ps != null) {
18148                    // Already installed so we apply the grant immediately
18149                    if (DEBUG_BACKUP) {
18150                        Slog.v(TAG, "        + already installed; applying");
18151                    }
18152                    PermissionsState perms = ps.getPermissionsState();
18153                    BasePermission bp = mSettings.mPermissions.get(permName);
18154                    if (bp != null) {
18155                        if (isGranted) {
18156                            perms.grantRuntimePermission(bp, userId);
18157                        }
18158                        if (newFlagSet != 0) {
18159                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
18160                        }
18161                    }
18162                } else {
18163                    // Need to wait for post-restore install to apply the grant
18164                    if (DEBUG_BACKUP) {
18165                        Slog.v(TAG, "        - not yet installed; saving for later");
18166                    }
18167                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
18168                            isGranted, newFlagSet, userId);
18169                }
18170            } else {
18171                PackageManagerService.reportSettingsProblem(Log.WARN,
18172                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
18173                XmlUtils.skipCurrentTag(parser);
18174            }
18175        }
18176
18177        scheduleWriteSettingsLocked();
18178        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18179    }
18180
18181    @Override
18182    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
18183            int sourceUserId, int targetUserId, int flags) {
18184        mContext.enforceCallingOrSelfPermission(
18185                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18186        int callingUid = Binder.getCallingUid();
18187        enforceOwnerRights(ownerPackage, callingUid);
18188        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18189        if (intentFilter.countActions() == 0) {
18190            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
18191            return;
18192        }
18193        synchronized (mPackages) {
18194            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
18195                    ownerPackage, targetUserId, flags);
18196            CrossProfileIntentResolver resolver =
18197                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18198            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
18199            // We have all those whose filter is equal. Now checking if the rest is equal as well.
18200            if (existing != null) {
18201                int size = existing.size();
18202                for (int i = 0; i < size; i++) {
18203                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
18204                        return;
18205                    }
18206                }
18207            }
18208            resolver.addFilter(newFilter);
18209            scheduleWritePackageRestrictionsLocked(sourceUserId);
18210        }
18211    }
18212
18213    @Override
18214    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
18215        mContext.enforceCallingOrSelfPermission(
18216                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
18217        int callingUid = Binder.getCallingUid();
18218        enforceOwnerRights(ownerPackage, callingUid);
18219        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
18220        synchronized (mPackages) {
18221            CrossProfileIntentResolver resolver =
18222                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
18223            ArraySet<CrossProfileIntentFilter> set =
18224                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
18225            for (CrossProfileIntentFilter filter : set) {
18226                if (filter.getOwnerPackage().equals(ownerPackage)) {
18227                    resolver.removeFilter(filter);
18228                }
18229            }
18230            scheduleWritePackageRestrictionsLocked(sourceUserId);
18231        }
18232    }
18233
18234    // Enforcing that callingUid is owning pkg on userId
18235    private void enforceOwnerRights(String pkg, int callingUid) {
18236        // The system owns everything.
18237        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18238            return;
18239        }
18240        int callingUserId = UserHandle.getUserId(callingUid);
18241        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
18242        if (pi == null) {
18243            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
18244                    + callingUserId);
18245        }
18246        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
18247            throw new SecurityException("Calling uid " + callingUid
18248                    + " does not own package " + pkg);
18249        }
18250    }
18251
18252    @Override
18253    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
18254        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
18255    }
18256
18257    private Intent getHomeIntent() {
18258        Intent intent = new Intent(Intent.ACTION_MAIN);
18259        intent.addCategory(Intent.CATEGORY_HOME);
18260        intent.addCategory(Intent.CATEGORY_DEFAULT);
18261        return intent;
18262    }
18263
18264    private IntentFilter getHomeFilter() {
18265        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
18266        filter.addCategory(Intent.CATEGORY_HOME);
18267        filter.addCategory(Intent.CATEGORY_DEFAULT);
18268        return filter;
18269    }
18270
18271    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
18272            int userId) {
18273        Intent intent  = getHomeIntent();
18274        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
18275                PackageManager.GET_META_DATA, userId);
18276        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
18277                true, false, false, userId);
18278
18279        allHomeCandidates.clear();
18280        if (list != null) {
18281            for (ResolveInfo ri : list) {
18282                allHomeCandidates.add(ri);
18283            }
18284        }
18285        return (preferred == null || preferred.activityInfo == null)
18286                ? null
18287                : new ComponentName(preferred.activityInfo.packageName,
18288                        preferred.activityInfo.name);
18289    }
18290
18291    @Override
18292    public void setHomeActivity(ComponentName comp, int userId) {
18293        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
18294        getHomeActivitiesAsUser(homeActivities, userId);
18295
18296        boolean found = false;
18297
18298        final int size = homeActivities.size();
18299        final ComponentName[] set = new ComponentName[size];
18300        for (int i = 0; i < size; i++) {
18301            final ResolveInfo candidate = homeActivities.get(i);
18302            final ActivityInfo info = candidate.activityInfo;
18303            final ComponentName activityName = new ComponentName(info.packageName, info.name);
18304            set[i] = activityName;
18305            if (!found && activityName.equals(comp)) {
18306                found = true;
18307            }
18308        }
18309        if (!found) {
18310            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
18311                    + userId);
18312        }
18313        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
18314                set, comp, userId);
18315    }
18316
18317    private @Nullable String getSetupWizardPackageName() {
18318        final Intent intent = new Intent(Intent.ACTION_MAIN);
18319        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
18320
18321        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18322                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18323                        | MATCH_DISABLED_COMPONENTS,
18324                UserHandle.myUserId());
18325        if (matches.size() == 1) {
18326            return matches.get(0).getComponentInfo().packageName;
18327        } else {
18328            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
18329                    + ": matches=" + matches);
18330            return null;
18331        }
18332    }
18333
18334    private @Nullable String getStorageManagerPackageName() {
18335        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
18336
18337        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
18338                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
18339                        | MATCH_DISABLED_COMPONENTS,
18340                UserHandle.myUserId());
18341        if (matches.size() == 1) {
18342            return matches.get(0).getComponentInfo().packageName;
18343        } else {
18344            Slog.e(TAG, "There should probably be exactly one storage manager; found "
18345                    + matches.size() + ": matches=" + matches);
18346            return null;
18347        }
18348    }
18349
18350    @Override
18351    public void setApplicationEnabledSetting(String appPackageName,
18352            int newState, int flags, int userId, String callingPackage) {
18353        if (!sUserManager.exists(userId)) return;
18354        if (callingPackage == null) {
18355            callingPackage = Integer.toString(Binder.getCallingUid());
18356        }
18357        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
18358    }
18359
18360    @Override
18361    public void setComponentEnabledSetting(ComponentName componentName,
18362            int newState, int flags, int userId) {
18363        if (!sUserManager.exists(userId)) return;
18364        setEnabledSetting(componentName.getPackageName(),
18365                componentName.getClassName(), newState, flags, userId, null);
18366    }
18367
18368    private void setEnabledSetting(final String packageName, String className, int newState,
18369            final int flags, int userId, String callingPackage) {
18370        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
18371              || newState == COMPONENT_ENABLED_STATE_ENABLED
18372              || newState == COMPONENT_ENABLED_STATE_DISABLED
18373              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18374              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
18375            throw new IllegalArgumentException("Invalid new component state: "
18376                    + newState);
18377        }
18378        PackageSetting pkgSetting;
18379        final int uid = Binder.getCallingUid();
18380        final int permission;
18381        if (uid == Process.SYSTEM_UID) {
18382            permission = PackageManager.PERMISSION_GRANTED;
18383        } else {
18384            permission = mContext.checkCallingOrSelfPermission(
18385                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18386        }
18387        enforceCrossUserPermission(uid, userId,
18388                false /* requireFullPermission */, true /* checkShell */, "set enabled");
18389        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18390        boolean sendNow = false;
18391        boolean isApp = (className == null);
18392        String componentName = isApp ? packageName : className;
18393        int packageUid = -1;
18394        ArrayList<String> components;
18395
18396        // writer
18397        synchronized (mPackages) {
18398            pkgSetting = mSettings.mPackages.get(packageName);
18399            if (pkgSetting == null) {
18400                if (className == null) {
18401                    throw new IllegalArgumentException("Unknown package: " + packageName);
18402                }
18403                throw new IllegalArgumentException(
18404                        "Unknown component: " + packageName + "/" + className);
18405            }
18406        }
18407
18408        // Limit who can change which apps
18409        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
18410            // Don't allow apps that don't have permission to modify other apps
18411            if (!allowedByPermission) {
18412                throw new SecurityException(
18413                        "Permission Denial: attempt to change component state from pid="
18414                        + Binder.getCallingPid()
18415                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
18416            }
18417            // Don't allow changing protected packages.
18418            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
18419                throw new SecurityException("Cannot disable a protected package: " + packageName);
18420            }
18421        }
18422
18423        synchronized (mPackages) {
18424            if (uid == Process.SHELL_UID
18425                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
18426                // Shell can only change whole packages between ENABLED and DISABLED_USER states
18427                // unless it is a test package.
18428                int oldState = pkgSetting.getEnabled(userId);
18429                if (className == null
18430                    &&
18431                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
18432                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
18433                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
18434                    &&
18435                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
18436                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
18437                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
18438                    // ok
18439                } else {
18440                    throw new SecurityException(
18441                            "Shell cannot change component state for " + packageName + "/"
18442                            + className + " to " + newState);
18443                }
18444            }
18445            if (className == null) {
18446                // We're dealing with an application/package level state change
18447                if (pkgSetting.getEnabled(userId) == newState) {
18448                    // Nothing to do
18449                    return;
18450                }
18451                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
18452                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
18453                    // Don't care about who enables an app.
18454                    callingPackage = null;
18455                }
18456                pkgSetting.setEnabled(newState, userId, callingPackage);
18457                // pkgSetting.pkg.mSetEnabled = newState;
18458            } else {
18459                // We're dealing with a component level state change
18460                // First, verify that this is a valid class name.
18461                PackageParser.Package pkg = pkgSetting.pkg;
18462                if (pkg == null || !pkg.hasComponentClassName(className)) {
18463                    if (pkg != null &&
18464                            pkg.applicationInfo.targetSdkVersion >=
18465                                    Build.VERSION_CODES.JELLY_BEAN) {
18466                        throw new IllegalArgumentException("Component class " + className
18467                                + " does not exist in " + packageName);
18468                    } else {
18469                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18470                                + className + " does not exist in " + packageName);
18471                    }
18472                }
18473                switch (newState) {
18474                case COMPONENT_ENABLED_STATE_ENABLED:
18475                    if (!pkgSetting.enableComponentLPw(className, userId)) {
18476                        return;
18477                    }
18478                    break;
18479                case COMPONENT_ENABLED_STATE_DISABLED:
18480                    if (!pkgSetting.disableComponentLPw(className, userId)) {
18481                        return;
18482                    }
18483                    break;
18484                case COMPONENT_ENABLED_STATE_DEFAULT:
18485                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
18486                        return;
18487                    }
18488                    break;
18489                default:
18490                    Slog.e(TAG, "Invalid new component state: " + newState);
18491                    return;
18492                }
18493            }
18494            scheduleWritePackageRestrictionsLocked(userId);
18495            components = mPendingBroadcasts.get(userId, packageName);
18496            final boolean newPackage = components == null;
18497            if (newPackage) {
18498                components = new ArrayList<String>();
18499            }
18500            if (!components.contains(componentName)) {
18501                components.add(componentName);
18502            }
18503            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18504                sendNow = true;
18505                // Purge entry from pending broadcast list if another one exists already
18506                // since we are sending one right away.
18507                mPendingBroadcasts.remove(userId, packageName);
18508            } else {
18509                if (newPackage) {
18510                    mPendingBroadcasts.put(userId, packageName, components);
18511                }
18512                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18513                    // Schedule a message
18514                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18515                }
18516            }
18517        }
18518
18519        long callingId = Binder.clearCallingIdentity();
18520        try {
18521            if (sendNow) {
18522                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18523                sendPackageChangedBroadcast(packageName,
18524                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18525            }
18526        } finally {
18527            Binder.restoreCallingIdentity(callingId);
18528        }
18529    }
18530
18531    @Override
18532    public void flushPackageRestrictionsAsUser(int userId) {
18533        if (!sUserManager.exists(userId)) {
18534            return;
18535        }
18536        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18537                false /* checkShell */, "flushPackageRestrictions");
18538        synchronized (mPackages) {
18539            mSettings.writePackageRestrictionsLPr(userId);
18540            mDirtyUsers.remove(userId);
18541            if (mDirtyUsers.isEmpty()) {
18542                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18543            }
18544        }
18545    }
18546
18547    private void sendPackageChangedBroadcast(String packageName,
18548            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18549        if (DEBUG_INSTALL)
18550            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18551                    + componentNames);
18552        Bundle extras = new Bundle(4);
18553        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18554        String nameList[] = new String[componentNames.size()];
18555        componentNames.toArray(nameList);
18556        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18557        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18558        extras.putInt(Intent.EXTRA_UID, packageUid);
18559        // If this is not reporting a change of the overall package, then only send it
18560        // to registered receivers.  We don't want to launch a swath of apps for every
18561        // little component state change.
18562        final int flags = !componentNames.contains(packageName)
18563                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18564        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18565                new int[] {UserHandle.getUserId(packageUid)});
18566    }
18567
18568    @Override
18569    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18570        if (!sUserManager.exists(userId)) return;
18571        final int uid = Binder.getCallingUid();
18572        final int permission = mContext.checkCallingOrSelfPermission(
18573                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18574        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18575        enforceCrossUserPermission(uid, userId,
18576                true /* requireFullPermission */, true /* checkShell */, "stop package");
18577        // writer
18578        synchronized (mPackages) {
18579            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18580                    allowedByPermission, uid, userId)) {
18581                scheduleWritePackageRestrictionsLocked(userId);
18582            }
18583        }
18584    }
18585
18586    @Override
18587    public String getInstallerPackageName(String packageName) {
18588        // reader
18589        synchronized (mPackages) {
18590            return mSettings.getInstallerPackageNameLPr(packageName);
18591        }
18592    }
18593
18594    public boolean isOrphaned(String packageName) {
18595        // reader
18596        synchronized (mPackages) {
18597            return mSettings.isOrphaned(packageName);
18598        }
18599    }
18600
18601    @Override
18602    public int getApplicationEnabledSetting(String packageName, int userId) {
18603        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18604        int uid = Binder.getCallingUid();
18605        enforceCrossUserPermission(uid, userId,
18606                false /* requireFullPermission */, false /* checkShell */, "get enabled");
18607        // reader
18608        synchronized (mPackages) {
18609            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18610        }
18611    }
18612
18613    @Override
18614    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18615        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18616        int uid = Binder.getCallingUid();
18617        enforceCrossUserPermission(uid, userId,
18618                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18619        // reader
18620        synchronized (mPackages) {
18621            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18622        }
18623    }
18624
18625    @Override
18626    public void enterSafeMode() {
18627        enforceSystemOrRoot("Only the system can request entering safe mode");
18628
18629        if (!mSystemReady) {
18630            mSafeMode = true;
18631        }
18632    }
18633
18634    @Override
18635    public void systemReady() {
18636        mSystemReady = true;
18637
18638        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18639        // disabled after already being started.
18640        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18641                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18642
18643        // Read the compatibilty setting when the system is ready.
18644        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18645                mContext.getContentResolver(),
18646                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18647        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18648        if (DEBUG_SETTINGS) {
18649            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18650        }
18651
18652        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18653
18654        synchronized (mPackages) {
18655            // Verify that all of the preferred activity components actually
18656            // exist.  It is possible for applications to be updated and at
18657            // that point remove a previously declared activity component that
18658            // had been set as a preferred activity.  We try to clean this up
18659            // the next time we encounter that preferred activity, but it is
18660            // possible for the user flow to never be able to return to that
18661            // situation so here we do a sanity check to make sure we haven't
18662            // left any junk around.
18663            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18664            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18665                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18666                removed.clear();
18667                for (PreferredActivity pa : pir.filterSet()) {
18668                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18669                        removed.add(pa);
18670                    }
18671                }
18672                if (removed.size() > 0) {
18673                    for (int r=0; r<removed.size(); r++) {
18674                        PreferredActivity pa = removed.get(r);
18675                        Slog.w(TAG, "Removing dangling preferred activity: "
18676                                + pa.mPref.mComponent);
18677                        pir.removeFilter(pa);
18678                    }
18679                    mSettings.writePackageRestrictionsLPr(
18680                            mSettings.mPreferredActivities.keyAt(i));
18681                }
18682            }
18683
18684            for (int userId : UserManagerService.getInstance().getUserIds()) {
18685                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18686                    grantPermissionsUserIds = ArrayUtils.appendInt(
18687                            grantPermissionsUserIds, userId);
18688                }
18689            }
18690        }
18691        sUserManager.systemReady();
18692
18693        // If we upgraded grant all default permissions before kicking off.
18694        for (int userId : grantPermissionsUserIds) {
18695            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18696        }
18697
18698        // If we did not grant default permissions, we preload from this the
18699        // default permission exceptions lazily to ensure we don't hit the
18700        // disk on a new user creation.
18701        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18702            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18703        }
18704
18705        // Kick off any messages waiting for system ready
18706        if (mPostSystemReadyMessages != null) {
18707            for (Message msg : mPostSystemReadyMessages) {
18708                msg.sendToTarget();
18709            }
18710            mPostSystemReadyMessages = null;
18711        }
18712
18713        // Watch for external volumes that come and go over time
18714        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18715        storage.registerListener(mStorageListener);
18716
18717        mInstallerService.systemReady();
18718        mPackageDexOptimizer.systemReady();
18719
18720        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
18721                StorageManagerInternal.class);
18722        StorageManagerInternal.addExternalStoragePolicy(
18723                new StorageManagerInternal.ExternalStorageMountPolicy() {
18724            @Override
18725            public int getMountMode(int uid, String packageName) {
18726                if (Process.isIsolated(uid)) {
18727                    return Zygote.MOUNT_EXTERNAL_NONE;
18728                }
18729                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18730                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18731                }
18732                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18733                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18734                }
18735                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18736                    return Zygote.MOUNT_EXTERNAL_READ;
18737                }
18738                return Zygote.MOUNT_EXTERNAL_WRITE;
18739            }
18740
18741            @Override
18742            public boolean hasExternalStorage(int uid, String packageName) {
18743                return true;
18744            }
18745        });
18746
18747        // Now that we're mostly running, clean up stale users and apps
18748        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18749        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18750    }
18751
18752    @Override
18753    public boolean isSafeMode() {
18754        return mSafeMode;
18755    }
18756
18757    @Override
18758    public boolean hasSystemUidErrors() {
18759        return mHasSystemUidErrors;
18760    }
18761
18762    static String arrayToString(int[] array) {
18763        StringBuffer buf = new StringBuffer(128);
18764        buf.append('[');
18765        if (array != null) {
18766            for (int i=0; i<array.length; i++) {
18767                if (i > 0) buf.append(", ");
18768                buf.append(array[i]);
18769            }
18770        }
18771        buf.append(']');
18772        return buf.toString();
18773    }
18774
18775    static class DumpState {
18776        public static final int DUMP_LIBS = 1 << 0;
18777        public static final int DUMP_FEATURES = 1 << 1;
18778        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18779        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18780        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18781        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18782        public static final int DUMP_PERMISSIONS = 1 << 6;
18783        public static final int DUMP_PACKAGES = 1 << 7;
18784        public static final int DUMP_SHARED_USERS = 1 << 8;
18785        public static final int DUMP_MESSAGES = 1 << 9;
18786        public static final int DUMP_PROVIDERS = 1 << 10;
18787        public static final int DUMP_VERIFIERS = 1 << 11;
18788        public static final int DUMP_PREFERRED = 1 << 12;
18789        public static final int DUMP_PREFERRED_XML = 1 << 13;
18790        public static final int DUMP_KEYSETS = 1 << 14;
18791        public static final int DUMP_VERSION = 1 << 15;
18792        public static final int DUMP_INSTALLS = 1 << 16;
18793        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18794        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18795        public static final int DUMP_FROZEN = 1 << 19;
18796        public static final int DUMP_DEXOPT = 1 << 20;
18797        public static final int DUMP_COMPILER_STATS = 1 << 21;
18798
18799        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18800
18801        private int mTypes;
18802
18803        private int mOptions;
18804
18805        private boolean mTitlePrinted;
18806
18807        private SharedUserSetting mSharedUser;
18808
18809        public boolean isDumping(int type) {
18810            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18811                return true;
18812            }
18813
18814            return (mTypes & type) != 0;
18815        }
18816
18817        public void setDump(int type) {
18818            mTypes |= type;
18819        }
18820
18821        public boolean isOptionEnabled(int option) {
18822            return (mOptions & option) != 0;
18823        }
18824
18825        public void setOptionEnabled(int option) {
18826            mOptions |= option;
18827        }
18828
18829        public boolean onTitlePrinted() {
18830            final boolean printed = mTitlePrinted;
18831            mTitlePrinted = true;
18832            return printed;
18833        }
18834
18835        public boolean getTitlePrinted() {
18836            return mTitlePrinted;
18837        }
18838
18839        public void setTitlePrinted(boolean enabled) {
18840            mTitlePrinted = enabled;
18841        }
18842
18843        public SharedUserSetting getSharedUser() {
18844            return mSharedUser;
18845        }
18846
18847        public void setSharedUser(SharedUserSetting user) {
18848            mSharedUser = user;
18849        }
18850    }
18851
18852    @Override
18853    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18854            FileDescriptor err, String[] args, ShellCallback callback,
18855            ResultReceiver resultReceiver) {
18856        (new PackageManagerShellCommand(this)).exec(
18857                this, in, out, err, args, callback, resultReceiver);
18858    }
18859
18860    @Override
18861    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18862        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18863                != PackageManager.PERMISSION_GRANTED) {
18864            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18865                    + Binder.getCallingPid()
18866                    + ", uid=" + Binder.getCallingUid()
18867                    + " without permission "
18868                    + android.Manifest.permission.DUMP);
18869            return;
18870        }
18871
18872        DumpState dumpState = new DumpState();
18873        boolean fullPreferred = false;
18874        boolean checkin = false;
18875
18876        String packageName = null;
18877        ArraySet<String> permissionNames = null;
18878
18879        int opti = 0;
18880        while (opti < args.length) {
18881            String opt = args[opti];
18882            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18883                break;
18884            }
18885            opti++;
18886
18887            if ("-a".equals(opt)) {
18888                // Right now we only know how to print all.
18889            } else if ("-h".equals(opt)) {
18890                pw.println("Package manager dump options:");
18891                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18892                pw.println("    --checkin: dump for a checkin");
18893                pw.println("    -f: print details of intent filters");
18894                pw.println("    -h: print this help");
18895                pw.println("  cmd may be one of:");
18896                pw.println("    l[ibraries]: list known shared libraries");
18897                pw.println("    f[eatures]: list device features");
18898                pw.println("    k[eysets]: print known keysets");
18899                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18900                pw.println("    perm[issions]: dump permissions");
18901                pw.println("    permission [name ...]: dump declaration and use of given permission");
18902                pw.println("    pref[erred]: print preferred package settings");
18903                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18904                pw.println("    prov[iders]: dump content providers");
18905                pw.println("    p[ackages]: dump installed packages");
18906                pw.println("    s[hared-users]: dump shared user IDs");
18907                pw.println("    m[essages]: print collected runtime messages");
18908                pw.println("    v[erifiers]: print package verifier info");
18909                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18910                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18911                pw.println("    version: print database version info");
18912                pw.println("    write: write current settings now");
18913                pw.println("    installs: details about install sessions");
18914                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18915                pw.println("    dexopt: dump dexopt state");
18916                pw.println("    compiler-stats: dump compiler statistics");
18917                pw.println("    <package.name>: info about given package");
18918                return;
18919            } else if ("--checkin".equals(opt)) {
18920                checkin = true;
18921            } else if ("-f".equals(opt)) {
18922                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18923            } else {
18924                pw.println("Unknown argument: " + opt + "; use -h for help");
18925            }
18926        }
18927
18928        // Is the caller requesting to dump a particular piece of data?
18929        if (opti < args.length) {
18930            String cmd = args[opti];
18931            opti++;
18932            // Is this a package name?
18933            if ("android".equals(cmd) || cmd.contains(".")) {
18934                packageName = cmd;
18935                // When dumping a single package, we always dump all of its
18936                // filter information since the amount of data will be reasonable.
18937                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18938            } else if ("check-permission".equals(cmd)) {
18939                if (opti >= args.length) {
18940                    pw.println("Error: check-permission missing permission argument");
18941                    return;
18942                }
18943                String perm = args[opti];
18944                opti++;
18945                if (opti >= args.length) {
18946                    pw.println("Error: check-permission missing package argument");
18947                    return;
18948                }
18949                String pkg = args[opti];
18950                opti++;
18951                int user = UserHandle.getUserId(Binder.getCallingUid());
18952                if (opti < args.length) {
18953                    try {
18954                        user = Integer.parseInt(args[opti]);
18955                    } catch (NumberFormatException e) {
18956                        pw.println("Error: check-permission user argument is not a number: "
18957                                + args[opti]);
18958                        return;
18959                    }
18960                }
18961                pw.println(checkPermission(perm, pkg, user));
18962                return;
18963            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18964                dumpState.setDump(DumpState.DUMP_LIBS);
18965            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18966                dumpState.setDump(DumpState.DUMP_FEATURES);
18967            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18968                if (opti >= args.length) {
18969                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18970                            | DumpState.DUMP_SERVICE_RESOLVERS
18971                            | DumpState.DUMP_RECEIVER_RESOLVERS
18972                            | DumpState.DUMP_CONTENT_RESOLVERS);
18973                } else {
18974                    while (opti < args.length) {
18975                        String name = args[opti];
18976                        if ("a".equals(name) || "activity".equals(name)) {
18977                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18978                        } else if ("s".equals(name) || "service".equals(name)) {
18979                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18980                        } else if ("r".equals(name) || "receiver".equals(name)) {
18981                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18982                        } else if ("c".equals(name) || "content".equals(name)) {
18983                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18984                        } else {
18985                            pw.println("Error: unknown resolver table type: " + name);
18986                            return;
18987                        }
18988                        opti++;
18989                    }
18990                }
18991            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18992                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18993            } else if ("permission".equals(cmd)) {
18994                if (opti >= args.length) {
18995                    pw.println("Error: permission requires permission name");
18996                    return;
18997                }
18998                permissionNames = new ArraySet<>();
18999                while (opti < args.length) {
19000                    permissionNames.add(args[opti]);
19001                    opti++;
19002                }
19003                dumpState.setDump(DumpState.DUMP_PERMISSIONS
19004                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
19005            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
19006                dumpState.setDump(DumpState.DUMP_PREFERRED);
19007            } else if ("preferred-xml".equals(cmd)) {
19008                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
19009                if (opti < args.length && "--full".equals(args[opti])) {
19010                    fullPreferred = true;
19011                    opti++;
19012                }
19013            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
19014                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
19015            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
19016                dumpState.setDump(DumpState.DUMP_PACKAGES);
19017            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
19018                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
19019            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
19020                dumpState.setDump(DumpState.DUMP_PROVIDERS);
19021            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
19022                dumpState.setDump(DumpState.DUMP_MESSAGES);
19023            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
19024                dumpState.setDump(DumpState.DUMP_VERIFIERS);
19025            } else if ("i".equals(cmd) || "ifv".equals(cmd)
19026                    || "intent-filter-verifiers".equals(cmd)) {
19027                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
19028            } else if ("version".equals(cmd)) {
19029                dumpState.setDump(DumpState.DUMP_VERSION);
19030            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
19031                dumpState.setDump(DumpState.DUMP_KEYSETS);
19032            } else if ("installs".equals(cmd)) {
19033                dumpState.setDump(DumpState.DUMP_INSTALLS);
19034            } else if ("frozen".equals(cmd)) {
19035                dumpState.setDump(DumpState.DUMP_FROZEN);
19036            } else if ("dexopt".equals(cmd)) {
19037                dumpState.setDump(DumpState.DUMP_DEXOPT);
19038            } else if ("compiler-stats".equals(cmd)) {
19039                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
19040            } else if ("write".equals(cmd)) {
19041                synchronized (mPackages) {
19042                    mSettings.writeLPr();
19043                    pw.println("Settings written.");
19044                    return;
19045                }
19046            }
19047        }
19048
19049        if (checkin) {
19050            pw.println("vers,1");
19051        }
19052
19053        // reader
19054        synchronized (mPackages) {
19055            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
19056                if (!checkin) {
19057                    if (dumpState.onTitlePrinted())
19058                        pw.println();
19059                    pw.println("Database versions:");
19060                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
19061                }
19062            }
19063
19064            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
19065                if (!checkin) {
19066                    if (dumpState.onTitlePrinted())
19067                        pw.println();
19068                    pw.println("Verifiers:");
19069                    pw.print("  Required: ");
19070                    pw.print(mRequiredVerifierPackage);
19071                    pw.print(" (uid=");
19072                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19073                            UserHandle.USER_SYSTEM));
19074                    pw.println(")");
19075                } else if (mRequiredVerifierPackage != null) {
19076                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
19077                    pw.print(",");
19078                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
19079                            UserHandle.USER_SYSTEM));
19080                }
19081            }
19082
19083            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
19084                    packageName == null) {
19085                if (mIntentFilterVerifierComponent != null) {
19086                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
19087                    if (!checkin) {
19088                        if (dumpState.onTitlePrinted())
19089                            pw.println();
19090                        pw.println("Intent Filter Verifier:");
19091                        pw.print("  Using: ");
19092                        pw.print(verifierPackageName);
19093                        pw.print(" (uid=");
19094                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19095                                UserHandle.USER_SYSTEM));
19096                        pw.println(")");
19097                    } else if (verifierPackageName != null) {
19098                        pw.print("ifv,"); pw.print(verifierPackageName);
19099                        pw.print(",");
19100                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
19101                                UserHandle.USER_SYSTEM));
19102                    }
19103                } else {
19104                    pw.println();
19105                    pw.println("No Intent Filter Verifier available!");
19106                }
19107            }
19108
19109            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
19110                boolean printedHeader = false;
19111                final Iterator<String> it = mSharedLibraries.keySet().iterator();
19112                while (it.hasNext()) {
19113                    String name = it.next();
19114                    SharedLibraryEntry ent = mSharedLibraries.get(name);
19115                    if (!checkin) {
19116                        if (!printedHeader) {
19117                            if (dumpState.onTitlePrinted())
19118                                pw.println();
19119                            pw.println("Libraries:");
19120                            printedHeader = true;
19121                        }
19122                        pw.print("  ");
19123                    } else {
19124                        pw.print("lib,");
19125                    }
19126                    pw.print(name);
19127                    if (!checkin) {
19128                        pw.print(" -> ");
19129                    }
19130                    if (ent.path != null) {
19131                        if (!checkin) {
19132                            pw.print("(jar) ");
19133                            pw.print(ent.path);
19134                        } else {
19135                            pw.print(",jar,");
19136                            pw.print(ent.path);
19137                        }
19138                    } else {
19139                        if (!checkin) {
19140                            pw.print("(apk) ");
19141                            pw.print(ent.apk);
19142                        } else {
19143                            pw.print(",apk,");
19144                            pw.print(ent.apk);
19145                        }
19146                    }
19147                    pw.println();
19148                }
19149            }
19150
19151            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
19152                if (dumpState.onTitlePrinted())
19153                    pw.println();
19154                if (!checkin) {
19155                    pw.println("Features:");
19156                }
19157
19158                for (FeatureInfo feat : mAvailableFeatures.values()) {
19159                    if (checkin) {
19160                        pw.print("feat,");
19161                        pw.print(feat.name);
19162                        pw.print(",");
19163                        pw.println(feat.version);
19164                    } else {
19165                        pw.print("  ");
19166                        pw.print(feat.name);
19167                        if (feat.version > 0) {
19168                            pw.print(" version=");
19169                            pw.print(feat.version);
19170                        }
19171                        pw.println();
19172                    }
19173                }
19174            }
19175
19176            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
19177                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
19178                        : "Activity Resolver Table:", "  ", packageName,
19179                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19180                    dumpState.setTitlePrinted(true);
19181                }
19182            }
19183            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
19184                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
19185                        : "Receiver Resolver Table:", "  ", packageName,
19186                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19187                    dumpState.setTitlePrinted(true);
19188                }
19189            }
19190            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
19191                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
19192                        : "Service Resolver Table:", "  ", packageName,
19193                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19194                    dumpState.setTitlePrinted(true);
19195                }
19196            }
19197            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
19198                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
19199                        : "Provider Resolver Table:", "  ", packageName,
19200                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
19201                    dumpState.setTitlePrinted(true);
19202                }
19203            }
19204
19205            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
19206                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19207                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19208                    int user = mSettings.mPreferredActivities.keyAt(i);
19209                    if (pir.dump(pw,
19210                            dumpState.getTitlePrinted()
19211                                ? "\nPreferred Activities User " + user + ":"
19212                                : "Preferred Activities User " + user + ":", "  ",
19213                            packageName, true, false)) {
19214                        dumpState.setTitlePrinted(true);
19215                    }
19216                }
19217            }
19218
19219            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
19220                pw.flush();
19221                FileOutputStream fout = new FileOutputStream(fd);
19222                BufferedOutputStream str = new BufferedOutputStream(fout);
19223                XmlSerializer serializer = new FastXmlSerializer();
19224                try {
19225                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
19226                    serializer.startDocument(null, true);
19227                    serializer.setFeature(
19228                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
19229                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
19230                    serializer.endDocument();
19231                    serializer.flush();
19232                } catch (IllegalArgumentException e) {
19233                    pw.println("Failed writing: " + e);
19234                } catch (IllegalStateException e) {
19235                    pw.println("Failed writing: " + e);
19236                } catch (IOException e) {
19237                    pw.println("Failed writing: " + e);
19238                }
19239            }
19240
19241            if (!checkin
19242                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
19243                    && packageName == null) {
19244                pw.println();
19245                int count = mSettings.mPackages.size();
19246                if (count == 0) {
19247                    pw.println("No applications!");
19248                    pw.println();
19249                } else {
19250                    final String prefix = "  ";
19251                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
19252                    if (allPackageSettings.size() == 0) {
19253                        pw.println("No domain preferred apps!");
19254                        pw.println();
19255                    } else {
19256                        pw.println("App verification status:");
19257                        pw.println();
19258                        count = 0;
19259                        for (PackageSetting ps : allPackageSettings) {
19260                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
19261                            if (ivi == null || ivi.getPackageName() == null) continue;
19262                            pw.println(prefix + "Package: " + ivi.getPackageName());
19263                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
19264                            pw.println(prefix + "Status:  " + ivi.getStatusString());
19265                            pw.println();
19266                            count++;
19267                        }
19268                        if (count == 0) {
19269                            pw.println(prefix + "No app verification established.");
19270                            pw.println();
19271                        }
19272                        for (int userId : sUserManager.getUserIds()) {
19273                            pw.println("App linkages for user " + userId + ":");
19274                            pw.println();
19275                            count = 0;
19276                            for (PackageSetting ps : allPackageSettings) {
19277                                final long status = ps.getDomainVerificationStatusForUser(userId);
19278                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
19279                                    continue;
19280                                }
19281                                pw.println(prefix + "Package: " + ps.name);
19282                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
19283                                String statusStr = IntentFilterVerificationInfo.
19284                                        getStatusStringFromValue(status);
19285                                pw.println(prefix + "Status:  " + statusStr);
19286                                pw.println();
19287                                count++;
19288                            }
19289                            if (count == 0) {
19290                                pw.println(prefix + "No configured app linkages.");
19291                                pw.println();
19292                            }
19293                        }
19294                    }
19295                }
19296            }
19297
19298            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
19299                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
19300                if (packageName == null && permissionNames == null) {
19301                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
19302                        if (iperm == 0) {
19303                            if (dumpState.onTitlePrinted())
19304                                pw.println();
19305                            pw.println("AppOp Permissions:");
19306                        }
19307                        pw.print("  AppOp Permission ");
19308                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
19309                        pw.println(":");
19310                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
19311                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
19312                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
19313                        }
19314                    }
19315                }
19316            }
19317
19318            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
19319                boolean printedSomething = false;
19320                for (PackageParser.Provider p : mProviders.mProviders.values()) {
19321                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19322                        continue;
19323                    }
19324                    if (!printedSomething) {
19325                        if (dumpState.onTitlePrinted())
19326                            pw.println();
19327                        pw.println("Registered ContentProviders:");
19328                        printedSomething = true;
19329                    }
19330                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
19331                    pw.print("    "); pw.println(p.toString());
19332                }
19333                printedSomething = false;
19334                for (Map.Entry<String, PackageParser.Provider> entry :
19335                        mProvidersByAuthority.entrySet()) {
19336                    PackageParser.Provider p = entry.getValue();
19337                    if (packageName != null && !packageName.equals(p.info.packageName)) {
19338                        continue;
19339                    }
19340                    if (!printedSomething) {
19341                        if (dumpState.onTitlePrinted())
19342                            pw.println();
19343                        pw.println("ContentProvider Authorities:");
19344                        printedSomething = true;
19345                    }
19346                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
19347                    pw.print("    "); pw.println(p.toString());
19348                    if (p.info != null && p.info.applicationInfo != null) {
19349                        final String appInfo = p.info.applicationInfo.toString();
19350                        pw.print("      applicationInfo="); pw.println(appInfo);
19351                    }
19352                }
19353            }
19354
19355            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
19356                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
19357            }
19358
19359            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
19360                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
19361            }
19362
19363            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
19364                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
19365            }
19366
19367            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
19368                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
19369            }
19370
19371            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
19372                // XXX should handle packageName != null by dumping only install data that
19373                // the given package is involved with.
19374                if (dumpState.onTitlePrinted()) pw.println();
19375                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
19376            }
19377
19378            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
19379                // XXX should handle packageName != null by dumping only install data that
19380                // the given package is involved with.
19381                if (dumpState.onTitlePrinted()) pw.println();
19382
19383                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19384                ipw.println();
19385                ipw.println("Frozen packages:");
19386                ipw.increaseIndent();
19387                if (mFrozenPackages.size() == 0) {
19388                    ipw.println("(none)");
19389                } else {
19390                    for (int i = 0; i < mFrozenPackages.size(); i++) {
19391                        ipw.println(mFrozenPackages.valueAt(i));
19392                    }
19393                }
19394                ipw.decreaseIndent();
19395            }
19396
19397            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
19398                if (dumpState.onTitlePrinted()) pw.println();
19399                dumpDexoptStateLPr(pw, packageName);
19400            }
19401
19402            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
19403                if (dumpState.onTitlePrinted()) pw.println();
19404                dumpCompilerStatsLPr(pw, packageName);
19405            }
19406
19407            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
19408                if (dumpState.onTitlePrinted()) pw.println();
19409                mSettings.dumpReadMessagesLPr(pw, dumpState);
19410
19411                pw.println();
19412                pw.println("Package warning messages:");
19413                BufferedReader in = null;
19414                String line = null;
19415                try {
19416                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19417                    while ((line = in.readLine()) != null) {
19418                        if (line.contains("ignored: updated version")) continue;
19419                        pw.println(line);
19420                    }
19421                } catch (IOException ignored) {
19422                } finally {
19423                    IoUtils.closeQuietly(in);
19424                }
19425            }
19426
19427            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
19428                BufferedReader in = null;
19429                String line = null;
19430                try {
19431                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
19432                    while ((line = in.readLine()) != null) {
19433                        if (line.contains("ignored: updated version")) continue;
19434                        pw.print("msg,");
19435                        pw.println(line);
19436                    }
19437                } catch (IOException ignored) {
19438                } finally {
19439                    IoUtils.closeQuietly(in);
19440                }
19441            }
19442        }
19443    }
19444
19445    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
19446        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19447        ipw.println();
19448        ipw.println("Dexopt state:");
19449        ipw.increaseIndent();
19450        Collection<PackageParser.Package> packages = null;
19451        if (packageName != null) {
19452            PackageParser.Package targetPackage = mPackages.get(packageName);
19453            if (targetPackage != null) {
19454                packages = Collections.singletonList(targetPackage);
19455            } else {
19456                ipw.println("Unable to find package: " + packageName);
19457                return;
19458            }
19459        } else {
19460            packages = mPackages.values();
19461        }
19462
19463        for (PackageParser.Package pkg : packages) {
19464            ipw.println("[" + pkg.packageName + "]");
19465            ipw.increaseIndent();
19466            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19467            ipw.decreaseIndent();
19468        }
19469    }
19470
19471    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19472        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19473        ipw.println();
19474        ipw.println("Compiler stats:");
19475        ipw.increaseIndent();
19476        Collection<PackageParser.Package> packages = null;
19477        if (packageName != null) {
19478            PackageParser.Package targetPackage = mPackages.get(packageName);
19479            if (targetPackage != null) {
19480                packages = Collections.singletonList(targetPackage);
19481            } else {
19482                ipw.println("Unable to find package: " + packageName);
19483                return;
19484            }
19485        } else {
19486            packages = mPackages.values();
19487        }
19488
19489        for (PackageParser.Package pkg : packages) {
19490            ipw.println("[" + pkg.packageName + "]");
19491            ipw.increaseIndent();
19492
19493            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19494            if (stats == null) {
19495                ipw.println("(No recorded stats)");
19496            } else {
19497                stats.dump(ipw);
19498            }
19499            ipw.decreaseIndent();
19500        }
19501    }
19502
19503    private String dumpDomainString(String packageName) {
19504        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19505                .getList();
19506        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19507
19508        ArraySet<String> result = new ArraySet<>();
19509        if (iviList.size() > 0) {
19510            for (IntentFilterVerificationInfo ivi : iviList) {
19511                for (String host : ivi.getDomains()) {
19512                    result.add(host);
19513                }
19514            }
19515        }
19516        if (filters != null && filters.size() > 0) {
19517            for (IntentFilter filter : filters) {
19518                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19519                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19520                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19521                    result.addAll(filter.getHostsList());
19522                }
19523            }
19524        }
19525
19526        StringBuilder sb = new StringBuilder(result.size() * 16);
19527        for (String domain : result) {
19528            if (sb.length() > 0) sb.append(" ");
19529            sb.append(domain);
19530        }
19531        return sb.toString();
19532    }
19533
19534    // ------- apps on sdcard specific code -------
19535    static final boolean DEBUG_SD_INSTALL = false;
19536
19537    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19538
19539    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19540
19541    private boolean mMediaMounted = false;
19542
19543    static String getEncryptKey() {
19544        try {
19545            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19546                    SD_ENCRYPTION_KEYSTORE_NAME);
19547            if (sdEncKey == null) {
19548                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19549                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19550                if (sdEncKey == null) {
19551                    Slog.e(TAG, "Failed to create encryption keys");
19552                    return null;
19553                }
19554            }
19555            return sdEncKey;
19556        } catch (NoSuchAlgorithmException nsae) {
19557            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19558            return null;
19559        } catch (IOException ioe) {
19560            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19561            return null;
19562        }
19563    }
19564
19565    /*
19566     * Update media status on PackageManager.
19567     */
19568    @Override
19569    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19570        int callingUid = Binder.getCallingUid();
19571        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19572            throw new SecurityException("Media status can only be updated by the system");
19573        }
19574        // reader; this apparently protects mMediaMounted, but should probably
19575        // be a different lock in that case.
19576        synchronized (mPackages) {
19577            Log.i(TAG, "Updating external media status from "
19578                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
19579                    + (mediaStatus ? "mounted" : "unmounted"));
19580            if (DEBUG_SD_INSTALL)
19581                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19582                        + ", mMediaMounted=" + mMediaMounted);
19583            if (mediaStatus == mMediaMounted) {
19584                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19585                        : 0, -1);
19586                mHandler.sendMessage(msg);
19587                return;
19588            }
19589            mMediaMounted = mediaStatus;
19590        }
19591        // Queue up an async operation since the package installation may take a
19592        // little while.
19593        mHandler.post(new Runnable() {
19594            public void run() {
19595                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19596            }
19597        });
19598    }
19599
19600    /**
19601     * Called by StorageManagerService when the initial ASECs to scan are available.
19602     * Should block until all the ASEC containers are finished being scanned.
19603     */
19604    public void scanAvailableAsecs() {
19605        updateExternalMediaStatusInner(true, false, false);
19606    }
19607
19608    /*
19609     * Collect information of applications on external media, map them against
19610     * existing containers and update information based on current mount status.
19611     * Please note that we always have to report status if reportStatus has been
19612     * set to true especially when unloading packages.
19613     */
19614    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19615            boolean externalStorage) {
19616        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19617        int[] uidArr = EmptyArray.INT;
19618
19619        final String[] list = PackageHelper.getSecureContainerList();
19620        if (ArrayUtils.isEmpty(list)) {
19621            Log.i(TAG, "No secure containers found");
19622        } else {
19623            // Process list of secure containers and categorize them
19624            // as active or stale based on their package internal state.
19625
19626            // reader
19627            synchronized (mPackages) {
19628                for (String cid : list) {
19629                    // Leave stages untouched for now; installer service owns them
19630                    if (PackageInstallerService.isStageName(cid)) continue;
19631
19632                    if (DEBUG_SD_INSTALL)
19633                        Log.i(TAG, "Processing container " + cid);
19634                    String pkgName = getAsecPackageName(cid);
19635                    if (pkgName == null) {
19636                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
19637                        continue;
19638                    }
19639                    if (DEBUG_SD_INSTALL)
19640                        Log.i(TAG, "Looking for pkg : " + pkgName);
19641
19642                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
19643                    if (ps == null) {
19644                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19645                        continue;
19646                    }
19647
19648                    /*
19649                     * Skip packages that are not external if we're unmounting
19650                     * external storage.
19651                     */
19652                    if (externalStorage && !isMounted && !isExternal(ps)) {
19653                        continue;
19654                    }
19655
19656                    final AsecInstallArgs args = new AsecInstallArgs(cid,
19657                            getAppDexInstructionSets(ps), ps.isForwardLocked());
19658                    // The package status is changed only if the code path
19659                    // matches between settings and the container id.
19660                    if (ps.codePathString != null
19661                            && ps.codePathString.startsWith(args.getCodePath())) {
19662                        if (DEBUG_SD_INSTALL) {
19663                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19664                                    + " at code path: " + ps.codePathString);
19665                        }
19666
19667                        // We do have a valid package installed on sdcard
19668                        processCids.put(args, ps.codePathString);
19669                        final int uid = ps.appId;
19670                        if (uid != -1) {
19671                            uidArr = ArrayUtils.appendInt(uidArr, uid);
19672                        }
19673                    } else {
19674                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19675                                + ps.codePathString);
19676                    }
19677                }
19678            }
19679
19680            Arrays.sort(uidArr);
19681        }
19682
19683        // Process packages with valid entries.
19684        if (isMounted) {
19685            if (DEBUG_SD_INSTALL)
19686                Log.i(TAG, "Loading packages");
19687            loadMediaPackages(processCids, uidArr, externalStorage);
19688            startCleaningPackages();
19689            mInstallerService.onSecureContainersAvailable();
19690        } else {
19691            if (DEBUG_SD_INSTALL)
19692                Log.i(TAG, "Unloading packages");
19693            unloadMediaPackages(processCids, uidArr, reportStatus);
19694        }
19695    }
19696
19697    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19698            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19699        final int size = infos.size();
19700        final String[] packageNames = new String[size];
19701        final int[] packageUids = new int[size];
19702        for (int i = 0; i < size; i++) {
19703            final ApplicationInfo info = infos.get(i);
19704            packageNames[i] = info.packageName;
19705            packageUids[i] = info.uid;
19706        }
19707        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19708                finishedReceiver);
19709    }
19710
19711    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19712            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19713        sendResourcesChangedBroadcast(mediaStatus, replacing,
19714                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19715    }
19716
19717    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19718            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19719        int size = pkgList.length;
19720        if (size > 0) {
19721            // Send broadcasts here
19722            Bundle extras = new Bundle();
19723            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19724            if (uidArr != null) {
19725                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19726            }
19727            if (replacing) {
19728                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19729            }
19730            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19731                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19732            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19733        }
19734    }
19735
19736   /*
19737     * Look at potentially valid container ids from processCids If package
19738     * information doesn't match the one on record or package scanning fails,
19739     * the cid is added to list of removeCids. We currently don't delete stale
19740     * containers.
19741     */
19742    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19743            boolean externalStorage) {
19744        ArrayList<String> pkgList = new ArrayList<String>();
19745        Set<AsecInstallArgs> keys = processCids.keySet();
19746
19747        for (AsecInstallArgs args : keys) {
19748            String codePath = processCids.get(args);
19749            if (DEBUG_SD_INSTALL)
19750                Log.i(TAG, "Loading container : " + args.cid);
19751            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19752            try {
19753                // Make sure there are no container errors first.
19754                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19755                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19756                            + " when installing from sdcard");
19757                    continue;
19758                }
19759                // Check code path here.
19760                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19761                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19762                            + " does not match one in settings " + codePath);
19763                    continue;
19764                }
19765                // Parse package
19766                int parseFlags = mDefParseFlags;
19767                if (args.isExternalAsec()) {
19768                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19769                }
19770                if (args.isFwdLocked()) {
19771                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19772                }
19773
19774                synchronized (mInstallLock) {
19775                    PackageParser.Package pkg = null;
19776                    try {
19777                        // Sadly we don't know the package name yet to freeze it
19778                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19779                                SCAN_IGNORE_FROZEN, 0, null);
19780                    } catch (PackageManagerException e) {
19781                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19782                    }
19783                    // Scan the package
19784                    if (pkg != null) {
19785                        /*
19786                         * TODO why is the lock being held? doPostInstall is
19787                         * called in other places without the lock. This needs
19788                         * to be straightened out.
19789                         */
19790                        // writer
19791                        synchronized (mPackages) {
19792                            retCode = PackageManager.INSTALL_SUCCEEDED;
19793                            pkgList.add(pkg.packageName);
19794                            // Post process args
19795                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19796                                    pkg.applicationInfo.uid);
19797                        }
19798                    } else {
19799                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19800                    }
19801                }
19802
19803            } finally {
19804                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19805                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19806                }
19807            }
19808        }
19809        // writer
19810        synchronized (mPackages) {
19811            // If the platform SDK has changed since the last time we booted,
19812            // we need to re-grant app permission to catch any new ones that
19813            // appear. This is really a hack, and means that apps can in some
19814            // cases get permissions that the user didn't initially explicitly
19815            // allow... it would be nice to have some better way to handle
19816            // this situation.
19817            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19818                    : mSettings.getInternalVersion();
19819            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19820                    : StorageManager.UUID_PRIVATE_INTERNAL;
19821
19822            int updateFlags = UPDATE_PERMISSIONS_ALL;
19823            if (ver.sdkVersion != mSdkVersion) {
19824                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19825                        + mSdkVersion + "; regranting permissions for external");
19826                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19827            }
19828            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19829
19830            // Yay, everything is now upgraded
19831            ver.forceCurrent();
19832
19833            // can downgrade to reader
19834            // Persist settings
19835            mSettings.writeLPr();
19836        }
19837        // Send a broadcast to let everyone know we are done processing
19838        if (pkgList.size() > 0) {
19839            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19840        }
19841    }
19842
19843   /*
19844     * Utility method to unload a list of specified containers
19845     */
19846    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19847        // Just unmount all valid containers.
19848        for (AsecInstallArgs arg : cidArgs) {
19849            synchronized (mInstallLock) {
19850                arg.doPostDeleteLI(false);
19851           }
19852       }
19853   }
19854
19855    /*
19856     * Unload packages mounted on external media. This involves deleting package
19857     * data from internal structures, sending broadcasts about disabled packages,
19858     * gc'ing to free up references, unmounting all secure containers
19859     * corresponding to packages on external media, and posting a
19860     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19861     * that we always have to post this message if status has been requested no
19862     * matter what.
19863     */
19864    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19865            final boolean reportStatus) {
19866        if (DEBUG_SD_INSTALL)
19867            Log.i(TAG, "unloading media packages");
19868        ArrayList<String> pkgList = new ArrayList<String>();
19869        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19870        final Set<AsecInstallArgs> keys = processCids.keySet();
19871        for (AsecInstallArgs args : keys) {
19872            String pkgName = args.getPackageName();
19873            if (DEBUG_SD_INSTALL)
19874                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19875            // Delete package internally
19876            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19877            synchronized (mInstallLock) {
19878                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19879                final boolean res;
19880                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19881                        "unloadMediaPackages")) {
19882                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19883                            null);
19884                }
19885                if (res) {
19886                    pkgList.add(pkgName);
19887                } else {
19888                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19889                    failedList.add(args);
19890                }
19891            }
19892        }
19893
19894        // reader
19895        synchronized (mPackages) {
19896            // We didn't update the settings after removing each package;
19897            // write them now for all packages.
19898            mSettings.writeLPr();
19899        }
19900
19901        // We have to absolutely send UPDATED_MEDIA_STATUS only
19902        // after confirming that all the receivers processed the ordered
19903        // broadcast when packages get disabled, force a gc to clean things up.
19904        // and unload all the containers.
19905        if (pkgList.size() > 0) {
19906            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19907                    new IIntentReceiver.Stub() {
19908                public void performReceive(Intent intent, int resultCode, String data,
19909                        Bundle extras, boolean ordered, boolean sticky,
19910                        int sendingUser) throws RemoteException {
19911                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19912                            reportStatus ? 1 : 0, 1, keys);
19913                    mHandler.sendMessage(msg);
19914                }
19915            });
19916        } else {
19917            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19918                    keys);
19919            mHandler.sendMessage(msg);
19920        }
19921    }
19922
19923    private void loadPrivatePackages(final VolumeInfo vol) {
19924        mHandler.post(new Runnable() {
19925            @Override
19926            public void run() {
19927                loadPrivatePackagesInner(vol);
19928            }
19929        });
19930    }
19931
19932    private void loadPrivatePackagesInner(VolumeInfo vol) {
19933        final String volumeUuid = vol.fsUuid;
19934        if (TextUtils.isEmpty(volumeUuid)) {
19935            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19936            return;
19937        }
19938
19939        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19940        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19941        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19942
19943        final VersionInfo ver;
19944        final List<PackageSetting> packages;
19945        synchronized (mPackages) {
19946            ver = mSettings.findOrCreateVersion(volumeUuid);
19947            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19948        }
19949
19950        for (PackageSetting ps : packages) {
19951            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19952            synchronized (mInstallLock) {
19953                final PackageParser.Package pkg;
19954                try {
19955                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19956                    loaded.add(pkg.applicationInfo);
19957
19958                } catch (PackageManagerException e) {
19959                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19960                }
19961
19962                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19963                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19964                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19965                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19966                }
19967            }
19968        }
19969
19970        // Reconcile app data for all started/unlocked users
19971        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19972        final UserManager um = mContext.getSystemService(UserManager.class);
19973        UserManagerInternal umInternal = getUserManagerInternal();
19974        for (UserInfo user : um.getUsers()) {
19975            final int flags;
19976            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19977                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19978            } else if (umInternal.isUserRunning(user.id)) {
19979                flags = StorageManager.FLAG_STORAGE_DE;
19980            } else {
19981                continue;
19982            }
19983
19984            try {
19985                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19986                synchronized (mInstallLock) {
19987                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19988                }
19989            } catch (IllegalStateException e) {
19990                // Device was probably ejected, and we'll process that event momentarily
19991                Slog.w(TAG, "Failed to prepare storage: " + e);
19992            }
19993        }
19994
19995        synchronized (mPackages) {
19996            int updateFlags = UPDATE_PERMISSIONS_ALL;
19997            if (ver.sdkVersion != mSdkVersion) {
19998                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19999                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
20000                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
20001            }
20002            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
20003
20004            // Yay, everything is now upgraded
20005            ver.forceCurrent();
20006
20007            mSettings.writeLPr();
20008        }
20009
20010        for (PackageFreezer freezer : freezers) {
20011            freezer.close();
20012        }
20013
20014        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
20015        sendResourcesChangedBroadcast(true, false, loaded, null);
20016    }
20017
20018    private void unloadPrivatePackages(final VolumeInfo vol) {
20019        mHandler.post(new Runnable() {
20020            @Override
20021            public void run() {
20022                unloadPrivatePackagesInner(vol);
20023            }
20024        });
20025    }
20026
20027    private void unloadPrivatePackagesInner(VolumeInfo vol) {
20028        final String volumeUuid = vol.fsUuid;
20029        if (TextUtils.isEmpty(volumeUuid)) {
20030            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
20031            return;
20032        }
20033
20034        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
20035        synchronized (mInstallLock) {
20036        synchronized (mPackages) {
20037            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
20038            for (PackageSetting ps : packages) {
20039                if (ps.pkg == null) continue;
20040
20041                final ApplicationInfo info = ps.pkg.applicationInfo;
20042                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
20043                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
20044
20045                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
20046                        "unloadPrivatePackagesInner")) {
20047                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
20048                            false, null)) {
20049                        unloaded.add(info);
20050                    } else {
20051                        Slog.w(TAG, "Failed to unload " + ps.codePath);
20052                    }
20053                }
20054
20055                // Try very hard to release any references to this package
20056                // so we don't risk the system server being killed due to
20057                // open FDs
20058                AttributeCache.instance().removePackage(ps.name);
20059            }
20060
20061            mSettings.writeLPr();
20062        }
20063        }
20064
20065        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
20066        sendResourcesChangedBroadcast(false, false, unloaded, null);
20067
20068        // Try very hard to release any references to this path so we don't risk
20069        // the system server being killed due to open FDs
20070        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
20071
20072        for (int i = 0; i < 3; i++) {
20073            System.gc();
20074            System.runFinalization();
20075        }
20076    }
20077
20078    /**
20079     * Prepare storage areas for given user on all mounted devices.
20080     */
20081    void prepareUserData(int userId, int userSerial, int flags) {
20082        synchronized (mInstallLock) {
20083            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20084            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20085                final String volumeUuid = vol.getFsUuid();
20086                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
20087            }
20088        }
20089    }
20090
20091    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
20092            boolean allowRecover) {
20093        // Prepare storage and verify that serial numbers are consistent; if
20094        // there's a mismatch we need to destroy to avoid leaking data
20095        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20096        try {
20097            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
20098
20099            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
20100                UserManagerService.enforceSerialNumber(
20101                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
20102                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20103                    UserManagerService.enforceSerialNumber(
20104                            Environment.getDataSystemDeDirectory(userId), userSerial);
20105                }
20106            }
20107            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
20108                UserManagerService.enforceSerialNumber(
20109                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
20110                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20111                    UserManagerService.enforceSerialNumber(
20112                            Environment.getDataSystemCeDirectory(userId), userSerial);
20113                }
20114            }
20115
20116            synchronized (mInstallLock) {
20117                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
20118            }
20119        } catch (Exception e) {
20120            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
20121                    + " because we failed to prepare: " + e);
20122            destroyUserDataLI(volumeUuid, userId,
20123                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20124
20125            if (allowRecover) {
20126                // Try one last time; if we fail again we're really in trouble
20127                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
20128            }
20129        }
20130    }
20131
20132    /**
20133     * Destroy storage areas for given user on all mounted devices.
20134     */
20135    void destroyUserData(int userId, int flags) {
20136        synchronized (mInstallLock) {
20137            final StorageManager storage = mContext.getSystemService(StorageManager.class);
20138            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20139                final String volumeUuid = vol.getFsUuid();
20140                destroyUserDataLI(volumeUuid, userId, flags);
20141            }
20142        }
20143    }
20144
20145    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
20146        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20147        try {
20148            // Clean up app data, profile data, and media data
20149            mInstaller.destroyUserData(volumeUuid, userId, flags);
20150
20151            // Clean up system data
20152            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
20153                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20154                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
20155                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
20156                }
20157                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20158                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
20159                }
20160            }
20161
20162            // Data with special labels is now gone, so finish the job
20163            storage.destroyUserStorage(volumeUuid, userId, flags);
20164
20165        } catch (Exception e) {
20166            logCriticalInfo(Log.WARN,
20167                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
20168        }
20169    }
20170
20171    /**
20172     * Examine all users present on given mounted volume, and destroy data
20173     * belonging to users that are no longer valid, or whose user ID has been
20174     * recycled.
20175     */
20176    private void reconcileUsers(String volumeUuid) {
20177        final List<File> files = new ArrayList<>();
20178        Collections.addAll(files, FileUtils
20179                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
20180        Collections.addAll(files, FileUtils
20181                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
20182        Collections.addAll(files, FileUtils
20183                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
20184        Collections.addAll(files, FileUtils
20185                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
20186        for (File file : files) {
20187            if (!file.isDirectory()) continue;
20188
20189            final int userId;
20190            final UserInfo info;
20191            try {
20192                userId = Integer.parseInt(file.getName());
20193                info = sUserManager.getUserInfo(userId);
20194            } catch (NumberFormatException e) {
20195                Slog.w(TAG, "Invalid user directory " + file);
20196                continue;
20197            }
20198
20199            boolean destroyUser = false;
20200            if (info == null) {
20201                logCriticalInfo(Log.WARN, "Destroying user directory " + file
20202                        + " because no matching user was found");
20203                destroyUser = true;
20204            } else if (!mOnlyCore) {
20205                try {
20206                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
20207                } catch (IOException e) {
20208                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
20209                            + " because we failed to enforce serial number: " + e);
20210                    destroyUser = true;
20211                }
20212            }
20213
20214            if (destroyUser) {
20215                synchronized (mInstallLock) {
20216                    destroyUserDataLI(volumeUuid, userId,
20217                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20218                }
20219            }
20220        }
20221    }
20222
20223    private void assertPackageKnown(String volumeUuid, String packageName)
20224            throws PackageManagerException {
20225        synchronized (mPackages) {
20226            // Normalize package name to handle renamed packages
20227            packageName = normalizePackageNameLPr(packageName);
20228
20229            final PackageSetting ps = mSettings.mPackages.get(packageName);
20230            if (ps == null) {
20231                throw new PackageManagerException("Package " + packageName + " is unknown");
20232            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20233                throw new PackageManagerException(
20234                        "Package " + packageName + " found on unknown volume " + volumeUuid
20235                                + "; expected volume " + ps.volumeUuid);
20236            }
20237        }
20238    }
20239
20240    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
20241            throws PackageManagerException {
20242        synchronized (mPackages) {
20243            // Normalize package name to handle renamed packages
20244            packageName = normalizePackageNameLPr(packageName);
20245
20246            final PackageSetting ps = mSettings.mPackages.get(packageName);
20247            if (ps == null) {
20248                throw new PackageManagerException("Package " + packageName + " is unknown");
20249            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
20250                throw new PackageManagerException(
20251                        "Package " + packageName + " found on unknown volume " + volumeUuid
20252                                + "; expected volume " + ps.volumeUuid);
20253            } else if (!ps.getInstalled(userId)) {
20254                throw new PackageManagerException(
20255                        "Package " + packageName + " not installed for user " + userId);
20256            }
20257        }
20258    }
20259
20260    /**
20261     * Examine all apps present on given mounted volume, and destroy apps that
20262     * aren't expected, either due to uninstallation or reinstallation on
20263     * another volume.
20264     */
20265    private void reconcileApps(String volumeUuid) {
20266        final File[] files = FileUtils
20267                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
20268        for (File file : files) {
20269            final boolean isPackage = (isApkFile(file) || file.isDirectory())
20270                    && !PackageInstallerService.isStageName(file.getName());
20271            if (!isPackage) {
20272                // Ignore entries which are not packages
20273                continue;
20274            }
20275
20276            try {
20277                final PackageLite pkg = PackageParser.parsePackageLite(file,
20278                        PackageParser.PARSE_MUST_BE_APK);
20279                assertPackageKnown(volumeUuid, pkg.packageName);
20280
20281            } catch (PackageParserException | PackageManagerException e) {
20282                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20283                synchronized (mInstallLock) {
20284                    removeCodePathLI(file);
20285                }
20286            }
20287        }
20288    }
20289
20290    /**
20291     * Reconcile all app data for the given user.
20292     * <p>
20293     * Verifies that directories exist and that ownership and labeling is
20294     * correct for all installed apps on all mounted volumes.
20295     */
20296    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
20297        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20298        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
20299            final String volumeUuid = vol.getFsUuid();
20300            synchronized (mInstallLock) {
20301                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
20302            }
20303        }
20304    }
20305
20306    /**
20307     * Reconcile all app data on given mounted volume.
20308     * <p>
20309     * Destroys app data that isn't expected, either due to uninstallation or
20310     * reinstallation on another volume.
20311     * <p>
20312     * Verifies that directories exist and that ownership and labeling is
20313     * correct for all installed apps.
20314     */
20315    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
20316            boolean migrateAppData) {
20317        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
20318                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
20319
20320        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
20321        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
20322
20323        // First look for stale data that doesn't belong, and check if things
20324        // have changed since we did our last restorecon
20325        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20326            if (StorageManager.isFileEncryptedNativeOrEmulated()
20327                    && !StorageManager.isUserKeyUnlocked(userId)) {
20328                throw new RuntimeException(
20329                        "Yikes, someone asked us to reconcile CE storage while " + userId
20330                                + " was still locked; this would have caused massive data loss!");
20331            }
20332
20333            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
20334            for (File file : files) {
20335                final String packageName = file.getName();
20336                try {
20337                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20338                } catch (PackageManagerException e) {
20339                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20340                    try {
20341                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20342                                StorageManager.FLAG_STORAGE_CE, 0);
20343                    } catch (InstallerException e2) {
20344                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20345                    }
20346                }
20347            }
20348        }
20349        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
20350            final File[] files = FileUtils.listFilesOrEmpty(deDir);
20351            for (File file : files) {
20352                final String packageName = file.getName();
20353                try {
20354                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
20355                } catch (PackageManagerException e) {
20356                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
20357                    try {
20358                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
20359                                StorageManager.FLAG_STORAGE_DE, 0);
20360                    } catch (InstallerException e2) {
20361                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
20362                    }
20363                }
20364            }
20365        }
20366
20367        // Ensure that data directories are ready to roll for all packages
20368        // installed for this volume and user
20369        final List<PackageSetting> packages;
20370        synchronized (mPackages) {
20371            packages = mSettings.getVolumePackagesLPr(volumeUuid);
20372        }
20373        int preparedCount = 0;
20374        for (PackageSetting ps : packages) {
20375            final String packageName = ps.name;
20376            if (ps.pkg == null) {
20377                Slog.w(TAG, "Odd, missing scanned package " + packageName);
20378                // TODO: might be due to legacy ASEC apps; we should circle back
20379                // and reconcile again once they're scanned
20380                continue;
20381            }
20382
20383            if (ps.getInstalled(userId)) {
20384                prepareAppDataLIF(ps.pkg, userId, flags);
20385
20386                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
20387                    // We may have just shuffled around app data directories, so
20388                    // prepare them one more time
20389                    prepareAppDataLIF(ps.pkg, userId, flags);
20390                }
20391
20392                preparedCount++;
20393            }
20394        }
20395
20396        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
20397    }
20398
20399    /**
20400     * Prepare app data for the given app just after it was installed or
20401     * upgraded. This method carefully only touches users that it's installed
20402     * for, and it forces a restorecon to handle any seinfo changes.
20403     * <p>
20404     * Verifies that directories exist and that ownership and labeling is
20405     * correct for all installed apps. If there is an ownership mismatch, it
20406     * will try recovering system apps by wiping data; third-party app data is
20407     * left intact.
20408     * <p>
20409     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
20410     */
20411    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
20412        final PackageSetting ps;
20413        synchronized (mPackages) {
20414            ps = mSettings.mPackages.get(pkg.packageName);
20415            mSettings.writeKernelMappingLPr(ps);
20416        }
20417
20418        final UserManager um = mContext.getSystemService(UserManager.class);
20419        UserManagerInternal umInternal = getUserManagerInternal();
20420        for (UserInfo user : um.getUsers()) {
20421            final int flags;
20422            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
20423                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20424            } else if (umInternal.isUserRunning(user.id)) {
20425                flags = StorageManager.FLAG_STORAGE_DE;
20426            } else {
20427                continue;
20428            }
20429
20430            if (ps.getInstalled(user.id)) {
20431                // TODO: when user data is locked, mark that we're still dirty
20432                prepareAppDataLIF(pkg, user.id, flags);
20433            }
20434        }
20435    }
20436
20437    /**
20438     * Prepare app data for the given app.
20439     * <p>
20440     * Verifies that directories exist and that ownership and labeling is
20441     * correct for all installed apps. If there is an ownership mismatch, this
20442     * will try recovering system apps by wiping data; third-party app data is
20443     * left intact.
20444     */
20445    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
20446        if (pkg == null) {
20447            Slog.wtf(TAG, "Package was null!", new Throwable());
20448            return;
20449        }
20450        prepareAppDataLeafLIF(pkg, userId, flags);
20451        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20452        for (int i = 0; i < childCount; i++) {
20453            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
20454        }
20455    }
20456
20457    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20458        if (DEBUG_APP_DATA) {
20459            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
20460                    + Integer.toHexString(flags));
20461        }
20462
20463        final String volumeUuid = pkg.volumeUuid;
20464        final String packageName = pkg.packageName;
20465        final ApplicationInfo app = pkg.applicationInfo;
20466        final int appId = UserHandle.getAppId(app.uid);
20467
20468        Preconditions.checkNotNull(app.seinfo);
20469
20470        long ceDataInode = -1;
20471        try {
20472            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20473                    appId, app.seinfo, app.targetSdkVersion);
20474        } catch (InstallerException e) {
20475            if (app.isSystemApp()) {
20476                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20477                        + ", but trying to recover: " + e);
20478                destroyAppDataLeafLIF(pkg, userId, flags);
20479                try {
20480                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20481                            appId, app.seinfo, app.targetSdkVersion);
20482                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20483                } catch (InstallerException e2) {
20484                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
20485                }
20486            } else {
20487                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20488            }
20489        }
20490
20491        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
20492            // TODO: mark this structure as dirty so we persist it!
20493            synchronized (mPackages) {
20494                final PackageSetting ps = mSettings.mPackages.get(packageName);
20495                if (ps != null) {
20496                    ps.setCeDataInode(ceDataInode, userId);
20497                }
20498            }
20499        }
20500
20501        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20502    }
20503
20504    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20505        if (pkg == null) {
20506            Slog.wtf(TAG, "Package was null!", new Throwable());
20507            return;
20508        }
20509        prepareAppDataContentsLeafLIF(pkg, userId, flags);
20510        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20511        for (int i = 0; i < childCount; i++) {
20512            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20513        }
20514    }
20515
20516    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20517        final String volumeUuid = pkg.volumeUuid;
20518        final String packageName = pkg.packageName;
20519        final ApplicationInfo app = pkg.applicationInfo;
20520
20521        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20522            // Create a native library symlink only if we have native libraries
20523            // and if the native libraries are 32 bit libraries. We do not provide
20524            // this symlink for 64 bit libraries.
20525            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20526                final String nativeLibPath = app.nativeLibraryDir;
20527                try {
20528                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20529                            nativeLibPath, userId);
20530                } catch (InstallerException e) {
20531                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20532                }
20533            }
20534        }
20535    }
20536
20537    /**
20538     * For system apps on non-FBE devices, this method migrates any existing
20539     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20540     * requested by the app.
20541     */
20542    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20543        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20544                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20545            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20546                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20547            try {
20548                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20549                        storageTarget);
20550            } catch (InstallerException e) {
20551                logCriticalInfo(Log.WARN,
20552                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20553            }
20554            return true;
20555        } else {
20556            return false;
20557        }
20558    }
20559
20560    public PackageFreezer freezePackage(String packageName, String killReason) {
20561        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20562    }
20563
20564    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20565        return new PackageFreezer(packageName, userId, killReason);
20566    }
20567
20568    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20569            String killReason) {
20570        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20571    }
20572
20573    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20574            String killReason) {
20575        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20576            return new PackageFreezer();
20577        } else {
20578            return freezePackage(packageName, userId, killReason);
20579        }
20580    }
20581
20582    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20583            String killReason) {
20584        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20585    }
20586
20587    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20588            String killReason) {
20589        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20590            return new PackageFreezer();
20591        } else {
20592            return freezePackage(packageName, userId, killReason);
20593        }
20594    }
20595
20596    /**
20597     * Class that freezes and kills the given package upon creation, and
20598     * unfreezes it upon closing. This is typically used when doing surgery on
20599     * app code/data to prevent the app from running while you're working.
20600     */
20601    private class PackageFreezer implements AutoCloseable {
20602        private final String mPackageName;
20603        private final PackageFreezer[] mChildren;
20604
20605        private final boolean mWeFroze;
20606
20607        private final AtomicBoolean mClosed = new AtomicBoolean();
20608        private final CloseGuard mCloseGuard = CloseGuard.get();
20609
20610        /**
20611         * Create and return a stub freezer that doesn't actually do anything,
20612         * typically used when someone requested
20613         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20614         * {@link PackageManager#DELETE_DONT_KILL_APP}.
20615         */
20616        public PackageFreezer() {
20617            mPackageName = null;
20618            mChildren = null;
20619            mWeFroze = false;
20620            mCloseGuard.open("close");
20621        }
20622
20623        public PackageFreezer(String packageName, int userId, String killReason) {
20624            synchronized (mPackages) {
20625                mPackageName = packageName;
20626                mWeFroze = mFrozenPackages.add(mPackageName);
20627
20628                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20629                if (ps != null) {
20630                    killApplication(ps.name, ps.appId, userId, killReason);
20631                }
20632
20633                final PackageParser.Package p = mPackages.get(packageName);
20634                if (p != null && p.childPackages != null) {
20635                    final int N = p.childPackages.size();
20636                    mChildren = new PackageFreezer[N];
20637                    for (int i = 0; i < N; i++) {
20638                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20639                                userId, killReason);
20640                    }
20641                } else {
20642                    mChildren = null;
20643                }
20644            }
20645            mCloseGuard.open("close");
20646        }
20647
20648        @Override
20649        protected void finalize() throws Throwable {
20650            try {
20651                mCloseGuard.warnIfOpen();
20652                close();
20653            } finally {
20654                super.finalize();
20655            }
20656        }
20657
20658        @Override
20659        public void close() {
20660            mCloseGuard.close();
20661            if (mClosed.compareAndSet(false, true)) {
20662                synchronized (mPackages) {
20663                    if (mWeFroze) {
20664                        mFrozenPackages.remove(mPackageName);
20665                    }
20666
20667                    if (mChildren != null) {
20668                        for (PackageFreezer freezer : mChildren) {
20669                            freezer.close();
20670                        }
20671                    }
20672                }
20673            }
20674        }
20675    }
20676
20677    /**
20678     * Verify that given package is currently frozen.
20679     */
20680    private void checkPackageFrozen(String packageName) {
20681        synchronized (mPackages) {
20682            if (!mFrozenPackages.contains(packageName)) {
20683                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20684            }
20685        }
20686    }
20687
20688    @Override
20689    public int movePackage(final String packageName, final String volumeUuid) {
20690        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20691
20692        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20693        final int moveId = mNextMoveId.getAndIncrement();
20694        mHandler.post(new Runnable() {
20695            @Override
20696            public void run() {
20697                try {
20698                    movePackageInternal(packageName, volumeUuid, moveId, user);
20699                } catch (PackageManagerException e) {
20700                    Slog.w(TAG, "Failed to move " + packageName, e);
20701                    mMoveCallbacks.notifyStatusChanged(moveId,
20702                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20703                }
20704            }
20705        });
20706        return moveId;
20707    }
20708
20709    private void movePackageInternal(final String packageName, final String volumeUuid,
20710            final int moveId, UserHandle user) throws PackageManagerException {
20711        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20712        final PackageManager pm = mContext.getPackageManager();
20713
20714        final boolean currentAsec;
20715        final String currentVolumeUuid;
20716        final File codeFile;
20717        final String installerPackageName;
20718        final String packageAbiOverride;
20719        final int appId;
20720        final String seinfo;
20721        final String label;
20722        final int targetSdkVersion;
20723        final PackageFreezer freezer;
20724        final int[] installedUserIds;
20725
20726        // reader
20727        synchronized (mPackages) {
20728            final PackageParser.Package pkg = mPackages.get(packageName);
20729            final PackageSetting ps = mSettings.mPackages.get(packageName);
20730            if (pkg == null || ps == null) {
20731                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20732            }
20733
20734            if (pkg.applicationInfo.isSystemApp()) {
20735                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20736                        "Cannot move system application");
20737            }
20738
20739            if (pkg.applicationInfo.isExternalAsec()) {
20740                currentAsec = true;
20741                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20742            } else if (pkg.applicationInfo.isForwardLocked()) {
20743                currentAsec = true;
20744                currentVolumeUuid = "forward_locked";
20745            } else {
20746                currentAsec = false;
20747                currentVolumeUuid = ps.volumeUuid;
20748
20749                final File probe = new File(pkg.codePath);
20750                final File probeOat = new File(probe, "oat");
20751                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20752                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20753                            "Move only supported for modern cluster style installs");
20754                }
20755            }
20756
20757            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20758                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20759                        "Package already moved to " + volumeUuid);
20760            }
20761            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20762                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20763                        "Device admin cannot be moved");
20764            }
20765
20766            if (mFrozenPackages.contains(packageName)) {
20767                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20768                        "Failed to move already frozen package");
20769            }
20770
20771            codeFile = new File(pkg.codePath);
20772            installerPackageName = ps.installerPackageName;
20773            packageAbiOverride = ps.cpuAbiOverrideString;
20774            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20775            seinfo = pkg.applicationInfo.seinfo;
20776            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20777            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20778            freezer = freezePackage(packageName, "movePackageInternal");
20779            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20780        }
20781
20782        final Bundle extras = new Bundle();
20783        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20784        extras.putString(Intent.EXTRA_TITLE, label);
20785        mMoveCallbacks.notifyCreated(moveId, extras);
20786
20787        int installFlags;
20788        final boolean moveCompleteApp;
20789        final File measurePath;
20790
20791        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20792            installFlags = INSTALL_INTERNAL;
20793            moveCompleteApp = !currentAsec;
20794            measurePath = Environment.getDataAppDirectory(volumeUuid);
20795        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20796            installFlags = INSTALL_EXTERNAL;
20797            moveCompleteApp = false;
20798            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20799        } else {
20800            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20801            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20802                    || !volume.isMountedWritable()) {
20803                freezer.close();
20804                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20805                        "Move location not mounted private volume");
20806            }
20807
20808            Preconditions.checkState(!currentAsec);
20809
20810            installFlags = INSTALL_INTERNAL;
20811            moveCompleteApp = true;
20812            measurePath = Environment.getDataAppDirectory(volumeUuid);
20813        }
20814
20815        final PackageStats stats = new PackageStats(null, -1);
20816        synchronized (mInstaller) {
20817            for (int userId : installedUserIds) {
20818                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20819                    freezer.close();
20820                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20821                            "Failed to measure package size");
20822                }
20823            }
20824        }
20825
20826        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20827                + stats.dataSize);
20828
20829        final long startFreeBytes = measurePath.getFreeSpace();
20830        final long sizeBytes;
20831        if (moveCompleteApp) {
20832            sizeBytes = stats.codeSize + stats.dataSize;
20833        } else {
20834            sizeBytes = stats.codeSize;
20835        }
20836
20837        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20838            freezer.close();
20839            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20840                    "Not enough free space to move");
20841        }
20842
20843        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20844
20845        final CountDownLatch installedLatch = new CountDownLatch(1);
20846        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20847            @Override
20848            public void onUserActionRequired(Intent intent) throws RemoteException {
20849                throw new IllegalStateException();
20850            }
20851
20852            @Override
20853            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20854                    Bundle extras) throws RemoteException {
20855                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20856                        + PackageManager.installStatusToString(returnCode, msg));
20857
20858                installedLatch.countDown();
20859                freezer.close();
20860
20861                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20862                switch (status) {
20863                    case PackageInstaller.STATUS_SUCCESS:
20864                        mMoveCallbacks.notifyStatusChanged(moveId,
20865                                PackageManager.MOVE_SUCCEEDED);
20866                        break;
20867                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20868                        mMoveCallbacks.notifyStatusChanged(moveId,
20869                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20870                        break;
20871                    default:
20872                        mMoveCallbacks.notifyStatusChanged(moveId,
20873                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20874                        break;
20875                }
20876            }
20877        };
20878
20879        final MoveInfo move;
20880        if (moveCompleteApp) {
20881            // Kick off a thread to report progress estimates
20882            new Thread() {
20883                @Override
20884                public void run() {
20885                    while (true) {
20886                        try {
20887                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20888                                break;
20889                            }
20890                        } catch (InterruptedException ignored) {
20891                        }
20892
20893                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20894                        final int progress = 10 + (int) MathUtils.constrain(
20895                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20896                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20897                    }
20898                }
20899            }.start();
20900
20901            final String dataAppName = codeFile.getName();
20902            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20903                    dataAppName, appId, seinfo, targetSdkVersion);
20904        } else {
20905            move = null;
20906        }
20907
20908        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20909
20910        final Message msg = mHandler.obtainMessage(INIT_COPY);
20911        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20912        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20913                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20914                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20915        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20916        msg.obj = params;
20917
20918        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20919                System.identityHashCode(msg.obj));
20920        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20921                System.identityHashCode(msg.obj));
20922
20923        mHandler.sendMessage(msg);
20924    }
20925
20926    @Override
20927    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20928        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20929
20930        final int realMoveId = mNextMoveId.getAndIncrement();
20931        final Bundle extras = new Bundle();
20932        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20933        mMoveCallbacks.notifyCreated(realMoveId, extras);
20934
20935        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20936            @Override
20937            public void onCreated(int moveId, Bundle extras) {
20938                // Ignored
20939            }
20940
20941            @Override
20942            public void onStatusChanged(int moveId, int status, long estMillis) {
20943                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20944            }
20945        };
20946
20947        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20948        storage.setPrimaryStorageUuid(volumeUuid, callback);
20949        return realMoveId;
20950    }
20951
20952    @Override
20953    public int getMoveStatus(int moveId) {
20954        mContext.enforceCallingOrSelfPermission(
20955                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20956        return mMoveCallbacks.mLastStatus.get(moveId);
20957    }
20958
20959    @Override
20960    public void registerMoveCallback(IPackageMoveObserver callback) {
20961        mContext.enforceCallingOrSelfPermission(
20962                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20963        mMoveCallbacks.register(callback);
20964    }
20965
20966    @Override
20967    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20968        mContext.enforceCallingOrSelfPermission(
20969                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20970        mMoveCallbacks.unregister(callback);
20971    }
20972
20973    @Override
20974    public boolean setInstallLocation(int loc) {
20975        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20976                null);
20977        if (getInstallLocation() == loc) {
20978            return true;
20979        }
20980        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20981                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20982            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20983                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20984            return true;
20985        }
20986        return false;
20987   }
20988
20989    @Override
20990    public int getInstallLocation() {
20991        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20992                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20993                PackageHelper.APP_INSTALL_AUTO);
20994    }
20995
20996    /** Called by UserManagerService */
20997    void cleanUpUser(UserManagerService userManager, int userHandle) {
20998        synchronized (mPackages) {
20999            mDirtyUsers.remove(userHandle);
21000            mUserNeedsBadging.delete(userHandle);
21001            mSettings.removeUserLPw(userHandle);
21002            mPendingBroadcasts.remove(userHandle);
21003            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
21004            removeUnusedPackagesLPw(userManager, userHandle);
21005        }
21006    }
21007
21008    /**
21009     * We're removing userHandle and would like to remove any downloaded packages
21010     * that are no longer in use by any other user.
21011     * @param userHandle the user being removed
21012     */
21013    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
21014        final boolean DEBUG_CLEAN_APKS = false;
21015        int [] users = userManager.getUserIds();
21016        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
21017        while (psit.hasNext()) {
21018            PackageSetting ps = psit.next();
21019            if (ps.pkg == null) {
21020                continue;
21021            }
21022            final String packageName = ps.pkg.packageName;
21023            // Skip over if system app
21024            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
21025                continue;
21026            }
21027            if (DEBUG_CLEAN_APKS) {
21028                Slog.i(TAG, "Checking package " + packageName);
21029            }
21030            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
21031            if (keep) {
21032                if (DEBUG_CLEAN_APKS) {
21033                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
21034                }
21035            } else {
21036                for (int i = 0; i < users.length; i++) {
21037                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
21038                        keep = true;
21039                        if (DEBUG_CLEAN_APKS) {
21040                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
21041                                    + users[i]);
21042                        }
21043                        break;
21044                    }
21045                }
21046            }
21047            if (!keep) {
21048                if (DEBUG_CLEAN_APKS) {
21049                    Slog.i(TAG, "  Removing package " + packageName);
21050                }
21051                mHandler.post(new Runnable() {
21052                    public void run() {
21053                        deletePackageX(packageName, userHandle, 0);
21054                    } //end run
21055                });
21056            }
21057        }
21058    }
21059
21060    /** Called by UserManagerService */
21061    void createNewUser(int userId, String[] disallowedPackages) {
21062        synchronized (mInstallLock) {
21063            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
21064        }
21065        synchronized (mPackages) {
21066            scheduleWritePackageRestrictionsLocked(userId);
21067            scheduleWritePackageListLocked(userId);
21068            applyFactoryDefaultBrowserLPw(userId);
21069            primeDomainVerificationsLPw(userId);
21070        }
21071    }
21072
21073    void onNewUserCreated(final int userId) {
21074        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21075        // If permission review for legacy apps is required, we represent
21076        // dagerous permissions for such apps as always granted runtime
21077        // permissions to keep per user flag state whether review is needed.
21078        // Hence, if a new user is added we have to propagate dangerous
21079        // permission grants for these legacy apps.
21080        if (mPermissionReviewRequired) {
21081            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
21082                    | UPDATE_PERMISSIONS_REPLACE_ALL);
21083        }
21084    }
21085
21086    @Override
21087    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
21088        mContext.enforceCallingOrSelfPermission(
21089                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
21090                "Only package verification agents can read the verifier device identity");
21091
21092        synchronized (mPackages) {
21093            return mSettings.getVerifierDeviceIdentityLPw();
21094        }
21095    }
21096
21097    @Override
21098    public void setPermissionEnforced(String permission, boolean enforced) {
21099        // TODO: Now that we no longer change GID for storage, this should to away.
21100        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
21101                "setPermissionEnforced");
21102        if (READ_EXTERNAL_STORAGE.equals(permission)) {
21103            synchronized (mPackages) {
21104                if (mSettings.mReadExternalStorageEnforced == null
21105                        || mSettings.mReadExternalStorageEnforced != enforced) {
21106                    mSettings.mReadExternalStorageEnforced = enforced;
21107                    mSettings.writeLPr();
21108                }
21109            }
21110            // kill any non-foreground processes so we restart them and
21111            // grant/revoke the GID.
21112            final IActivityManager am = ActivityManager.getService();
21113            if (am != null) {
21114                final long token = Binder.clearCallingIdentity();
21115                try {
21116                    am.killProcessesBelowForeground("setPermissionEnforcement");
21117                } catch (RemoteException e) {
21118                } finally {
21119                    Binder.restoreCallingIdentity(token);
21120                }
21121            }
21122        } else {
21123            throw new IllegalArgumentException("No selective enforcement for " + permission);
21124        }
21125    }
21126
21127    @Override
21128    @Deprecated
21129    public boolean isPermissionEnforced(String permission) {
21130        return true;
21131    }
21132
21133    @Override
21134    public boolean isStorageLow() {
21135        final long token = Binder.clearCallingIdentity();
21136        try {
21137            final DeviceStorageMonitorInternal
21138                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
21139            if (dsm != null) {
21140                return dsm.isMemoryLow();
21141            } else {
21142                return false;
21143            }
21144        } finally {
21145            Binder.restoreCallingIdentity(token);
21146        }
21147    }
21148
21149    @Override
21150    public IPackageInstaller getPackageInstaller() {
21151        return mInstallerService;
21152    }
21153
21154    private boolean userNeedsBadging(int userId) {
21155        int index = mUserNeedsBadging.indexOfKey(userId);
21156        if (index < 0) {
21157            final UserInfo userInfo;
21158            final long token = Binder.clearCallingIdentity();
21159            try {
21160                userInfo = sUserManager.getUserInfo(userId);
21161            } finally {
21162                Binder.restoreCallingIdentity(token);
21163            }
21164            final boolean b;
21165            if (userInfo != null && userInfo.isManagedProfile()) {
21166                b = true;
21167            } else {
21168                b = false;
21169            }
21170            mUserNeedsBadging.put(userId, b);
21171            return b;
21172        }
21173        return mUserNeedsBadging.valueAt(index);
21174    }
21175
21176    @Override
21177    public KeySet getKeySetByAlias(String packageName, String alias) {
21178        if (packageName == null || alias == null) {
21179            return null;
21180        }
21181        synchronized(mPackages) {
21182            final PackageParser.Package pkg = mPackages.get(packageName);
21183            if (pkg == null) {
21184                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21185                throw new IllegalArgumentException("Unknown package: " + packageName);
21186            }
21187            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21188            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
21189        }
21190    }
21191
21192    @Override
21193    public KeySet getSigningKeySet(String packageName) {
21194        if (packageName == null) {
21195            return null;
21196        }
21197        synchronized(mPackages) {
21198            final PackageParser.Package pkg = mPackages.get(packageName);
21199            if (pkg == null) {
21200                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21201                throw new IllegalArgumentException("Unknown package: " + packageName);
21202            }
21203            if (pkg.applicationInfo.uid != Binder.getCallingUid()
21204                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
21205                throw new SecurityException("May not access signing KeySet of other apps.");
21206            }
21207            KeySetManagerService ksms = mSettings.mKeySetManagerService;
21208            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
21209        }
21210    }
21211
21212    @Override
21213    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
21214        if (packageName == null || ks == null) {
21215            return false;
21216        }
21217        synchronized(mPackages) {
21218            final PackageParser.Package pkg = mPackages.get(packageName);
21219            if (pkg == null) {
21220                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21221                throw new IllegalArgumentException("Unknown package: " + packageName);
21222            }
21223            IBinder ksh = ks.getToken();
21224            if (ksh instanceof KeySetHandle) {
21225                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21226                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
21227            }
21228            return false;
21229        }
21230    }
21231
21232    @Override
21233    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
21234        if (packageName == null || ks == null) {
21235            return false;
21236        }
21237        synchronized(mPackages) {
21238            final PackageParser.Package pkg = mPackages.get(packageName);
21239            if (pkg == null) {
21240                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
21241                throw new IllegalArgumentException("Unknown package: " + packageName);
21242            }
21243            IBinder ksh = ks.getToken();
21244            if (ksh instanceof KeySetHandle) {
21245                KeySetManagerService ksms = mSettings.mKeySetManagerService;
21246                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
21247            }
21248            return false;
21249        }
21250    }
21251
21252    private void deletePackageIfUnusedLPr(final String packageName) {
21253        PackageSetting ps = mSettings.mPackages.get(packageName);
21254        if (ps == null) {
21255            return;
21256        }
21257        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
21258            // TODO Implement atomic delete if package is unused
21259            // It is currently possible that the package will be deleted even if it is installed
21260            // after this method returns.
21261            mHandler.post(new Runnable() {
21262                public void run() {
21263                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
21264                }
21265            });
21266        }
21267    }
21268
21269    /**
21270     * Check and throw if the given before/after packages would be considered a
21271     * downgrade.
21272     */
21273    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
21274            throws PackageManagerException {
21275        if (after.versionCode < before.mVersionCode) {
21276            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21277                    "Update version code " + after.versionCode + " is older than current "
21278                    + before.mVersionCode);
21279        } else if (after.versionCode == before.mVersionCode) {
21280            if (after.baseRevisionCode < before.baseRevisionCode) {
21281                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21282                        "Update base revision code " + after.baseRevisionCode
21283                        + " is older than current " + before.baseRevisionCode);
21284            }
21285
21286            if (!ArrayUtils.isEmpty(after.splitNames)) {
21287                for (int i = 0; i < after.splitNames.length; i++) {
21288                    final String splitName = after.splitNames[i];
21289                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
21290                    if (j != -1) {
21291                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
21292                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
21293                                    "Update split " + splitName + " revision code "
21294                                    + after.splitRevisionCodes[i] + " is older than current "
21295                                    + before.splitRevisionCodes[j]);
21296                        }
21297                    }
21298                }
21299            }
21300        }
21301    }
21302
21303    private static class MoveCallbacks extends Handler {
21304        private static final int MSG_CREATED = 1;
21305        private static final int MSG_STATUS_CHANGED = 2;
21306
21307        private final RemoteCallbackList<IPackageMoveObserver>
21308                mCallbacks = new RemoteCallbackList<>();
21309
21310        private final SparseIntArray mLastStatus = new SparseIntArray();
21311
21312        public MoveCallbacks(Looper looper) {
21313            super(looper);
21314        }
21315
21316        public void register(IPackageMoveObserver callback) {
21317            mCallbacks.register(callback);
21318        }
21319
21320        public void unregister(IPackageMoveObserver callback) {
21321            mCallbacks.unregister(callback);
21322        }
21323
21324        @Override
21325        public void handleMessage(Message msg) {
21326            final SomeArgs args = (SomeArgs) msg.obj;
21327            final int n = mCallbacks.beginBroadcast();
21328            for (int i = 0; i < n; i++) {
21329                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
21330                try {
21331                    invokeCallback(callback, msg.what, args);
21332                } catch (RemoteException ignored) {
21333                }
21334            }
21335            mCallbacks.finishBroadcast();
21336            args.recycle();
21337        }
21338
21339        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
21340                throws RemoteException {
21341            switch (what) {
21342                case MSG_CREATED: {
21343                    callback.onCreated(args.argi1, (Bundle) args.arg2);
21344                    break;
21345                }
21346                case MSG_STATUS_CHANGED: {
21347                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
21348                    break;
21349                }
21350            }
21351        }
21352
21353        private void notifyCreated(int moveId, Bundle extras) {
21354            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
21355
21356            final SomeArgs args = SomeArgs.obtain();
21357            args.argi1 = moveId;
21358            args.arg2 = extras;
21359            obtainMessage(MSG_CREATED, args).sendToTarget();
21360        }
21361
21362        private void notifyStatusChanged(int moveId, int status) {
21363            notifyStatusChanged(moveId, status, -1);
21364        }
21365
21366        private void notifyStatusChanged(int moveId, int status, long estMillis) {
21367            Slog.v(TAG, "Move " + moveId + " status " + status);
21368
21369            final SomeArgs args = SomeArgs.obtain();
21370            args.argi1 = moveId;
21371            args.argi2 = status;
21372            args.arg3 = estMillis;
21373            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
21374
21375            synchronized (mLastStatus) {
21376                mLastStatus.put(moveId, status);
21377            }
21378        }
21379    }
21380
21381    private final static class OnPermissionChangeListeners extends Handler {
21382        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
21383
21384        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
21385                new RemoteCallbackList<>();
21386
21387        public OnPermissionChangeListeners(Looper looper) {
21388            super(looper);
21389        }
21390
21391        @Override
21392        public void handleMessage(Message msg) {
21393            switch (msg.what) {
21394                case MSG_ON_PERMISSIONS_CHANGED: {
21395                    final int uid = msg.arg1;
21396                    handleOnPermissionsChanged(uid);
21397                } break;
21398            }
21399        }
21400
21401        public void addListenerLocked(IOnPermissionsChangeListener listener) {
21402            mPermissionListeners.register(listener);
21403
21404        }
21405
21406        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
21407            mPermissionListeners.unregister(listener);
21408        }
21409
21410        public void onPermissionsChanged(int uid) {
21411            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
21412                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
21413            }
21414        }
21415
21416        private void handleOnPermissionsChanged(int uid) {
21417            final int count = mPermissionListeners.beginBroadcast();
21418            try {
21419                for (int i = 0; i < count; i++) {
21420                    IOnPermissionsChangeListener callback = mPermissionListeners
21421                            .getBroadcastItem(i);
21422                    try {
21423                        callback.onPermissionsChanged(uid);
21424                    } catch (RemoteException e) {
21425                        Log.e(TAG, "Permission listener is dead", e);
21426                    }
21427                }
21428            } finally {
21429                mPermissionListeners.finishBroadcast();
21430            }
21431        }
21432    }
21433
21434    private class PackageManagerInternalImpl extends PackageManagerInternal {
21435        @Override
21436        public void setLocationPackagesProvider(PackagesProvider provider) {
21437            synchronized (mPackages) {
21438                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
21439            }
21440        }
21441
21442        @Override
21443        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
21444            synchronized (mPackages) {
21445                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
21446            }
21447        }
21448
21449        @Override
21450        public void setSmsAppPackagesProvider(PackagesProvider provider) {
21451            synchronized (mPackages) {
21452                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
21453            }
21454        }
21455
21456        @Override
21457        public void setDialerAppPackagesProvider(PackagesProvider provider) {
21458            synchronized (mPackages) {
21459                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21460            }
21461        }
21462
21463        @Override
21464        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21465            synchronized (mPackages) {
21466                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21467            }
21468        }
21469
21470        @Override
21471        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21472            synchronized (mPackages) {
21473                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21474            }
21475        }
21476
21477        @Override
21478        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21479            synchronized (mPackages) {
21480                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21481                        packageName, userId);
21482            }
21483        }
21484
21485        @Override
21486        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21487            synchronized (mPackages) {
21488                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21489                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21490                        packageName, userId);
21491            }
21492        }
21493
21494        @Override
21495        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21496            synchronized (mPackages) {
21497                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21498                        packageName, userId);
21499            }
21500        }
21501
21502        @Override
21503        public void setKeepUninstalledPackages(final List<String> packageList) {
21504            Preconditions.checkNotNull(packageList);
21505            List<String> removedFromList = null;
21506            synchronized (mPackages) {
21507                if (mKeepUninstalledPackages != null) {
21508                    final int packagesCount = mKeepUninstalledPackages.size();
21509                    for (int i = 0; i < packagesCount; i++) {
21510                        String oldPackage = mKeepUninstalledPackages.get(i);
21511                        if (packageList != null && packageList.contains(oldPackage)) {
21512                            continue;
21513                        }
21514                        if (removedFromList == null) {
21515                            removedFromList = new ArrayList<>();
21516                        }
21517                        removedFromList.add(oldPackage);
21518                    }
21519                }
21520                mKeepUninstalledPackages = new ArrayList<>(packageList);
21521                if (removedFromList != null) {
21522                    final int removedCount = removedFromList.size();
21523                    for (int i = 0; i < removedCount; i++) {
21524                        deletePackageIfUnusedLPr(removedFromList.get(i));
21525                    }
21526                }
21527            }
21528        }
21529
21530        @Override
21531        public boolean isPermissionsReviewRequired(String packageName, int userId) {
21532            synchronized (mPackages) {
21533                // If we do not support permission review, done.
21534                if (!mPermissionReviewRequired) {
21535                    return false;
21536                }
21537
21538                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21539                if (packageSetting == null) {
21540                    return false;
21541                }
21542
21543                // Permission review applies only to apps not supporting the new permission model.
21544                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21545                    return false;
21546                }
21547
21548                // Legacy apps have the permission and get user consent on launch.
21549                PermissionsState permissionsState = packageSetting.getPermissionsState();
21550                return permissionsState.isPermissionReviewRequired(userId);
21551            }
21552        }
21553
21554        @Override
21555        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21556            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21557        }
21558
21559        @Override
21560        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21561                int userId) {
21562            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21563        }
21564
21565        @Override
21566        public void setDeviceAndProfileOwnerPackages(
21567                int deviceOwnerUserId, String deviceOwnerPackage,
21568                SparseArray<String> profileOwnerPackages) {
21569            mProtectedPackages.setDeviceAndProfileOwnerPackages(
21570                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21571        }
21572
21573        @Override
21574        public boolean isPackageDataProtected(int userId, String packageName) {
21575            return mProtectedPackages.isPackageDataProtected(userId, packageName);
21576        }
21577
21578        @Override
21579        public boolean isPackageEphemeral(int userId, String packageName) {
21580            synchronized (mPackages) {
21581                PackageParser.Package p = mPackages.get(packageName);
21582                return p != null ? p.applicationInfo.isEphemeralApp() : false;
21583            }
21584        }
21585
21586        @Override
21587        public boolean wasPackageEverLaunched(String packageName, int userId) {
21588            synchronized (mPackages) {
21589                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21590            }
21591        }
21592
21593        @Override
21594        public void grantRuntimePermission(String packageName, String name, int userId,
21595                boolean overridePolicy) {
21596            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
21597                    overridePolicy);
21598        }
21599
21600        @Override
21601        public void revokeRuntimePermission(String packageName, String name, int userId,
21602                boolean overridePolicy) {
21603            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
21604                    overridePolicy);
21605        }
21606
21607        @Override
21608        public String getNameForUid(int uid) {
21609            return PackageManagerService.this.getNameForUid(uid);
21610        }
21611
21612        @Override
21613        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
21614                Intent origIntent, String resolvedType, Intent launchIntent,
21615                String callingPackage, int userId) {
21616            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
21617                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
21618        }
21619    }
21620
21621    @Override
21622    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21623        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21624        synchronized (mPackages) {
21625            final long identity = Binder.clearCallingIdentity();
21626            try {
21627                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21628                        packageNames, userId);
21629            } finally {
21630                Binder.restoreCallingIdentity(identity);
21631            }
21632        }
21633    }
21634
21635    private static void enforceSystemOrPhoneCaller(String tag) {
21636        int callingUid = Binder.getCallingUid();
21637        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21638            throw new SecurityException(
21639                    "Cannot call " + tag + " from UID " + callingUid);
21640        }
21641    }
21642
21643    boolean isHistoricalPackageUsageAvailable() {
21644        return mPackageUsage.isHistoricalPackageUsageAvailable();
21645    }
21646
21647    /**
21648     * Return a <b>copy</b> of the collection of packages known to the package manager.
21649     * @return A copy of the values of mPackages.
21650     */
21651    Collection<PackageParser.Package> getPackages() {
21652        synchronized (mPackages) {
21653            return new ArrayList<>(mPackages.values());
21654        }
21655    }
21656
21657    /**
21658     * Logs process start information (including base APK hash) to the security log.
21659     * @hide
21660     */
21661    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21662            String apkFile, int pid) {
21663        if (!SecurityLog.isLoggingEnabled()) {
21664            return;
21665        }
21666        Bundle data = new Bundle();
21667        data.putLong("startTimestamp", System.currentTimeMillis());
21668        data.putString("processName", processName);
21669        data.putInt("uid", uid);
21670        data.putString("seinfo", seinfo);
21671        data.putString("apkFile", apkFile);
21672        data.putInt("pid", pid);
21673        Message msg = mProcessLoggingHandler.obtainMessage(
21674                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21675        msg.setData(data);
21676        mProcessLoggingHandler.sendMessage(msg);
21677    }
21678
21679    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21680        return mCompilerStats.getPackageStats(pkgName);
21681    }
21682
21683    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21684        return getOrCreateCompilerPackageStats(pkg.packageName);
21685    }
21686
21687    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21688        return mCompilerStats.getOrCreatePackageStats(pkgName);
21689    }
21690
21691    public void deleteCompilerPackageStats(String pkgName) {
21692        mCompilerStats.deletePackageStats(pkgName);
21693    }
21694}
21695