PackageManagerService.java revision 860d8b9a7c1742817ea360a7433139786196accb
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.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ComponentInfo;
130import android.content.pm.InstantAppInfo;
131import android.content.pm.EphemeralRequest;
132import android.content.pm.EphemeralResolveInfo;
133import android.content.pm.EphemeralResponse;
134import android.content.pm.FallbackCategoryProvider;
135import android.content.pm.FeatureInfo;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.graphics.Bitmap;
175import android.hardware.display.DisplayManager;
176import android.net.Uri;
177import android.os.Binder;
178import android.os.Build;
179import android.os.Bundle;
180import android.os.Debug;
181import android.os.Environment;
182import android.os.Environment.UserEnvironment;
183import android.os.FileUtils;
184import android.os.Handler;
185import android.os.IBinder;
186import android.os.Looper;
187import android.os.Message;
188import android.os.Parcel;
189import android.os.ParcelFileDescriptor;
190import android.os.PatternMatcher;
191import android.os.Process;
192import android.os.RemoteCallbackList;
193import android.os.RemoteException;
194import android.os.ResultReceiver;
195import android.os.SELinux;
196import android.os.ServiceManager;
197import android.os.ShellCallback;
198import android.os.SystemClock;
199import android.os.SystemProperties;
200import android.os.Trace;
201import android.os.UserHandle;
202import android.os.UserManager;
203import android.os.UserManagerInternal;
204import android.os.storage.IStorageManager;
205import android.os.storage.StorageManagerInternal;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.VolumeInfo;
209import android.os.storage.VolumeRecord;
210import android.provider.Settings.Global;
211import android.provider.Settings.Secure;
212import android.security.KeyStore;
213import android.security.SystemKeyStore;
214import android.system.ErrnoException;
215import android.system.Os;
216import android.text.TextUtils;
217import android.text.format.DateUtils;
218import android.util.ArrayMap;
219import android.util.ArraySet;
220import android.util.Base64;
221import android.util.DisplayMetrics;
222import android.util.EventLog;
223import android.util.ExceptionUtils;
224import android.util.Log;
225import android.util.LogPrinter;
226import android.util.MathUtils;
227import android.util.PackageUtils;
228import android.util.Pair;
229import android.util.PrintStreamPrinter;
230import android.util.Slog;
231import android.util.SparseArray;
232import android.util.SparseBooleanArray;
233import android.util.SparseIntArray;
234import android.util.Xml;
235import android.util.jar.StrictJarFile;
236import android.view.Display;
237
238import com.android.internal.R;
239import com.android.internal.annotations.GuardedBy;
240import com.android.internal.app.IMediaContainerService;
241import com.android.internal.app.ResolverActivity;
242import com.android.internal.content.NativeLibraryHelper;
243import com.android.internal.content.PackageHelper;
244import com.android.internal.logging.MetricsLogger;
245import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
246import com.android.internal.os.IParcelFileDescriptorFactory;
247import com.android.internal.os.RoSystemProperties;
248import com.android.internal.os.SomeArgs;
249import com.android.internal.os.Zygote;
250import com.android.internal.telephony.CarrierAppUtils;
251import com.android.internal.util.ArrayUtils;
252import com.android.internal.util.FastPrintWriter;
253import com.android.internal.util.FastXmlSerializer;
254import com.android.internal.util.IndentingPrintWriter;
255import com.android.internal.util.Preconditions;
256import com.android.internal.util.XmlUtils;
257import com.android.server.AttributeCache;
258import com.android.server.BackgroundDexOptJobService;
259import com.android.server.DeviceIdleController;
260import com.android.server.EventLogTags;
261import com.android.server.FgThread;
262import com.android.server.IntentResolver;
263import com.android.server.LocalServices;
264import com.android.server.ServiceThread;
265import com.android.server.SystemConfig;
266import com.android.server.Watchdog;
267import com.android.server.net.NetworkPolicyManagerInternal;
268import com.android.server.pm.Installer.InstallerException;
269import com.android.server.pm.PermissionsState.PermissionState;
270import com.android.server.pm.Settings.DatabaseVersion;
271import com.android.server.pm.Settings.VersionInfo;
272import com.android.server.pm.dex.DexManager;
273import com.android.server.storage.DeviceStorageMonitorInternal;
274
275import dalvik.system.CloseGuard;
276import dalvik.system.DexFile;
277import dalvik.system.VMRuntime;
278
279import libcore.io.IoUtils;
280import libcore.util.EmptyArray;
281
282import org.xmlpull.v1.XmlPullParser;
283import org.xmlpull.v1.XmlPullParserException;
284import org.xmlpull.v1.XmlSerializer;
285
286import java.io.BufferedOutputStream;
287import java.io.BufferedReader;
288import java.io.ByteArrayInputStream;
289import java.io.ByteArrayOutputStream;
290import java.io.File;
291import java.io.FileDescriptor;
292import java.io.FileInputStream;
293import java.io.FileNotFoundException;
294import java.io.FileOutputStream;
295import java.io.FileReader;
296import java.io.FilenameFilter;
297import java.io.IOException;
298import java.io.PrintWriter;
299import java.nio.charset.StandardCharsets;
300import java.security.DigestInputStream;
301import java.security.MessageDigest;
302import java.security.NoSuchAlgorithmException;
303import java.security.PublicKey;
304import java.security.SecureRandom;
305import java.security.cert.Certificate;
306import java.security.cert.CertificateEncodingException;
307import java.security.cert.CertificateException;
308import java.text.SimpleDateFormat;
309import java.util.ArrayList;
310import java.util.Arrays;
311import java.util.Collection;
312import java.util.Collections;
313import java.util.Comparator;
314import java.util.Date;
315import java.util.HashSet;
316import java.util.HashMap;
317import java.util.Iterator;
318import java.util.List;
319import java.util.Map;
320import java.util.Objects;
321import java.util.Set;
322import java.util.concurrent.CountDownLatch;
323import java.util.concurrent.TimeUnit;
324import java.util.concurrent.atomic.AtomicBoolean;
325import java.util.concurrent.atomic.AtomicInteger;
326
327/**
328 * Keep track of all those APKs everywhere.
329 * <p>
330 * Internally there are two important locks:
331 * <ul>
332 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
333 * and other related state. It is a fine-grained lock that should only be held
334 * momentarily, as it's one of the most contended locks in the system.
335 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
336 * operations typically involve heavy lifting of application data on disk. Since
337 * {@code installd} is single-threaded, and it's operations can often be slow,
338 * this lock should never be acquired while already holding {@link #mPackages}.
339 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
340 * holding {@link #mInstallLock}.
341 * </ul>
342 * Many internal methods rely on the caller to hold the appropriate locks, and
343 * this contract is expressed through method name suffixes:
344 * <ul>
345 * <li>fooLI(): the caller must hold {@link #mInstallLock}
346 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
347 * being modified must be frozen
348 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
349 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
350 * </ul>
351 * <p>
352 * Because this class is very central to the platform's security; please run all
353 * CTS and unit tests whenever making modifications:
354 *
355 * <pre>
356 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
357 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
358 * </pre>
359 */
360public class PackageManagerService extends IPackageManager.Stub {
361    static final String TAG = "PackageManager";
362    static final boolean DEBUG_SETTINGS = false;
363    static final boolean DEBUG_PREFERRED = false;
364    static final boolean DEBUG_UPGRADE = false;
365    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
366    private static final boolean DEBUG_BACKUP = false;
367    private static final boolean DEBUG_INSTALL = false;
368    private static final boolean DEBUG_REMOVE = false;
369    private static final boolean DEBUG_BROADCASTS = false;
370    private static final boolean DEBUG_SHOW_INFO = false;
371    private static final boolean DEBUG_PACKAGE_INFO = false;
372    private static final boolean DEBUG_INTENT_MATCHING = false;
373    private static final boolean DEBUG_PACKAGE_SCANNING = false;
374    private static final boolean DEBUG_VERIFY = false;
375    private static final boolean DEBUG_FILTERS = false;
376
377    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
378    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
379    // user, but by default initialize to this.
380    public static final boolean DEBUG_DEXOPT = false;
381
382    private static final boolean DEBUG_ABI_SELECTION = false;
383    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
384    private static final boolean DEBUG_TRIAGED_MISSING = false;
385    private static final boolean DEBUG_APP_DATA = false;
386
387    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
388    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
389
390    private static final boolean DISABLE_EPHEMERAL_APPS = false;
391    private static final boolean HIDE_EPHEMERAL_APIS = false;
392
393    private static final boolean ENABLE_QUOTA =
394            SystemProperties.getBoolean("persist.fw.quota", false);
395
396    private static final int RADIO_UID = Process.PHONE_UID;
397    private static final int LOG_UID = Process.LOG_UID;
398    private static final int NFC_UID = Process.NFC_UID;
399    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
400    private static final int SHELL_UID = Process.SHELL_UID;
401
402    // Cap the size of permission trees that 3rd party apps can define
403    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
404
405    // Suffix used during package installation when copying/moving
406    // package apks to install directory.
407    private static final String INSTALL_PACKAGE_SUFFIX = "-";
408
409    static final int SCAN_NO_DEX = 1<<1;
410    static final int SCAN_FORCE_DEX = 1<<2;
411    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
412    static final int SCAN_NEW_INSTALL = 1<<4;
413    static final int SCAN_UPDATE_TIME = 1<<5;
414    static final int SCAN_BOOTING = 1<<6;
415    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
416    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
417    static final int SCAN_REPLACING = 1<<9;
418    static final int SCAN_REQUIRE_KNOWN = 1<<10;
419    static final int SCAN_MOVE = 1<<11;
420    static final int SCAN_INITIAL = 1<<12;
421    static final int SCAN_CHECK_ONLY = 1<<13;
422    static final int SCAN_DONT_KILL_APP = 1<<14;
423    static final int SCAN_IGNORE_FROZEN = 1<<15;
424    static final int REMOVE_CHATTY = 1<<16;
425    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
426
427    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
428
429    private static final int[] EMPTY_INT_ARRAY = new int[0];
430
431    /**
432     * Timeout (in milliseconds) after which the watchdog should declare that
433     * our handler thread is wedged.  The usual default for such things is one
434     * minute but we sometimes do very lengthy I/O operations on this thread,
435     * such as installing multi-gigabyte applications, so ours needs to be longer.
436     */
437    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
438
439    /**
440     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
441     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
442     * settings entry if available, otherwise we use the hardcoded default.  If it's been
443     * more than this long since the last fstrim, we force one during the boot sequence.
444     *
445     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
446     * one gets run at the next available charging+idle time.  This final mandatory
447     * no-fstrim check kicks in only of the other scheduling criteria is never met.
448     */
449    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
450
451    /**
452     * Whether verification is enabled by default.
453     */
454    private static final boolean DEFAULT_VERIFY_ENABLE = true;
455
456    /**
457     * The default maximum time to wait for the verification agent to return in
458     * milliseconds.
459     */
460    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
461
462    /**
463     * The default response for package verification timeout.
464     *
465     * This can be either PackageManager.VERIFICATION_ALLOW or
466     * PackageManager.VERIFICATION_REJECT.
467     */
468    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
469
470    static final String PLATFORM_PACKAGE_NAME = "android";
471
472    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
473
474    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
475            DEFAULT_CONTAINER_PACKAGE,
476            "com.android.defcontainer.DefaultContainerService");
477
478    private static final String KILL_APP_REASON_GIDS_CHANGED =
479            "permission grant or revoke changed gids";
480
481    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
482            "permissions revoked";
483
484    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
485
486    private static final String PACKAGE_SCHEME = "package";
487
488    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
489    /**
490     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
491     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
492     * VENDOR_OVERLAY_DIR.
493     */
494    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
495    /**
496     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
497     * is in VENDOR_OVERLAY_THEME_PROPERTY.
498     */
499    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
500            = "persist.vendor.overlay.theme";
501
502    /** Permission grant: not grant the permission. */
503    private static final int GRANT_DENIED = 1;
504
505    /** Permission grant: grant the permission as an install permission. */
506    private static final int GRANT_INSTALL = 2;
507
508    /** Permission grant: grant the permission as a runtime one. */
509    private static final int GRANT_RUNTIME = 3;
510
511    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
512    private static final int GRANT_UPGRADE = 4;
513
514    /** Canonical intent used to identify what counts as a "web browser" app */
515    private static final Intent sBrowserIntent;
516    static {
517        sBrowserIntent = new Intent();
518        sBrowserIntent.setAction(Intent.ACTION_VIEW);
519        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
520        sBrowserIntent.setData(Uri.parse("http:"));
521    }
522
523    /**
524     * The set of all protected actions [i.e. those actions for which a high priority
525     * intent filter is disallowed].
526     */
527    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
528    static {
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
531        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
532        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
533    }
534
535    // Compilation reasons.
536    public static final int REASON_FIRST_BOOT = 0;
537    public static final int REASON_BOOT = 1;
538    public static final int REASON_INSTALL = 2;
539    public static final int REASON_BACKGROUND_DEXOPT = 3;
540    public static final int REASON_AB_OTA = 4;
541    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
542    public static final int REASON_SHARED_APK = 6;
543    public static final int REASON_FORCED_DEXOPT = 7;
544    public static final int REASON_CORE_APP = 8;
545
546    public static final int REASON_LAST = REASON_CORE_APP;
547
548    /** Special library name that skips shared libraries check during compilation. */
549    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
550
551    /** All dangerous permission names in the same order as the events in MetricsEvent */
552    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
553            Manifest.permission.READ_CALENDAR,
554            Manifest.permission.WRITE_CALENDAR,
555            Manifest.permission.CAMERA,
556            Manifest.permission.READ_CONTACTS,
557            Manifest.permission.WRITE_CONTACTS,
558            Manifest.permission.GET_ACCOUNTS,
559            Manifest.permission.ACCESS_FINE_LOCATION,
560            Manifest.permission.ACCESS_COARSE_LOCATION,
561            Manifest.permission.RECORD_AUDIO,
562            Manifest.permission.READ_PHONE_STATE,
563            Manifest.permission.CALL_PHONE,
564            Manifest.permission.READ_CALL_LOG,
565            Manifest.permission.WRITE_CALL_LOG,
566            Manifest.permission.ADD_VOICEMAIL,
567            Manifest.permission.USE_SIP,
568            Manifest.permission.PROCESS_OUTGOING_CALLS,
569            Manifest.permission.READ_CELL_BROADCASTS,
570            Manifest.permission.BODY_SENSORS,
571            Manifest.permission.SEND_SMS,
572            Manifest.permission.RECEIVE_SMS,
573            Manifest.permission.READ_SMS,
574            Manifest.permission.RECEIVE_WAP_PUSH,
575            Manifest.permission.RECEIVE_MMS,
576            Manifest.permission.READ_EXTERNAL_STORAGE,
577            Manifest.permission.WRITE_EXTERNAL_STORAGE,
578            Manifest.permission.READ_PHONE_NUMBER);
579
580
581    /**
582     * Version number for the package parser cache. Increment this whenever the format or
583     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
584     */
585    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
586
587    /**
588     * Whether the package parser cache is enabled.
589     */
590    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
591
592    final ServiceThread mHandlerThread;
593
594    final PackageHandler mHandler;
595
596    private final ProcessLoggingHandler mProcessLoggingHandler;
597
598    /**
599     * Messages for {@link #mHandler} that need to wait for system ready before
600     * being dispatched.
601     */
602    private ArrayList<Message> mPostSystemReadyMessages;
603
604    final int mSdkVersion = Build.VERSION.SDK_INT;
605
606    final Context mContext;
607    final boolean mFactoryTest;
608    final boolean mOnlyCore;
609    final DisplayMetrics mMetrics;
610    final int mDefParseFlags;
611    final String[] mSeparateProcesses;
612    final boolean mIsUpgrade;
613    final boolean mIsPreNUpgrade;
614    final boolean mIsPreNMR1Upgrade;
615
616    @GuardedBy("mPackages")
617    private boolean mDexOptDialogShown;
618
619    /** The location for ASEC container files on internal storage. */
620    final String mAsecInternalPath;
621
622    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
623    // LOCK HELD.  Can be called with mInstallLock held.
624    @GuardedBy("mInstallLock")
625    final Installer mInstaller;
626
627    /** Directory where installed third-party apps stored */
628    final File mAppInstallDir;
629    final File mEphemeralInstallDir;
630
631    /**
632     * Directory to which applications installed internally have their
633     * 32 bit native libraries copied.
634     */
635    private File mAppLib32InstallDir;
636
637    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
638    // apps.
639    final File mDrmAppPrivateInstallDir;
640
641    // ----------------------------------------------------------------
642
643    // Lock for state used when installing and doing other long running
644    // operations.  Methods that must be called with this lock held have
645    // the suffix "LI".
646    final Object mInstallLock = new Object();
647
648    // ----------------------------------------------------------------
649
650    // Keys are String (package name), values are Package.  This also serves
651    // as the lock for the global state.  Methods that must be called with
652    // this lock held have the prefix "LP".
653    @GuardedBy("mPackages")
654    final ArrayMap<String, PackageParser.Package> mPackages =
655            new ArrayMap<String, PackageParser.Package>();
656
657    final ArrayMap<String, Set<String>> mKnownCodebase =
658            new ArrayMap<String, Set<String>>();
659
660    // Tracks available target package names -> overlay package paths.
661    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
662        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
663
664    /**
665     * Tracks new system packages [received in an OTA] that we expect to
666     * find updated user-installed versions. Keys are package name, values
667     * are package location.
668     */
669    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
670    /**
671     * Tracks high priority intent filters for protected actions. During boot, certain
672     * filter actions are protected and should never be allowed to have a high priority
673     * intent filter for them. However, there is one, and only one exception -- the
674     * setup wizard. It must be able to define a high priority intent filter for these
675     * actions to ensure there are no escapes from the wizard. We need to delay processing
676     * of these during boot as we need to look at all of the system packages in order
677     * to know which component is the setup wizard.
678     */
679    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
680    /**
681     * Whether or not processing protected filters should be deferred.
682     */
683    private boolean mDeferProtectedFilters = true;
684
685    /**
686     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
687     */
688    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
689    /**
690     * Whether or not system app permissions should be promoted from install to runtime.
691     */
692    boolean mPromoteSystemApps;
693
694    @GuardedBy("mPackages")
695    final Settings mSettings;
696
697    /**
698     * Set of package names that are currently "frozen", which means active
699     * surgery is being done on the code/data for that package. The platform
700     * will refuse to launch frozen packages to avoid race conditions.
701     *
702     * @see PackageFreezer
703     */
704    @GuardedBy("mPackages")
705    final ArraySet<String> mFrozenPackages = new ArraySet<>();
706
707    final ProtectedPackages mProtectedPackages;
708
709    boolean mFirstBoot;
710
711    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
712
713    // System configuration read by SystemConfig.
714    final int[] mGlobalGids;
715    final SparseArray<ArraySet<String>> mSystemPermissions;
716    @GuardedBy("mAvailableFeatures")
717    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
718
719    // If mac_permissions.xml was found for seinfo labeling.
720    boolean mFoundPolicyFile;
721
722    private final InstantAppRegistry mInstantAppRegistry;
723
724    public static final class SharedLibraryEntry {
725        public final String path;
726        public final String apk;
727        public final SharedLibraryInfo info;
728
729        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
730                String declaringPackageName, int declaringPackageVersionCode) {
731            path = _path;
732            apk = _apk;
733            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
734                    declaringPackageName, declaringPackageVersionCode), null);
735        }
736    }
737
738    // Currently known shared libraries.
739    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
740    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
741            new ArrayMap<>();
742
743    // All available activities, for your resolving pleasure.
744    final ActivityIntentResolver mActivities =
745            new ActivityIntentResolver();
746
747    // All available receivers, for your resolving pleasure.
748    final ActivityIntentResolver mReceivers =
749            new ActivityIntentResolver();
750
751    // All available services, for your resolving pleasure.
752    final ServiceIntentResolver mServices = new ServiceIntentResolver();
753
754    // All available providers, for your resolving pleasure.
755    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
756
757    // Mapping from provider base names (first directory in content URI codePath)
758    // to the provider information.
759    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
760            new ArrayMap<String, PackageParser.Provider>();
761
762    // Mapping from instrumentation class names to info about them.
763    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
764            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
765
766    // Mapping from permission names to info about them.
767    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
768            new ArrayMap<String, PackageParser.PermissionGroup>();
769
770    // Packages whose data we have transfered into another package, thus
771    // should no longer exist.
772    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
773
774    // Broadcast actions that are only available to the system.
775    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
776
777    /** List of packages waiting for verification. */
778    final SparseArray<PackageVerificationState> mPendingVerification
779            = new SparseArray<PackageVerificationState>();
780
781    /** Set of packages associated with each app op permission. */
782    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
783
784    final PackageInstallerService mInstallerService;
785
786    private final PackageDexOptimizer mPackageDexOptimizer;
787    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
788    // is used by other apps).
789    private final DexManager mDexManager;
790
791    private AtomicInteger mNextMoveId = new AtomicInteger();
792    private final MoveCallbacks mMoveCallbacks;
793
794    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
795
796    // Cache of users who need badging.
797    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
798
799    /** Token for keys in mPendingVerification. */
800    private int mPendingVerificationToken = 0;
801
802    volatile boolean mSystemReady;
803    volatile boolean mSafeMode;
804    volatile boolean mHasSystemUidErrors;
805
806    ApplicationInfo mAndroidApplication;
807    final ActivityInfo mResolveActivity = new ActivityInfo();
808    final ResolveInfo mResolveInfo = new ResolveInfo();
809    ComponentName mResolveComponentName;
810    PackageParser.Package mPlatformPackage;
811    ComponentName mCustomResolverComponentName;
812
813    boolean mResolverReplaced = false;
814
815    private final @Nullable ComponentName mIntentFilterVerifierComponent;
816    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
817
818    private int mIntentFilterVerificationToken = 0;
819
820    /** The service connection to the ephemeral resolver */
821    final EphemeralResolverConnection mEphemeralResolverConnection;
822
823    /** Component used to install ephemeral applications */
824    ComponentName mEphemeralInstallerComponent;
825    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
826    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
827
828    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
829            = new SparseArray<IntentFilterVerificationState>();
830
831    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
832
833    // List of packages names to keep cached, even if they are uninstalled for all users
834    private List<String> mKeepUninstalledPackages;
835
836    private UserManagerInternal mUserManagerInternal;
837
838    private DeviceIdleController.LocalService mDeviceIdleController;
839
840    private File mCacheDir;
841
842    private ArraySet<String> mPrivappPermissionsViolations;
843
844    private static class IFVerificationParams {
845        PackageParser.Package pkg;
846        boolean replacing;
847        int userId;
848        int verifierUid;
849
850        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
851                int _userId, int _verifierUid) {
852            pkg = _pkg;
853            replacing = _replacing;
854            userId = _userId;
855            replacing = _replacing;
856            verifierUid = _verifierUid;
857        }
858    }
859
860    private interface IntentFilterVerifier<T extends IntentFilter> {
861        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
862                                               T filter, String packageName);
863        void startVerifications(int userId);
864        void receiveVerificationResponse(int verificationId);
865    }
866
867    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
868        private Context mContext;
869        private ComponentName mIntentFilterVerifierComponent;
870        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
871
872        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
873            mContext = context;
874            mIntentFilterVerifierComponent = verifierComponent;
875        }
876
877        private String getDefaultScheme() {
878            return IntentFilter.SCHEME_HTTPS;
879        }
880
881        @Override
882        public void startVerifications(int userId) {
883            // Launch verifications requests
884            int count = mCurrentIntentFilterVerifications.size();
885            for (int n=0; n<count; n++) {
886                int verificationId = mCurrentIntentFilterVerifications.get(n);
887                final IntentFilterVerificationState ivs =
888                        mIntentFilterVerificationStates.get(verificationId);
889
890                String packageName = ivs.getPackageName();
891
892                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
893                final int filterCount = filters.size();
894                ArraySet<String> domainsSet = new ArraySet<>();
895                for (int m=0; m<filterCount; m++) {
896                    PackageParser.ActivityIntentInfo filter = filters.get(m);
897                    domainsSet.addAll(filter.getHostsList());
898                }
899                synchronized (mPackages) {
900                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
901                            packageName, domainsSet) != null) {
902                        scheduleWriteSettingsLocked();
903                    }
904                }
905                sendVerificationRequest(userId, verificationId, ivs);
906            }
907            mCurrentIntentFilterVerifications.clear();
908        }
909
910        private void sendVerificationRequest(int userId, int verificationId,
911                IntentFilterVerificationState ivs) {
912
913            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
914            verificationIntent.putExtra(
915                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
916                    verificationId);
917            verificationIntent.putExtra(
918                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
919                    getDefaultScheme());
920            verificationIntent.putExtra(
921                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
922                    ivs.getHostsString());
923            verificationIntent.putExtra(
924                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
925                    ivs.getPackageName());
926            verificationIntent.setComponent(mIntentFilterVerifierComponent);
927            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
928
929            UserHandle user = new UserHandle(userId);
930            mContext.sendBroadcastAsUser(verificationIntent, user);
931            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
932                    "Sending IntentFilter verification broadcast");
933        }
934
935        public void receiveVerificationResponse(int verificationId) {
936            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
937
938            final boolean verified = ivs.isVerified();
939
940            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
941            final int count = filters.size();
942            if (DEBUG_DOMAIN_VERIFICATION) {
943                Slog.i(TAG, "Received verification response " + verificationId
944                        + " for " + count + " filters, verified=" + verified);
945            }
946            for (int n=0; n<count; n++) {
947                PackageParser.ActivityIntentInfo filter = filters.get(n);
948                filter.setVerified(verified);
949
950                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
951                        + " verified with result:" + verified + " and hosts:"
952                        + ivs.getHostsString());
953            }
954
955            mIntentFilterVerificationStates.remove(verificationId);
956
957            final String packageName = ivs.getPackageName();
958            IntentFilterVerificationInfo ivi = null;
959
960            synchronized (mPackages) {
961                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
962            }
963            if (ivi == null) {
964                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
965                        + verificationId + " packageName:" + packageName);
966                return;
967            }
968            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
969                    "Updating IntentFilterVerificationInfo for package " + packageName
970                            +" verificationId:" + verificationId);
971
972            synchronized (mPackages) {
973                if (verified) {
974                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
975                } else {
976                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
977                }
978                scheduleWriteSettingsLocked();
979
980                final int userId = ivs.getUserId();
981                if (userId != UserHandle.USER_ALL) {
982                    final int userStatus =
983                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
984
985                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
986                    boolean needUpdate = false;
987
988                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
989                    // already been set by the User thru the Disambiguation dialog
990                    switch (userStatus) {
991                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
992                            if (verified) {
993                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
994                            } else {
995                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
996                            }
997                            needUpdate = true;
998                            break;
999
1000                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1001                            if (verified) {
1002                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1003                                needUpdate = true;
1004                            }
1005                            break;
1006
1007                        default:
1008                            // Nothing to do
1009                    }
1010
1011                    if (needUpdate) {
1012                        mSettings.updateIntentFilterVerificationStatusLPw(
1013                                packageName, updatedStatus, userId);
1014                        scheduleWritePackageRestrictionsLocked(userId);
1015                    }
1016                }
1017            }
1018        }
1019
1020        @Override
1021        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1022                    ActivityIntentInfo filter, String packageName) {
1023            if (!hasValidDomains(filter)) {
1024                return false;
1025            }
1026            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1027            if (ivs == null) {
1028                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1029                        packageName);
1030            }
1031            if (DEBUG_DOMAIN_VERIFICATION) {
1032                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1033            }
1034            ivs.addFilter(filter);
1035            return true;
1036        }
1037
1038        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1039                int userId, int verificationId, String packageName) {
1040            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1041                    verifierUid, userId, packageName);
1042            ivs.setPendingState();
1043            synchronized (mPackages) {
1044                mIntentFilterVerificationStates.append(verificationId, ivs);
1045                mCurrentIntentFilterVerifications.add(verificationId);
1046            }
1047            return ivs;
1048        }
1049    }
1050
1051    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1052        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1053                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1054                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1055    }
1056
1057    // Set of pending broadcasts for aggregating enable/disable of components.
1058    static class PendingPackageBroadcasts {
1059        // for each user id, a map of <package name -> components within that package>
1060        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1061
1062        public PendingPackageBroadcasts() {
1063            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1064        }
1065
1066        public ArrayList<String> get(int userId, String packageName) {
1067            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1068            return packages.get(packageName);
1069        }
1070
1071        public void put(int userId, String packageName, ArrayList<String> components) {
1072            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1073            packages.put(packageName, components);
1074        }
1075
1076        public void remove(int userId, String packageName) {
1077            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1078            if (packages != null) {
1079                packages.remove(packageName);
1080            }
1081        }
1082
1083        public void remove(int userId) {
1084            mUidMap.remove(userId);
1085        }
1086
1087        public int userIdCount() {
1088            return mUidMap.size();
1089        }
1090
1091        public int userIdAt(int n) {
1092            return mUidMap.keyAt(n);
1093        }
1094
1095        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1096            return mUidMap.get(userId);
1097        }
1098
1099        public int size() {
1100            // total number of pending broadcast entries across all userIds
1101            int num = 0;
1102            for (int i = 0; i< mUidMap.size(); i++) {
1103                num += mUidMap.valueAt(i).size();
1104            }
1105            return num;
1106        }
1107
1108        public void clear() {
1109            mUidMap.clear();
1110        }
1111
1112        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1113            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1114            if (map == null) {
1115                map = new ArrayMap<String, ArrayList<String>>();
1116                mUidMap.put(userId, map);
1117            }
1118            return map;
1119        }
1120    }
1121    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1122
1123    // Service Connection to remote media container service to copy
1124    // package uri's from external media onto secure containers
1125    // or internal storage.
1126    private IMediaContainerService mContainerService = null;
1127
1128    static final int SEND_PENDING_BROADCAST = 1;
1129    static final int MCS_BOUND = 3;
1130    static final int END_COPY = 4;
1131    static final int INIT_COPY = 5;
1132    static final int MCS_UNBIND = 6;
1133    static final int START_CLEANING_PACKAGE = 7;
1134    static final int FIND_INSTALL_LOC = 8;
1135    static final int POST_INSTALL = 9;
1136    static final int MCS_RECONNECT = 10;
1137    static final int MCS_GIVE_UP = 11;
1138    static final int UPDATED_MEDIA_STATUS = 12;
1139    static final int WRITE_SETTINGS = 13;
1140    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1141    static final int PACKAGE_VERIFIED = 15;
1142    static final int CHECK_PENDING_VERIFICATION = 16;
1143    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1144    static final int INTENT_FILTER_VERIFIED = 18;
1145    static final int WRITE_PACKAGE_LIST = 19;
1146    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1147
1148    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1149
1150    // Delay time in millisecs
1151    static final int BROADCAST_DELAY = 10 * 1000;
1152
1153    static UserManagerService sUserManager;
1154
1155    // Stores a list of users whose package restrictions file needs to be updated
1156    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1157
1158    final private DefaultContainerConnection mDefContainerConn =
1159            new DefaultContainerConnection();
1160    class DefaultContainerConnection implements ServiceConnection {
1161        public void onServiceConnected(ComponentName name, IBinder service) {
1162            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1163            final IMediaContainerService imcs = IMediaContainerService.Stub
1164                    .asInterface(Binder.allowBlocking(service));
1165            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1166        }
1167
1168        public void onServiceDisconnected(ComponentName name) {
1169            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1170        }
1171    }
1172
1173    // Recordkeeping of restore-after-install operations that are currently in flight
1174    // between the Package Manager and the Backup Manager
1175    static class PostInstallData {
1176        public InstallArgs args;
1177        public PackageInstalledInfo res;
1178
1179        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1180            args = _a;
1181            res = _r;
1182        }
1183    }
1184
1185    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1186    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1187
1188    // XML tags for backup/restore of various bits of state
1189    private static final String TAG_PREFERRED_BACKUP = "pa";
1190    private static final String TAG_DEFAULT_APPS = "da";
1191    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1192
1193    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1194    private static final String TAG_ALL_GRANTS = "rt-grants";
1195    private static final String TAG_GRANT = "grant";
1196    private static final String ATTR_PACKAGE_NAME = "pkg";
1197
1198    private static final String TAG_PERMISSION = "perm";
1199    private static final String ATTR_PERMISSION_NAME = "name";
1200    private static final String ATTR_IS_GRANTED = "g";
1201    private static final String ATTR_USER_SET = "set";
1202    private static final String ATTR_USER_FIXED = "fixed";
1203    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1204
1205    // System/policy permission grants are not backed up
1206    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1207            FLAG_PERMISSION_POLICY_FIXED
1208            | FLAG_PERMISSION_SYSTEM_FIXED
1209            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1210
1211    // And we back up these user-adjusted states
1212    private static final int USER_RUNTIME_GRANT_MASK =
1213            FLAG_PERMISSION_USER_SET
1214            | FLAG_PERMISSION_USER_FIXED
1215            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1216
1217    final @Nullable String mRequiredVerifierPackage;
1218    final @NonNull String mRequiredInstallerPackage;
1219    final @NonNull String mRequiredUninstallerPackage;
1220    final @Nullable String mSetupWizardPackage;
1221    final @Nullable String mStorageManagerPackage;
1222    final @NonNull String mServicesSystemSharedLibraryPackageName;
1223    final @NonNull String mSharedSystemSharedLibraryPackageName;
1224
1225    final boolean mPermissionReviewRequired;
1226
1227    private final PackageUsage mPackageUsage = new PackageUsage();
1228    private final CompilerStats mCompilerStats = new CompilerStats();
1229
1230    class PackageHandler extends Handler {
1231        private boolean mBound = false;
1232        final ArrayList<HandlerParams> mPendingInstalls =
1233            new ArrayList<HandlerParams>();
1234
1235        private boolean connectToService() {
1236            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1237                    " DefaultContainerService");
1238            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1239            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1240            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1241                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1242                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1243                mBound = true;
1244                return true;
1245            }
1246            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1247            return false;
1248        }
1249
1250        private void disconnectService() {
1251            mContainerService = null;
1252            mBound = false;
1253            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1254            mContext.unbindService(mDefContainerConn);
1255            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1256        }
1257
1258        PackageHandler(Looper looper) {
1259            super(looper);
1260        }
1261
1262        public void handleMessage(Message msg) {
1263            try {
1264                doHandleMessage(msg);
1265            } finally {
1266                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1267            }
1268        }
1269
1270        void doHandleMessage(Message msg) {
1271            switch (msg.what) {
1272                case INIT_COPY: {
1273                    HandlerParams params = (HandlerParams) msg.obj;
1274                    int idx = mPendingInstalls.size();
1275                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1276                    // If a bind was already initiated we dont really
1277                    // need to do anything. The pending install
1278                    // will be processed later on.
1279                    if (!mBound) {
1280                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1281                                System.identityHashCode(mHandler));
1282                        // If this is the only one pending we might
1283                        // have to bind to the service again.
1284                        if (!connectToService()) {
1285                            Slog.e(TAG, "Failed to bind to media container service");
1286                            params.serviceError();
1287                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1288                                    System.identityHashCode(mHandler));
1289                            if (params.traceMethod != null) {
1290                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1291                                        params.traceCookie);
1292                            }
1293                            return;
1294                        } else {
1295                            // Once we bind to the service, the first
1296                            // pending request will be processed.
1297                            mPendingInstalls.add(idx, params);
1298                        }
1299                    } else {
1300                        mPendingInstalls.add(idx, params);
1301                        // Already bound to the service. Just make
1302                        // sure we trigger off processing the first request.
1303                        if (idx == 0) {
1304                            mHandler.sendEmptyMessage(MCS_BOUND);
1305                        }
1306                    }
1307                    break;
1308                }
1309                case MCS_BOUND: {
1310                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1311                    if (msg.obj != null) {
1312                        mContainerService = (IMediaContainerService) msg.obj;
1313                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1314                                System.identityHashCode(mHandler));
1315                    }
1316                    if (mContainerService == null) {
1317                        if (!mBound) {
1318                            // Something seriously wrong since we are not bound and we are not
1319                            // waiting for connection. Bail out.
1320                            Slog.e(TAG, "Cannot bind to media container service");
1321                            for (HandlerParams params : mPendingInstalls) {
1322                                // Indicate service bind error
1323                                params.serviceError();
1324                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1325                                        System.identityHashCode(params));
1326                                if (params.traceMethod != null) {
1327                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1328                                            params.traceMethod, params.traceCookie);
1329                                }
1330                                return;
1331                            }
1332                            mPendingInstalls.clear();
1333                        } else {
1334                            Slog.w(TAG, "Waiting to connect to media container service");
1335                        }
1336                    } else if (mPendingInstalls.size() > 0) {
1337                        HandlerParams params = mPendingInstalls.get(0);
1338                        if (params != null) {
1339                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1340                                    System.identityHashCode(params));
1341                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1342                            if (params.startCopy()) {
1343                                // We are done...  look for more work or to
1344                                // go idle.
1345                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1346                                        "Checking for more work or unbind...");
1347                                // Delete pending install
1348                                if (mPendingInstalls.size() > 0) {
1349                                    mPendingInstalls.remove(0);
1350                                }
1351                                if (mPendingInstalls.size() == 0) {
1352                                    if (mBound) {
1353                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1354                                                "Posting delayed MCS_UNBIND");
1355                                        removeMessages(MCS_UNBIND);
1356                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1357                                        // Unbind after a little delay, to avoid
1358                                        // continual thrashing.
1359                                        sendMessageDelayed(ubmsg, 10000);
1360                                    }
1361                                } else {
1362                                    // There are more pending requests in queue.
1363                                    // Just post MCS_BOUND message to trigger processing
1364                                    // of next pending install.
1365                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1366                                            "Posting MCS_BOUND for next work");
1367                                    mHandler.sendEmptyMessage(MCS_BOUND);
1368                                }
1369                            }
1370                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1371                        }
1372                    } else {
1373                        // Should never happen ideally.
1374                        Slog.w(TAG, "Empty queue");
1375                    }
1376                    break;
1377                }
1378                case MCS_RECONNECT: {
1379                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1380                    if (mPendingInstalls.size() > 0) {
1381                        if (mBound) {
1382                            disconnectService();
1383                        }
1384                        if (!connectToService()) {
1385                            Slog.e(TAG, "Failed to bind to media container service");
1386                            for (HandlerParams params : mPendingInstalls) {
1387                                // Indicate service bind error
1388                                params.serviceError();
1389                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1390                                        System.identityHashCode(params));
1391                            }
1392                            mPendingInstalls.clear();
1393                        }
1394                    }
1395                    break;
1396                }
1397                case MCS_UNBIND: {
1398                    // If there is no actual work left, then time to unbind.
1399                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1400
1401                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1402                        if (mBound) {
1403                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1404
1405                            disconnectService();
1406                        }
1407                    } else if (mPendingInstalls.size() > 0) {
1408                        // There are more pending requests in queue.
1409                        // Just post MCS_BOUND message to trigger processing
1410                        // of next pending install.
1411                        mHandler.sendEmptyMessage(MCS_BOUND);
1412                    }
1413
1414                    break;
1415                }
1416                case MCS_GIVE_UP: {
1417                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1418                    HandlerParams params = mPendingInstalls.remove(0);
1419                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1420                            System.identityHashCode(params));
1421                    break;
1422                }
1423                case SEND_PENDING_BROADCAST: {
1424                    String packages[];
1425                    ArrayList<String> components[];
1426                    int size = 0;
1427                    int uids[];
1428                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1429                    synchronized (mPackages) {
1430                        if (mPendingBroadcasts == null) {
1431                            return;
1432                        }
1433                        size = mPendingBroadcasts.size();
1434                        if (size <= 0) {
1435                            // Nothing to be done. Just return
1436                            return;
1437                        }
1438                        packages = new String[size];
1439                        components = new ArrayList[size];
1440                        uids = new int[size];
1441                        int i = 0;  // filling out the above arrays
1442
1443                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1444                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1445                            Iterator<Map.Entry<String, ArrayList<String>>> it
1446                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1447                                            .entrySet().iterator();
1448                            while (it.hasNext() && i < size) {
1449                                Map.Entry<String, ArrayList<String>> ent = it.next();
1450                                packages[i] = ent.getKey();
1451                                components[i] = ent.getValue();
1452                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1453                                uids[i] = (ps != null)
1454                                        ? UserHandle.getUid(packageUserId, ps.appId)
1455                                        : -1;
1456                                i++;
1457                            }
1458                        }
1459                        size = i;
1460                        mPendingBroadcasts.clear();
1461                    }
1462                    // Send broadcasts
1463                    for (int i = 0; i < size; i++) {
1464                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1465                    }
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1467                    break;
1468                }
1469                case START_CLEANING_PACKAGE: {
1470                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1471                    final String packageName = (String)msg.obj;
1472                    final int userId = msg.arg1;
1473                    final boolean andCode = msg.arg2 != 0;
1474                    synchronized (mPackages) {
1475                        if (userId == UserHandle.USER_ALL) {
1476                            int[] users = sUserManager.getUserIds();
1477                            for (int user : users) {
1478                                mSettings.addPackageToCleanLPw(
1479                                        new PackageCleanItem(user, packageName, andCode));
1480                            }
1481                        } else {
1482                            mSettings.addPackageToCleanLPw(
1483                                    new PackageCleanItem(userId, packageName, andCode));
1484                        }
1485                    }
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1487                    startCleaningPackages();
1488                } break;
1489                case POST_INSTALL: {
1490                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1491
1492                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1493                    final boolean didRestore = (msg.arg2 != 0);
1494                    mRunningInstalls.delete(msg.arg1);
1495
1496                    if (data != null) {
1497                        InstallArgs args = data.args;
1498                        PackageInstalledInfo parentRes = data.res;
1499
1500                        final boolean grantPermissions = (args.installFlags
1501                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1502                        final boolean killApp = (args.installFlags
1503                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1504                        final String[] grantedPermissions = args.installGrantPermissions;
1505
1506                        // Handle the parent package
1507                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1508                                grantedPermissions, didRestore, args.installerPackageName,
1509                                args.observer);
1510
1511                        // Handle the child packages
1512                        final int childCount = (parentRes.addedChildPackages != null)
1513                                ? parentRes.addedChildPackages.size() : 0;
1514                        for (int i = 0; i < childCount; i++) {
1515                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1516                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1517                                    grantedPermissions, false, args.installerPackageName,
1518                                    args.observer);
1519                        }
1520
1521                        // Log tracing if needed
1522                        if (args.traceMethod != null) {
1523                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1524                                    args.traceCookie);
1525                        }
1526                    } else {
1527                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1528                    }
1529
1530                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1531                } break;
1532                case UPDATED_MEDIA_STATUS: {
1533                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1534                    boolean reportStatus = msg.arg1 == 1;
1535                    boolean doGc = msg.arg2 == 1;
1536                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1537                    if (doGc) {
1538                        // Force a gc to clear up stale containers.
1539                        Runtime.getRuntime().gc();
1540                    }
1541                    if (msg.obj != null) {
1542                        @SuppressWarnings("unchecked")
1543                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1544                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1545                        // Unload containers
1546                        unloadAllContainers(args);
1547                    }
1548                    if (reportStatus) {
1549                        try {
1550                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1551                                    "Invoking StorageManagerService call back");
1552                            PackageHelper.getStorageManager().finishMediaUpdate();
1553                        } catch (RemoteException e) {
1554                            Log.e(TAG, "StorageManagerService not running?");
1555                        }
1556                    }
1557                } break;
1558                case WRITE_SETTINGS: {
1559                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1560                    synchronized (mPackages) {
1561                        removeMessages(WRITE_SETTINGS);
1562                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1563                        mSettings.writeLPr();
1564                        mDirtyUsers.clear();
1565                    }
1566                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1567                } break;
1568                case WRITE_PACKAGE_RESTRICTIONS: {
1569                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1570                    synchronized (mPackages) {
1571                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1572                        for (int userId : mDirtyUsers) {
1573                            mSettings.writePackageRestrictionsLPr(userId);
1574                        }
1575                        mDirtyUsers.clear();
1576                    }
1577                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1578                } break;
1579                case WRITE_PACKAGE_LIST: {
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1581                    synchronized (mPackages) {
1582                        removeMessages(WRITE_PACKAGE_LIST);
1583                        mSettings.writePackageListLPr(msg.arg1);
1584                    }
1585                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1586                } break;
1587                case CHECK_PENDING_VERIFICATION: {
1588                    final int verificationId = msg.arg1;
1589                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1590
1591                    if ((state != null) && !state.timeoutExtended()) {
1592                        final InstallArgs args = state.getInstallArgs();
1593                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1594
1595                        Slog.i(TAG, "Verification timed out for " + originUri);
1596                        mPendingVerification.remove(verificationId);
1597
1598                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1599
1600                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1601                            Slog.i(TAG, "Continuing with installation of " + originUri);
1602                            state.setVerifierResponse(Binder.getCallingUid(),
1603                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1604                            broadcastPackageVerified(verificationId, originUri,
1605                                    PackageManager.VERIFICATION_ALLOW,
1606                                    state.getInstallArgs().getUser());
1607                            try {
1608                                ret = args.copyApk(mContainerService, true);
1609                            } catch (RemoteException e) {
1610                                Slog.e(TAG, "Could not contact the ContainerService");
1611                            }
1612                        } else {
1613                            broadcastPackageVerified(verificationId, originUri,
1614                                    PackageManager.VERIFICATION_REJECT,
1615                                    state.getInstallArgs().getUser());
1616                        }
1617
1618                        Trace.asyncTraceEnd(
1619                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1620
1621                        processPendingInstall(args, ret);
1622                        mHandler.sendEmptyMessage(MCS_UNBIND);
1623                    }
1624                    break;
1625                }
1626                case PACKAGE_VERIFIED: {
1627                    final int verificationId = msg.arg1;
1628
1629                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1630                    if (state == null) {
1631                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1632                        break;
1633                    }
1634
1635                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1636
1637                    state.setVerifierResponse(response.callerUid, response.code);
1638
1639                    if (state.isVerificationComplete()) {
1640                        mPendingVerification.remove(verificationId);
1641
1642                        final InstallArgs args = state.getInstallArgs();
1643                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1644
1645                        int ret;
1646                        if (state.isInstallAllowed()) {
1647                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1648                            broadcastPackageVerified(verificationId, originUri,
1649                                    response.code, state.getInstallArgs().getUser());
1650                            try {
1651                                ret = args.copyApk(mContainerService, true);
1652                            } catch (RemoteException e) {
1653                                Slog.e(TAG, "Could not contact the ContainerService");
1654                            }
1655                        } else {
1656                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1657                        }
1658
1659                        Trace.asyncTraceEnd(
1660                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1661
1662                        processPendingInstall(args, ret);
1663                        mHandler.sendEmptyMessage(MCS_UNBIND);
1664                    }
1665
1666                    break;
1667                }
1668                case START_INTENT_FILTER_VERIFICATIONS: {
1669                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1670                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1671                            params.replacing, params.pkg);
1672                    break;
1673                }
1674                case INTENT_FILTER_VERIFIED: {
1675                    final int verificationId = msg.arg1;
1676
1677                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1678                            verificationId);
1679                    if (state == null) {
1680                        Slog.w(TAG, "Invalid IntentFilter verification token "
1681                                + verificationId + " received");
1682                        break;
1683                    }
1684
1685                    final int userId = state.getUserId();
1686
1687                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1688                            "Processing IntentFilter verification with token:"
1689                            + verificationId + " and userId:" + userId);
1690
1691                    final IntentFilterVerificationResponse response =
1692                            (IntentFilterVerificationResponse) msg.obj;
1693
1694                    state.setVerifierResponse(response.callerUid, response.code);
1695
1696                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1697                            "IntentFilter verification with token:" + verificationId
1698                            + " and userId:" + userId
1699                            + " is settings verifier response with response code:"
1700                            + response.code);
1701
1702                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1703                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1704                                + response.getFailedDomainsString());
1705                    }
1706
1707                    if (state.isVerificationComplete()) {
1708                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1709                    } else {
1710                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1711                                "IntentFilter verification with token:" + verificationId
1712                                + " was not said to be complete");
1713                    }
1714
1715                    break;
1716                }
1717                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1718                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1719                            mEphemeralResolverConnection,
1720                            (EphemeralRequest) msg.obj,
1721                            mEphemeralInstallerActivity,
1722                            mHandler);
1723                }
1724            }
1725        }
1726    }
1727
1728    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1729            boolean killApp, String[] grantedPermissions,
1730            boolean launchedForRestore, String installerPackage,
1731            IPackageInstallObserver2 installObserver) {
1732        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1733            // Send the removed broadcasts
1734            if (res.removedInfo != null) {
1735                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1736            }
1737
1738            // Now that we successfully installed the package, grant runtime
1739            // permissions if requested before broadcasting the install. Also
1740            // for legacy apps in permission review mode we clear the permission
1741            // review flag which is used to emulate runtime permissions for
1742            // legacy apps.
1743            if (grantPermissions) {
1744                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1745            }
1746
1747            final boolean update = res.removedInfo != null
1748                    && res.removedInfo.removedPackage != null;
1749
1750            // If this is the first time we have child packages for a disabled privileged
1751            // app that had no children, we grant requested runtime permissions to the new
1752            // children if the parent on the system image had them already granted.
1753            if (res.pkg.parentPackage != null) {
1754                synchronized (mPackages) {
1755                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1756                }
1757            }
1758
1759            synchronized (mPackages) {
1760                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1761            }
1762
1763            final String packageName = res.pkg.applicationInfo.packageName;
1764
1765            // Determine the set of users who are adding this package for
1766            // the first time vs. those who are seeing an update.
1767            int[] firstUsers = EMPTY_INT_ARRAY;
1768            int[] updateUsers = EMPTY_INT_ARRAY;
1769            if (res.origUsers == null || res.origUsers.length == 0) {
1770                firstUsers = res.newUsers;
1771            } else {
1772                for (int newUser : res.newUsers) {
1773                    boolean isNew = true;
1774                    for (int origUser : res.origUsers) {
1775                        if (origUser == newUser) {
1776                            isNew = false;
1777                            break;
1778                        }
1779                    }
1780                    if (isNew) {
1781                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1782                    } else {
1783                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1784                    }
1785                }
1786            }
1787
1788            // Send installed broadcasts if the install/update is not ephemeral
1789            // and the package is not a static shared lib.
1790            if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) {
1791                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1792
1793                // Send added for users that see the package for the first time
1794                // sendPackageAddedForNewUsers also deals with system apps
1795                int appId = UserHandle.getAppId(res.uid);
1796                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1797                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1798
1799                // Send added for users that don't see the package for the first time
1800                Bundle extras = new Bundle(1);
1801                extras.putInt(Intent.EXTRA_UID, res.uid);
1802                if (update) {
1803                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1804                }
1805                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1806                        extras, 0 /*flags*/, null /*targetPackage*/,
1807                        null /*finishedReceiver*/, updateUsers);
1808
1809                // Send replaced for users that don't see the package for the first time
1810                if (update) {
1811                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1812                            packageName, extras, 0 /*flags*/,
1813                            null /*targetPackage*/, null /*finishedReceiver*/,
1814                            updateUsers);
1815                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1816                            null /*package*/, null /*extras*/, 0 /*flags*/,
1817                            packageName /*targetPackage*/,
1818                            null /*finishedReceiver*/, updateUsers);
1819                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1820                    // First-install and we did a restore, so we're responsible for the
1821                    // first-launch broadcast.
1822                    if (DEBUG_BACKUP) {
1823                        Slog.i(TAG, "Post-restore of " + packageName
1824                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1825                    }
1826                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1827                }
1828
1829                // Send broadcast package appeared if forward locked/external for all users
1830                // treat asec-hosted packages like removable media on upgrade
1831                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1832                    if (DEBUG_INSTALL) {
1833                        Slog.i(TAG, "upgrading pkg " + res.pkg
1834                                + " is ASEC-hosted -> AVAILABLE");
1835                    }
1836                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1837                    ArrayList<String> pkgList = new ArrayList<>(1);
1838                    pkgList.add(packageName);
1839                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1840                }
1841            }
1842
1843            // Work that needs to happen on first install within each user
1844            if (firstUsers != null && firstUsers.length > 0) {
1845                synchronized (mPackages) {
1846                    for (int userId : firstUsers) {
1847                        // If this app is a browser and it's newly-installed for some
1848                        // users, clear any default-browser state in those users. The
1849                        // app's nature doesn't depend on the user, so we can just check
1850                        // its browser nature in any user and generalize.
1851                        if (packageIsBrowser(packageName, userId)) {
1852                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1853                        }
1854
1855                        // We may also need to apply pending (restored) runtime
1856                        // permission grants within these users.
1857                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1858                    }
1859                }
1860            }
1861
1862            // Log current value of "unknown sources" setting
1863            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1864                    getUnknownSourcesSettings());
1865
1866            // Force a gc to clear up things
1867            Runtime.getRuntime().gc();
1868
1869            // Remove the replaced package's older resources safely now
1870            // We delete after a gc for applications  on sdcard.
1871            if (res.removedInfo != null && res.removedInfo.args != null) {
1872                synchronized (mInstallLock) {
1873                    res.removedInfo.args.doPostDeleteLI(true);
1874                }
1875            }
1876
1877            if (!isEphemeral(res.pkg)) {
1878                // Notify DexManager that the package was installed for new users.
1879                // The updated users should already be indexed and the package code paths
1880                // should not change.
1881                // Don't notify the manager for ephemeral apps as they are not expected to
1882                // survive long enough to benefit of background optimizations.
1883                for (int userId : firstUsers) {
1884                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1885                    mDexManager.notifyPackageInstalled(info, userId);
1886                }
1887            }
1888        }
1889
1890        // If someone is watching installs - notify them
1891        if (installObserver != null) {
1892            try {
1893                Bundle extras = extrasForInstallResult(res);
1894                installObserver.onPackageInstalled(res.name, res.returnCode,
1895                        res.returnMsg, extras);
1896            } catch (RemoteException e) {
1897                Slog.i(TAG, "Observer no longer exists.");
1898            }
1899        }
1900    }
1901
1902    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1903            PackageParser.Package pkg) {
1904        if (pkg.parentPackage == null) {
1905            return;
1906        }
1907        if (pkg.requestedPermissions == null) {
1908            return;
1909        }
1910        final PackageSetting disabledSysParentPs = mSettings
1911                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1912        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1913                || !disabledSysParentPs.isPrivileged()
1914                || (disabledSysParentPs.childPackageNames != null
1915                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1916            return;
1917        }
1918        final int[] allUserIds = sUserManager.getUserIds();
1919        final int permCount = pkg.requestedPermissions.size();
1920        for (int i = 0; i < permCount; i++) {
1921            String permission = pkg.requestedPermissions.get(i);
1922            BasePermission bp = mSettings.mPermissions.get(permission);
1923            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1924                continue;
1925            }
1926            for (int userId : allUserIds) {
1927                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1928                        permission, userId)) {
1929                    grantRuntimePermission(pkg.packageName, permission, userId);
1930                }
1931            }
1932        }
1933    }
1934
1935    private StorageEventListener mStorageListener = new StorageEventListener() {
1936        @Override
1937        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1938            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1939                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1940                    final String volumeUuid = vol.getFsUuid();
1941
1942                    // Clean up any users or apps that were removed or recreated
1943                    // while this volume was missing
1944                    sUserManager.reconcileUsers(volumeUuid);
1945                    reconcileApps(volumeUuid);
1946
1947                    // Clean up any install sessions that expired or were
1948                    // cancelled while this volume was missing
1949                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1950
1951                    loadPrivatePackages(vol);
1952
1953                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1954                    unloadPrivatePackages(vol);
1955                }
1956            }
1957
1958            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1959                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1960                    updateExternalMediaStatus(true, false);
1961                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1962                    updateExternalMediaStatus(false, false);
1963                }
1964            }
1965        }
1966
1967        @Override
1968        public void onVolumeForgotten(String fsUuid) {
1969            if (TextUtils.isEmpty(fsUuid)) {
1970                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1971                return;
1972            }
1973
1974            // Remove any apps installed on the forgotten volume
1975            synchronized (mPackages) {
1976                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1977                for (PackageSetting ps : packages) {
1978                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1979                    deletePackageVersioned(new VersionedPackage(ps.name,
1980                            PackageManager.VERSION_CODE_HIGHEST),
1981                            new LegacyPackageDeleteObserver(null).getBinder(),
1982                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1983                    // Try very hard to release any references to this package
1984                    // so we don't risk the system server being killed due to
1985                    // open FDs
1986                    AttributeCache.instance().removePackage(ps.name);
1987                }
1988
1989                mSettings.onVolumeForgotten(fsUuid);
1990                mSettings.writeLPr();
1991            }
1992        }
1993    };
1994
1995    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1996            String[] grantedPermissions) {
1997        for (int userId : userIds) {
1998            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1999        }
2000    }
2001
2002    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2003            String[] grantedPermissions) {
2004        SettingBase sb = (SettingBase) pkg.mExtras;
2005        if (sb == null) {
2006            return;
2007        }
2008
2009        PermissionsState permissionsState = sb.getPermissionsState();
2010
2011        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2012                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2013
2014        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2015                >= Build.VERSION_CODES.M;
2016
2017        for (String permission : pkg.requestedPermissions) {
2018            final BasePermission bp;
2019            synchronized (mPackages) {
2020                bp = mSettings.mPermissions.get(permission);
2021            }
2022            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2023                    && (grantedPermissions == null
2024                           || ArrayUtils.contains(grantedPermissions, permission))) {
2025                final int flags = permissionsState.getPermissionFlags(permission, userId);
2026                if (supportsRuntimePermissions) {
2027                    // Installer cannot change immutable permissions.
2028                    if ((flags & immutableFlags) == 0) {
2029                        grantRuntimePermission(pkg.packageName, permission, userId);
2030                    }
2031                } else if (mPermissionReviewRequired) {
2032                    // In permission review mode we clear the review flag when we
2033                    // are asked to install the app with all permissions granted.
2034                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2035                        updatePermissionFlags(permission, pkg.packageName,
2036                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2037                    }
2038                }
2039            }
2040        }
2041    }
2042
2043    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2044        Bundle extras = null;
2045        switch (res.returnCode) {
2046            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2047                extras = new Bundle();
2048                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2049                        res.origPermission);
2050                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2051                        res.origPackage);
2052                break;
2053            }
2054            case PackageManager.INSTALL_SUCCEEDED: {
2055                extras = new Bundle();
2056                extras.putBoolean(Intent.EXTRA_REPLACING,
2057                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2058                break;
2059            }
2060        }
2061        return extras;
2062    }
2063
2064    void scheduleWriteSettingsLocked() {
2065        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2066            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2067        }
2068    }
2069
2070    void scheduleWritePackageListLocked(int userId) {
2071        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2072            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2073            msg.arg1 = userId;
2074            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2075        }
2076    }
2077
2078    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2079        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2080        scheduleWritePackageRestrictionsLocked(userId);
2081    }
2082
2083    void scheduleWritePackageRestrictionsLocked(int userId) {
2084        final int[] userIds = (userId == UserHandle.USER_ALL)
2085                ? sUserManager.getUserIds() : new int[]{userId};
2086        for (int nextUserId : userIds) {
2087            if (!sUserManager.exists(nextUserId)) return;
2088            mDirtyUsers.add(nextUserId);
2089            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2090                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2091            }
2092        }
2093    }
2094
2095    public static PackageManagerService main(Context context, Installer installer,
2096            boolean factoryTest, boolean onlyCore) {
2097        // Self-check for initial settings.
2098        PackageManagerServiceCompilerMapping.checkProperties();
2099
2100        PackageManagerService m = new PackageManagerService(context, installer,
2101                factoryTest, onlyCore);
2102        m.enableSystemUserPackages();
2103        ServiceManager.addService("package", m);
2104        return m;
2105    }
2106
2107    private void enableSystemUserPackages() {
2108        if (!UserManager.isSplitSystemUser()) {
2109            return;
2110        }
2111        // For system user, enable apps based on the following conditions:
2112        // - app is whitelisted or belong to one of these groups:
2113        //   -- system app which has no launcher icons
2114        //   -- system app which has INTERACT_ACROSS_USERS permission
2115        //   -- system IME app
2116        // - app is not in the blacklist
2117        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2118        Set<String> enableApps = new ArraySet<>();
2119        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2120                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2121                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2122        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2123        enableApps.addAll(wlApps);
2124        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2125                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2126        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2127        enableApps.removeAll(blApps);
2128        Log.i(TAG, "Applications installed for system user: " + enableApps);
2129        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2130                UserHandle.SYSTEM);
2131        final int allAppsSize = allAps.size();
2132        synchronized (mPackages) {
2133            for (int i = 0; i < allAppsSize; i++) {
2134                String pName = allAps.get(i);
2135                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2136                // Should not happen, but we shouldn't be failing if it does
2137                if (pkgSetting == null) {
2138                    continue;
2139                }
2140                boolean install = enableApps.contains(pName);
2141                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2142                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2143                            + " for system user");
2144                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2145                }
2146            }
2147        }
2148    }
2149
2150    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2151        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2152                Context.DISPLAY_SERVICE);
2153        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2154    }
2155
2156    /**
2157     * Requests that files preopted on a secondary system partition be copied to the data partition
2158     * if possible.  Note that the actual copying of the files is accomplished by init for security
2159     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2160     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2161     */
2162    private static void requestCopyPreoptedFiles() {
2163        final int WAIT_TIME_MS = 100;
2164        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2165        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2166            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2167            // We will wait for up to 100 seconds.
2168            final long timeStart = SystemClock.uptimeMillis();
2169            final long timeEnd = timeStart + 100 * 1000;
2170            long timeNow = timeStart;
2171            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2172                try {
2173                    Thread.sleep(WAIT_TIME_MS);
2174                } catch (InterruptedException e) {
2175                    // Do nothing
2176                }
2177                timeNow = SystemClock.uptimeMillis();
2178                if (timeNow > timeEnd) {
2179                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2180                    Slog.wtf(TAG, "cppreopt did not finish!");
2181                    break;
2182                }
2183            }
2184
2185            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2186        }
2187    }
2188
2189    public PackageManagerService(Context context, Installer installer,
2190            boolean factoryTest, boolean onlyCore) {
2191        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2192        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2193                SystemClock.uptimeMillis());
2194
2195        if (mSdkVersion <= 0) {
2196            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2197        }
2198
2199        mContext = context;
2200
2201        mPermissionReviewRequired = context.getResources().getBoolean(
2202                R.bool.config_permissionReviewRequired);
2203
2204        mFactoryTest = factoryTest;
2205        mOnlyCore = onlyCore;
2206        mMetrics = new DisplayMetrics();
2207        mSettings = new Settings(mPackages);
2208        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2209                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2210        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2211                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2212        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2213                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2214        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2215                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2216        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2217                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2218        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2219                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2220
2221        String separateProcesses = SystemProperties.get("debug.separate_processes");
2222        if (separateProcesses != null && separateProcesses.length() > 0) {
2223            if ("*".equals(separateProcesses)) {
2224                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2225                mSeparateProcesses = null;
2226                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2227            } else {
2228                mDefParseFlags = 0;
2229                mSeparateProcesses = separateProcesses.split(",");
2230                Slog.w(TAG, "Running with debug.separate_processes: "
2231                        + separateProcesses);
2232            }
2233        } else {
2234            mDefParseFlags = 0;
2235            mSeparateProcesses = null;
2236        }
2237
2238        mInstaller = installer;
2239        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2240                "*dexopt*");
2241        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2242        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2243
2244        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2245                FgThread.get().getLooper());
2246
2247        getDefaultDisplayMetrics(context, mMetrics);
2248
2249        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2250        SystemConfig systemConfig = SystemConfig.getInstance();
2251        mGlobalGids = systemConfig.getGlobalGids();
2252        mSystemPermissions = systemConfig.getSystemPermissions();
2253        mAvailableFeatures = systemConfig.getAvailableFeatures();
2254        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2255
2256        mProtectedPackages = new ProtectedPackages(mContext);
2257
2258        synchronized (mInstallLock) {
2259        // writer
2260        synchronized (mPackages) {
2261            mHandlerThread = new ServiceThread(TAG,
2262                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2263            mHandlerThread.start();
2264            mHandler = new PackageHandler(mHandlerThread.getLooper());
2265            mProcessLoggingHandler = new ProcessLoggingHandler();
2266            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2267
2268            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2269            mInstantAppRegistry = new InstantAppRegistry(this);
2270
2271            File dataDir = Environment.getDataDirectory();
2272            mAppInstallDir = new File(dataDir, "app");
2273            mAppLib32InstallDir = new File(dataDir, "app-lib");
2274            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2275            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2276            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2277            sUserManager = new UserManagerService(context, this,
2278                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2279
2280            // Propagate permission configuration in to package manager.
2281            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2282                    = systemConfig.getPermissions();
2283            for (int i=0; i<permConfig.size(); i++) {
2284                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2285                BasePermission bp = mSettings.mPermissions.get(perm.name);
2286                if (bp == null) {
2287                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2288                    mSettings.mPermissions.put(perm.name, bp);
2289                }
2290                if (perm.gids != null) {
2291                    bp.setGids(perm.gids, perm.perUser);
2292                }
2293            }
2294
2295            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2296            final int builtInLibCount = libConfig.size();
2297            for (int i = 0; i < builtInLibCount; i++) {
2298                String name = libConfig.keyAt(i);
2299                String path = libConfig.valueAt(i);
2300                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2301                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2302            }
2303
2304            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2305
2306            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2307            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2308            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2309
2310            // Clean up orphaned packages for which the code path doesn't exist
2311            // and they are an update to a system app - caused by bug/32321269
2312            final int packageSettingCount = mSettings.mPackages.size();
2313            for (int i = packageSettingCount - 1; i >= 0; i--) {
2314                PackageSetting ps = mSettings.mPackages.valueAt(i);
2315                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2316                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2317                    mSettings.mPackages.removeAt(i);
2318                    mSettings.enableSystemPackageLPw(ps.name);
2319                }
2320            }
2321
2322            if (mFirstBoot) {
2323                requestCopyPreoptedFiles();
2324            }
2325
2326            String customResolverActivity = Resources.getSystem().getString(
2327                    R.string.config_customResolverActivity);
2328            if (TextUtils.isEmpty(customResolverActivity)) {
2329                customResolverActivity = null;
2330            } else {
2331                mCustomResolverComponentName = ComponentName.unflattenFromString(
2332                        customResolverActivity);
2333            }
2334
2335            long startTime = SystemClock.uptimeMillis();
2336
2337            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2338                    startTime);
2339
2340            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2341            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2342
2343            if (bootClassPath == null) {
2344                Slog.w(TAG, "No BOOTCLASSPATH found!");
2345            }
2346
2347            if (systemServerClassPath == null) {
2348                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2349            }
2350
2351            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2352            final String[] dexCodeInstructionSets =
2353                    getDexCodeInstructionSets(
2354                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2355
2356            /**
2357             * Ensure all external libraries have had dexopt run on them.
2358             */
2359            if (mSharedLibraries.size() > 0) {
2360                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2361                // NOTE: For now, we're compiling these system "shared libraries"
2362                // (and framework jars) into all available architectures. It's possible
2363                // to compile them only when we come across an app that uses them (there's
2364                // already logic for that in scanPackageLI) but that adds some complexity.
2365                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2366                    final int libCount = mSharedLibraries.size();
2367                    for (int i = 0; i < libCount; i++) {
2368                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2369                        final int versionCount = versionedLib.size();
2370                        for (int j = 0; j < versionCount; j++) {
2371                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2372                            final String libPath = libEntry.path != null
2373                                    ? libEntry.path : libEntry.apk;
2374                            if (libPath == null) {
2375                                continue;
2376                            }
2377                            try {
2378                                // Shared libraries do not have profiles so we perform a full
2379                                // AOT compilation (if needed).
2380                                int dexoptNeeded = DexFile.getDexOptNeeded(
2381                                        libPath, dexCodeInstructionSet,
2382                                        getCompilerFilterForReason(REASON_SHARED_APK),
2383                                        false /* newProfile */);
2384                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2385                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2386                                            dexCodeInstructionSet, dexoptNeeded, null,
2387                                            DEXOPT_PUBLIC,
2388                                            getCompilerFilterForReason(REASON_SHARED_APK),
2389                                            StorageManager.UUID_PRIVATE_INTERNAL,
2390                                            SKIP_SHARED_LIBRARY_CHECK);
2391                                }
2392                            } catch (FileNotFoundException e) {
2393                                Slog.w(TAG, "Library not found: " + libPath);
2394                            } catch (IOException | InstallerException e) {
2395                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2396                                        + e.getMessage());
2397                            }
2398                        }
2399                    }
2400                }
2401                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2402            }
2403
2404            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2405
2406            final VersionInfo ver = mSettings.getInternalVersion();
2407            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2408
2409            // when upgrading from pre-M, promote system app permissions from install to runtime
2410            mPromoteSystemApps =
2411                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2412
2413            // When upgrading from pre-N, we need to handle package extraction like first boot,
2414            // as there is no profiling data available.
2415            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2416
2417            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2418
2419            // save off the names of pre-existing system packages prior to scanning; we don't
2420            // want to automatically grant runtime permissions for new system apps
2421            if (mPromoteSystemApps) {
2422                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2423                while (pkgSettingIter.hasNext()) {
2424                    PackageSetting ps = pkgSettingIter.next();
2425                    if (isSystemApp(ps)) {
2426                        mExistingSystemPackages.add(ps.name);
2427                    }
2428                }
2429            }
2430
2431            mCacheDir = preparePackageParserCache(mIsUpgrade);
2432
2433            // Set flag to monitor and not change apk file paths when
2434            // scanning install directories.
2435            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2436
2437            if (mIsUpgrade || mFirstBoot) {
2438                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2439            }
2440
2441            // Collect vendor overlay packages. (Do this before scanning any apps.)
2442            // For security and version matching reason, only consider
2443            // overlay packages if they reside in the right directory.
2444            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2445            if (overlayThemeDir.isEmpty()) {
2446                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2447            }
2448            if (!overlayThemeDir.isEmpty()) {
2449                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2450                        | PackageParser.PARSE_IS_SYSTEM
2451                        | PackageParser.PARSE_IS_SYSTEM_DIR
2452                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2453            }
2454            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2455                    | PackageParser.PARSE_IS_SYSTEM
2456                    | PackageParser.PARSE_IS_SYSTEM_DIR
2457                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2458
2459            // Find base frameworks (resource packages without code).
2460            scanDirTracedLI(frameworkDir, mDefParseFlags
2461                    | PackageParser.PARSE_IS_SYSTEM
2462                    | PackageParser.PARSE_IS_SYSTEM_DIR
2463                    | PackageParser.PARSE_IS_PRIVILEGED,
2464                    scanFlags | SCAN_NO_DEX, 0);
2465
2466            // Collected privileged system packages.
2467            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2468            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2469                    | PackageParser.PARSE_IS_SYSTEM
2470                    | PackageParser.PARSE_IS_SYSTEM_DIR
2471                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2472
2473            // Collect ordinary system packages.
2474            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2475            scanDirTracedLI(systemAppDir, mDefParseFlags
2476                    | PackageParser.PARSE_IS_SYSTEM
2477                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2478
2479            // Collect all vendor packages.
2480            File vendorAppDir = new File("/vendor/app");
2481            try {
2482                vendorAppDir = vendorAppDir.getCanonicalFile();
2483            } catch (IOException e) {
2484                // failed to look up canonical path, continue with original one
2485            }
2486            scanDirTracedLI(vendorAppDir, mDefParseFlags
2487                    | PackageParser.PARSE_IS_SYSTEM
2488                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2489
2490            // Collect all OEM packages.
2491            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2492            scanDirTracedLI(oemAppDir, mDefParseFlags
2493                    | PackageParser.PARSE_IS_SYSTEM
2494                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2495
2496            // Prune any system packages that no longer exist.
2497            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2498            if (!mOnlyCore) {
2499                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2500                while (psit.hasNext()) {
2501                    PackageSetting ps = psit.next();
2502
2503                    /*
2504                     * If this is not a system app, it can't be a
2505                     * disable system app.
2506                     */
2507                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2508                        continue;
2509                    }
2510
2511                    /*
2512                     * If the package is scanned, it's not erased.
2513                     */
2514                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2515                    if (scannedPkg != null) {
2516                        /*
2517                         * If the system app is both scanned and in the
2518                         * disabled packages list, then it must have been
2519                         * added via OTA. Remove it from the currently
2520                         * scanned package so the previously user-installed
2521                         * application can be scanned.
2522                         */
2523                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2524                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2525                                    + ps.name + "; removing system app.  Last known codePath="
2526                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2527                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2528                                    + scannedPkg.mVersionCode);
2529                            removePackageLI(scannedPkg, true);
2530                            mExpectingBetter.put(ps.name, ps.codePath);
2531                        }
2532
2533                        continue;
2534                    }
2535
2536                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2537                        psit.remove();
2538                        logCriticalInfo(Log.WARN, "System package " + ps.name
2539                                + " no longer exists; it's data will be wiped");
2540                        // Actual deletion of code and data will be handled by later
2541                        // reconciliation step
2542                    } else {
2543                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2544                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2545                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2546                        }
2547                    }
2548                }
2549            }
2550
2551            //look for any incomplete package installations
2552            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2553            for (int i = 0; i < deletePkgsList.size(); i++) {
2554                // Actual deletion of code and data will be handled by later
2555                // reconciliation step
2556                final String packageName = deletePkgsList.get(i).name;
2557                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2558                synchronized (mPackages) {
2559                    mSettings.removePackageLPw(packageName);
2560                }
2561            }
2562
2563            //delete tmp files
2564            deleteTempPackageFiles();
2565
2566            // Remove any shared userIDs that have no associated packages
2567            mSettings.pruneSharedUsersLPw();
2568
2569            if (!mOnlyCore) {
2570                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2571                        SystemClock.uptimeMillis());
2572                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2573
2574                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2575                        | PackageParser.PARSE_FORWARD_LOCK,
2576                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2577
2578                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2579                        | PackageParser.PARSE_IS_EPHEMERAL,
2580                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2581
2582                /**
2583                 * Remove disable package settings for any updated system
2584                 * apps that were removed via an OTA. If they're not a
2585                 * previously-updated app, remove them completely.
2586                 * Otherwise, just revoke their system-level permissions.
2587                 */
2588                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2589                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2590                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2591
2592                    String msg;
2593                    if (deletedPkg == null) {
2594                        msg = "Updated system package " + deletedAppName
2595                                + " no longer exists; it's data will be wiped";
2596                        // Actual deletion of code and data will be handled by later
2597                        // reconciliation step
2598                    } else {
2599                        msg = "Updated system app + " + deletedAppName
2600                                + " no longer present; removing system privileges for "
2601                                + deletedAppName;
2602
2603                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2604
2605                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2606                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2607                    }
2608                    logCriticalInfo(Log.WARN, msg);
2609                }
2610
2611                /**
2612                 * Make sure all system apps that we expected to appear on
2613                 * the userdata partition actually showed up. If they never
2614                 * appeared, crawl back and revive the system version.
2615                 */
2616                for (int i = 0; i < mExpectingBetter.size(); i++) {
2617                    final String packageName = mExpectingBetter.keyAt(i);
2618                    if (!mPackages.containsKey(packageName)) {
2619                        final File scanFile = mExpectingBetter.valueAt(i);
2620
2621                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2622                                + " but never showed up; reverting to system");
2623
2624                        int reparseFlags = mDefParseFlags;
2625                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2626                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2627                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2628                                    | PackageParser.PARSE_IS_PRIVILEGED;
2629                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2630                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2631                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2632                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2633                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2634                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2635                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2636                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2637                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2638                        } else {
2639                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2640                            continue;
2641                        }
2642
2643                        mSettings.enableSystemPackageLPw(packageName);
2644
2645                        try {
2646                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2647                        } catch (PackageManagerException e) {
2648                            Slog.e(TAG, "Failed to parse original system package: "
2649                                    + e.getMessage());
2650                        }
2651                    }
2652                }
2653            }
2654            mExpectingBetter.clear();
2655
2656            // Resolve the storage manager.
2657            mStorageManagerPackage = getStorageManagerPackageName();
2658
2659            // Resolve protected action filters. Only the setup wizard is allowed to
2660            // have a high priority filter for these actions.
2661            mSetupWizardPackage = getSetupWizardPackageName();
2662            if (mProtectedFilters.size() > 0) {
2663                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2664                    Slog.i(TAG, "No setup wizard;"
2665                        + " All protected intents capped to priority 0");
2666                }
2667                for (ActivityIntentInfo filter : mProtectedFilters) {
2668                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2669                        if (DEBUG_FILTERS) {
2670                            Slog.i(TAG, "Found setup wizard;"
2671                                + " allow priority " + filter.getPriority() + ";"
2672                                + " package: " + filter.activity.info.packageName
2673                                + " activity: " + filter.activity.className
2674                                + " priority: " + filter.getPriority());
2675                        }
2676                        // skip setup wizard; allow it to keep the high priority filter
2677                        continue;
2678                    }
2679                    Slog.w(TAG, "Protected action; cap priority to 0;"
2680                            + " package: " + filter.activity.info.packageName
2681                            + " activity: " + filter.activity.className
2682                            + " origPrio: " + filter.getPriority());
2683                    filter.setPriority(0);
2684                }
2685            }
2686            mDeferProtectedFilters = false;
2687            mProtectedFilters.clear();
2688
2689            // Now that we know all of the shared libraries, update all clients to have
2690            // the correct library paths.
2691            updateAllSharedLibrariesLPw(null);
2692
2693            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2694                // NOTE: We ignore potential failures here during a system scan (like
2695                // the rest of the commands above) because there's precious little we
2696                // can do about it. A settings error is reported, though.
2697                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2698            }
2699
2700            // Now that we know all the packages we are keeping,
2701            // read and update their last usage times.
2702            mPackageUsage.read(mPackages);
2703            mCompilerStats.read();
2704
2705            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2706                    SystemClock.uptimeMillis());
2707            Slog.i(TAG, "Time to scan packages: "
2708                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2709                    + " seconds");
2710
2711            // If the platform SDK has changed since the last time we booted,
2712            // we need to re-grant app permission to catch any new ones that
2713            // appear.  This is really a hack, and means that apps can in some
2714            // cases get permissions that the user didn't initially explicitly
2715            // allow...  it would be nice to have some better way to handle
2716            // this situation.
2717            int updateFlags = UPDATE_PERMISSIONS_ALL;
2718            if (ver.sdkVersion != mSdkVersion) {
2719                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2720                        + mSdkVersion + "; regranting permissions for internal storage");
2721                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2722            }
2723            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2724            ver.sdkVersion = mSdkVersion;
2725
2726            // If this is the first boot or an update from pre-M, and it is a normal
2727            // boot, then we need to initialize the default preferred apps across
2728            // all defined users.
2729            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2730                for (UserInfo user : sUserManager.getUsers(true)) {
2731                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2732                    applyFactoryDefaultBrowserLPw(user.id);
2733                    primeDomainVerificationsLPw(user.id);
2734                }
2735            }
2736
2737            // Prepare storage for system user really early during boot,
2738            // since core system apps like SettingsProvider and SystemUI
2739            // can't wait for user to start
2740            final int storageFlags;
2741            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2742                storageFlags = StorageManager.FLAG_STORAGE_DE;
2743            } else {
2744                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2745            }
2746            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2747                    storageFlags, true /* migrateAppData */);
2748
2749            // If this is first boot after an OTA, and a normal boot, then
2750            // we need to clear code cache directories.
2751            // Note that we do *not* clear the application profiles. These remain valid
2752            // across OTAs and are used to drive profile verification (post OTA) and
2753            // profile compilation (without waiting to collect a fresh set of profiles).
2754            if (mIsUpgrade && !onlyCore) {
2755                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2756                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2757                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2758                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2759                        // No apps are running this early, so no need to freeze
2760                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2761                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2762                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2763                    }
2764                }
2765                ver.fingerprint = Build.FINGERPRINT;
2766            }
2767
2768            checkDefaultBrowser();
2769
2770            // clear only after permissions and other defaults have been updated
2771            mExistingSystemPackages.clear();
2772            mPromoteSystemApps = false;
2773
2774            // All the changes are done during package scanning.
2775            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2776
2777            // can downgrade to reader
2778            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2779            mSettings.writeLPr();
2780            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2781
2782            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2783            // early on (before the package manager declares itself as early) because other
2784            // components in the system server might ask for package contexts for these apps.
2785            //
2786            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2787            // (i.e, that the data partition is unavailable).
2788            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2789                long start = System.nanoTime();
2790                List<PackageParser.Package> coreApps = new ArrayList<>();
2791                for (PackageParser.Package pkg : mPackages.values()) {
2792                    if (pkg.coreApp) {
2793                        coreApps.add(pkg);
2794                    }
2795                }
2796
2797                int[] stats = performDexOptUpgrade(coreApps, false,
2798                        getCompilerFilterForReason(REASON_CORE_APP));
2799
2800                final int elapsedTimeSeconds =
2801                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2802                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2803
2804                if (DEBUG_DEXOPT) {
2805                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2806                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2807                }
2808
2809
2810                // TODO: Should we log these stats to tron too ?
2811                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2812                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2813                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2814                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2815            }
2816
2817            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2818                    SystemClock.uptimeMillis());
2819
2820            if (!mOnlyCore) {
2821                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2822                mRequiredInstallerPackage = getRequiredInstallerLPr();
2823                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2824                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2825                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2826                        mIntentFilterVerifierComponent);
2827                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2828                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2829                        SharedLibraryInfo.VERSION_UNDEFINED);
2830                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2831                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2832                        SharedLibraryInfo.VERSION_UNDEFINED);
2833            } else {
2834                mRequiredVerifierPackage = null;
2835                mRequiredInstallerPackage = null;
2836                mRequiredUninstallerPackage = null;
2837                mIntentFilterVerifierComponent = null;
2838                mIntentFilterVerifier = null;
2839                mServicesSystemSharedLibraryPackageName = null;
2840                mSharedSystemSharedLibraryPackageName = null;
2841            }
2842
2843            mInstallerService = new PackageInstallerService(context, this);
2844
2845            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2846            if (ephemeralResolverComponent != null) {
2847                if (DEBUG_EPHEMERAL) {
2848                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2849                }
2850                mEphemeralResolverConnection =
2851                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2852            } else {
2853                mEphemeralResolverConnection = null;
2854            }
2855            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2856            if (mEphemeralInstallerComponent != null) {
2857                if (DEBUG_EPHEMERAL) {
2858                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2859                }
2860                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2861            }
2862
2863            // Read and update the usage of dex files.
2864            // Do this at the end of PM init so that all the packages have their
2865            // data directory reconciled.
2866            // At this point we know the code paths of the packages, so we can validate
2867            // the disk file and build the internal cache.
2868            // The usage file is expected to be small so loading and verifying it
2869            // should take a fairly small time compare to the other activities (e.g. package
2870            // scanning).
2871            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2872            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2873            for (int userId : currentUserIds) {
2874                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2875            }
2876            mDexManager.load(userPackages);
2877        } // synchronized (mPackages)
2878        } // synchronized (mInstallLock)
2879
2880        // Now after opening every single application zip, make sure they
2881        // are all flushed.  Not really needed, but keeps things nice and
2882        // tidy.
2883        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2884        Runtime.getRuntime().gc();
2885        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2886
2887        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2888        FallbackCategoryProvider.loadFallbacks();
2889        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2890
2891        // The initial scanning above does many calls into installd while
2892        // holding the mPackages lock, but we're mostly interested in yelling
2893        // once we have a booted system.
2894        mInstaller.setWarnIfHeld(mPackages);
2895
2896        // Expose private service for system components to use.
2897        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2898        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2899    }
2900
2901    private static File preparePackageParserCache(boolean isUpgrade) {
2902        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2903            return null;
2904        }
2905
2906        // Disable package parsing on eng builds to allow for faster incremental development.
2907        if ("eng".equals(Build.TYPE)) {
2908            return null;
2909        }
2910
2911        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2912            Slog.i(TAG, "Disabling package parser cache due to system property.");
2913            return null;
2914        }
2915
2916        // The base directory for the package parser cache lives under /data/system/.
2917        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2918                "package_cache");
2919        if (cacheBaseDir == null) {
2920            return null;
2921        }
2922
2923        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2924        // This also serves to "GC" unused entries when the package cache version changes (which
2925        // can only happen during upgrades).
2926        if (isUpgrade) {
2927            FileUtils.deleteContents(cacheBaseDir);
2928        }
2929
2930
2931        // Return the versioned package cache directory. This is something like
2932        // "/data/system/package_cache/1"
2933        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2934
2935        // The following is a workaround to aid development on non-numbered userdebug
2936        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2937        // the system partition is newer.
2938        //
2939        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2940        // that starts with "eng." to signify that this is an engineering build and not
2941        // destined for release.
2942        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2943            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2944
2945            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2946            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2947            // in general and should not be used for production changes. In this specific case,
2948            // we know that they will work.
2949            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2950            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2951                FileUtils.deleteContents(cacheBaseDir);
2952                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2953            }
2954        }
2955
2956        return cacheDir;
2957    }
2958
2959    @Override
2960    public boolean isFirstBoot() {
2961        return mFirstBoot;
2962    }
2963
2964    @Override
2965    public boolean isOnlyCoreApps() {
2966        return mOnlyCore;
2967    }
2968
2969    @Override
2970    public boolean isUpgrade() {
2971        return mIsUpgrade;
2972    }
2973
2974    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2975        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2976
2977        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2978                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2979                UserHandle.USER_SYSTEM);
2980        if (matches.size() == 1) {
2981            return matches.get(0).getComponentInfo().packageName;
2982        } else if (matches.size() == 0) {
2983            Log.e(TAG, "There should probably be a verifier, but, none were found");
2984            return null;
2985        }
2986        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2987    }
2988
2989    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2990        synchronized (mPackages) {
2991            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2992            if (libraryEntry == null) {
2993                throw new IllegalStateException("Missing required shared library:" + name);
2994            }
2995            return libraryEntry.apk;
2996        }
2997    }
2998
2999    private @NonNull String getRequiredInstallerLPr() {
3000        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3001        intent.addCategory(Intent.CATEGORY_DEFAULT);
3002        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3003
3004        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3005                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3006                UserHandle.USER_SYSTEM);
3007        if (matches.size() == 1) {
3008            ResolveInfo resolveInfo = matches.get(0);
3009            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3010                throw new RuntimeException("The installer must be a privileged app");
3011            }
3012            return matches.get(0).getComponentInfo().packageName;
3013        } else {
3014            throw new RuntimeException("There must be exactly one installer; found " + matches);
3015        }
3016    }
3017
3018    private @NonNull String getRequiredUninstallerLPr() {
3019        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3020        intent.addCategory(Intent.CATEGORY_DEFAULT);
3021        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3022
3023        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3024                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3025                UserHandle.USER_SYSTEM);
3026        if (resolveInfo == null ||
3027                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3028            throw new RuntimeException("There must be exactly one uninstaller; found "
3029                    + resolveInfo);
3030        }
3031        return resolveInfo.getComponentInfo().packageName;
3032    }
3033
3034    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3035        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3036
3037        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3038                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3039                UserHandle.USER_SYSTEM);
3040        ResolveInfo best = null;
3041        final int N = matches.size();
3042        for (int i = 0; i < N; i++) {
3043            final ResolveInfo cur = matches.get(i);
3044            final String packageName = cur.getComponentInfo().packageName;
3045            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3046                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3047                continue;
3048            }
3049
3050            if (best == null || cur.priority > best.priority) {
3051                best = cur;
3052            }
3053        }
3054
3055        if (best != null) {
3056            return best.getComponentInfo().getComponentName();
3057        } else {
3058            throw new RuntimeException("There must be at least one intent filter verifier");
3059        }
3060    }
3061
3062    private @Nullable ComponentName getEphemeralResolverLPr() {
3063        final String[] packageArray =
3064                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3065        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3066            if (DEBUG_EPHEMERAL) {
3067                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3068            }
3069            return null;
3070        }
3071
3072        final int resolveFlags =
3073                MATCH_DIRECT_BOOT_AWARE
3074                | MATCH_DIRECT_BOOT_UNAWARE
3075                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3076        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3077        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3078                resolveFlags, UserHandle.USER_SYSTEM);
3079
3080        final int N = resolvers.size();
3081        if (N == 0) {
3082            if (DEBUG_EPHEMERAL) {
3083                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3084            }
3085            return null;
3086        }
3087
3088        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3089        for (int i = 0; i < N; i++) {
3090            final ResolveInfo info = resolvers.get(i);
3091
3092            if (info.serviceInfo == null) {
3093                continue;
3094            }
3095
3096            final String packageName = info.serviceInfo.packageName;
3097            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3098                if (DEBUG_EPHEMERAL) {
3099                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3100                            + " pkg: " + packageName + ", info:" + info);
3101                }
3102                continue;
3103            }
3104
3105            if (DEBUG_EPHEMERAL) {
3106                Slog.v(TAG, "Ephemeral resolver found;"
3107                        + " pkg: " + packageName + ", info:" + info);
3108            }
3109            return new ComponentName(packageName, info.serviceInfo.name);
3110        }
3111        if (DEBUG_EPHEMERAL) {
3112            Slog.v(TAG, "Ephemeral resolver NOT found");
3113        }
3114        return null;
3115    }
3116
3117    private @Nullable ComponentName getEphemeralInstallerLPr() {
3118        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3119        intent.addCategory(Intent.CATEGORY_DEFAULT);
3120        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3121
3122        final int resolveFlags =
3123                MATCH_DIRECT_BOOT_AWARE
3124                | MATCH_DIRECT_BOOT_UNAWARE
3125                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3126        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3127                resolveFlags, UserHandle.USER_SYSTEM);
3128        Iterator<ResolveInfo> iter = matches.iterator();
3129        while (iter.hasNext()) {
3130            final ResolveInfo rInfo = iter.next();
3131            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3132            if (ps != null) {
3133                final PermissionsState permissionsState = ps.getPermissionsState();
3134                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3135                    continue;
3136                }
3137            }
3138            iter.remove();
3139        }
3140        if (matches.size() == 0) {
3141            return null;
3142        } else if (matches.size() == 1) {
3143            return matches.get(0).getComponentInfo().getComponentName();
3144        } else {
3145            throw new RuntimeException(
3146                    "There must be at most one ephemeral installer; found " + matches);
3147        }
3148    }
3149
3150    private void primeDomainVerificationsLPw(int userId) {
3151        if (DEBUG_DOMAIN_VERIFICATION) {
3152            Slog.d(TAG, "Priming domain verifications in user " + userId);
3153        }
3154
3155        SystemConfig systemConfig = SystemConfig.getInstance();
3156        ArraySet<String> packages = systemConfig.getLinkedApps();
3157
3158        for (String packageName : packages) {
3159            PackageParser.Package pkg = mPackages.get(packageName);
3160            if (pkg != null) {
3161                if (!pkg.isSystemApp()) {
3162                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3163                    continue;
3164                }
3165
3166                ArraySet<String> domains = null;
3167                for (PackageParser.Activity a : pkg.activities) {
3168                    for (ActivityIntentInfo filter : a.intents) {
3169                        if (hasValidDomains(filter)) {
3170                            if (domains == null) {
3171                                domains = new ArraySet<String>();
3172                            }
3173                            domains.addAll(filter.getHostsList());
3174                        }
3175                    }
3176                }
3177
3178                if (domains != null && domains.size() > 0) {
3179                    if (DEBUG_DOMAIN_VERIFICATION) {
3180                        Slog.v(TAG, "      + " + packageName);
3181                    }
3182                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3183                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3184                    // and then 'always' in the per-user state actually used for intent resolution.
3185                    final IntentFilterVerificationInfo ivi;
3186                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3187                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3188                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3189                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3190                } else {
3191                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3192                            + "' does not handle web links");
3193                }
3194            } else {
3195                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3196            }
3197        }
3198
3199        scheduleWritePackageRestrictionsLocked(userId);
3200        scheduleWriteSettingsLocked();
3201    }
3202
3203    private void applyFactoryDefaultBrowserLPw(int userId) {
3204        // The default browser app's package name is stored in a string resource,
3205        // with a product-specific overlay used for vendor customization.
3206        String browserPkg = mContext.getResources().getString(
3207                com.android.internal.R.string.default_browser);
3208        if (!TextUtils.isEmpty(browserPkg)) {
3209            // non-empty string => required to be a known package
3210            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3211            if (ps == null) {
3212                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3213                browserPkg = null;
3214            } else {
3215                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3216            }
3217        }
3218
3219        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3220        // default.  If there's more than one, just leave everything alone.
3221        if (browserPkg == null) {
3222            calculateDefaultBrowserLPw(userId);
3223        }
3224    }
3225
3226    private void calculateDefaultBrowserLPw(int userId) {
3227        List<String> allBrowsers = resolveAllBrowserApps(userId);
3228        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3229        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3230    }
3231
3232    private List<String> resolveAllBrowserApps(int userId) {
3233        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3234        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3235                PackageManager.MATCH_ALL, userId);
3236
3237        final int count = list.size();
3238        List<String> result = new ArrayList<String>(count);
3239        for (int i=0; i<count; i++) {
3240            ResolveInfo info = list.get(i);
3241            if (info.activityInfo == null
3242                    || !info.handleAllWebDataURI
3243                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3244                    || result.contains(info.activityInfo.packageName)) {
3245                continue;
3246            }
3247            result.add(info.activityInfo.packageName);
3248        }
3249
3250        return result;
3251    }
3252
3253    private boolean packageIsBrowser(String packageName, int userId) {
3254        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3255                PackageManager.MATCH_ALL, userId);
3256        final int N = list.size();
3257        for (int i = 0; i < N; i++) {
3258            ResolveInfo info = list.get(i);
3259            if (packageName.equals(info.activityInfo.packageName)) {
3260                return true;
3261            }
3262        }
3263        return false;
3264    }
3265
3266    private void checkDefaultBrowser() {
3267        final int myUserId = UserHandle.myUserId();
3268        final String packageName = getDefaultBrowserPackageName(myUserId);
3269        if (packageName != null) {
3270            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3271            if (info == null) {
3272                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3273                synchronized (mPackages) {
3274                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3275                }
3276            }
3277        }
3278    }
3279
3280    @Override
3281    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3282            throws RemoteException {
3283        try {
3284            return super.onTransact(code, data, reply, flags);
3285        } catch (RuntimeException e) {
3286            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3287                Slog.wtf(TAG, "Package Manager Crash", e);
3288            }
3289            throw e;
3290        }
3291    }
3292
3293    static int[] appendInts(int[] cur, int[] add) {
3294        if (add == null) return cur;
3295        if (cur == null) return add;
3296        final int N = add.length;
3297        for (int i=0; i<N; i++) {
3298            cur = appendInt(cur, add[i]);
3299        }
3300        return cur;
3301    }
3302
3303    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3304        if (!sUserManager.exists(userId)) return null;
3305        if (ps == null) {
3306            return null;
3307        }
3308        final PackageParser.Package p = ps.pkg;
3309        if (p == null) {
3310            return null;
3311        }
3312        // Filter out ephemeral app metadata:
3313        //   * The system/shell/root can see metadata for any app
3314        //   * An installed app can see metadata for 1) other installed apps
3315        //     and 2) ephemeral apps that have explicitly interacted with it
3316        //   * Ephemeral apps can only see their own metadata
3317        //   * Holding a signature permission allows seeing instant apps
3318        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3319        if (callingAppId != Process.SYSTEM_UID
3320                && callingAppId != Process.SHELL_UID
3321                && callingAppId != Process.ROOT_UID
3322                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3323                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3324            final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid());
3325            if (ephemeralPackageName != null) {
3326                // ephemeral apps can only get information on themselves
3327                if (!ephemeralPackageName.equals(p.packageName)) {
3328                    return null;
3329                }
3330            } else {
3331                if (p.applicationInfo.isInstantApp()) {
3332                    // only get access to the ephemeral app if we've been granted access
3333                    if (!mInstantAppRegistry.isInstantAccessGranted(
3334                            userId, callingAppId, ps.appId)) {
3335                        return null;
3336                    }
3337                }
3338            }
3339        }
3340
3341        final PermissionsState permissionsState = ps.getPermissionsState();
3342
3343        // Compute GIDs only if requested
3344        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3345                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3346        // Compute granted permissions only if package has requested permissions
3347        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3348                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3349        final PackageUserState state = ps.readUserState(userId);
3350
3351        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3352                && ps.isSystem()) {
3353            flags |= MATCH_ANY_USER;
3354        }
3355
3356        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3357                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3358
3359        if (packageInfo == null) {
3360            return null;
3361        }
3362
3363        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3364                resolveExternalPackageNameLPr(p);
3365
3366        return packageInfo;
3367    }
3368
3369    @Override
3370    public void checkPackageStartable(String packageName, int userId) {
3371        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3372
3373        synchronized (mPackages) {
3374            final PackageSetting ps = mSettings.mPackages.get(packageName);
3375            if (ps == null) {
3376                throw new SecurityException("Package " + packageName + " was not found!");
3377            }
3378
3379            if (!ps.getInstalled(userId)) {
3380                throw new SecurityException(
3381                        "Package " + packageName + " was not installed for user " + userId + "!");
3382            }
3383
3384            if (mSafeMode && !ps.isSystem()) {
3385                throw new SecurityException("Package " + packageName + " not a system app!");
3386            }
3387
3388            if (mFrozenPackages.contains(packageName)) {
3389                throw new SecurityException("Package " + packageName + " is currently frozen!");
3390            }
3391
3392            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3393                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3394                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3395            }
3396        }
3397    }
3398
3399    @Override
3400    public boolean isPackageAvailable(String packageName, int userId) {
3401        if (!sUserManager.exists(userId)) return false;
3402        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3403                false /* requireFullPermission */, false /* checkShell */, "is package available");
3404        synchronized (mPackages) {
3405            PackageParser.Package p = mPackages.get(packageName);
3406            if (p != null) {
3407                final PackageSetting ps = (PackageSetting) p.mExtras;
3408                if (ps != null) {
3409                    final PackageUserState state = ps.readUserState(userId);
3410                    if (state != null) {
3411                        return PackageParser.isAvailable(state);
3412                    }
3413                }
3414            }
3415        }
3416        return false;
3417    }
3418
3419    @Override
3420    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3421        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3422                flags, userId);
3423    }
3424
3425    @Override
3426    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3427            int flags, int userId) {
3428        return getPackageInfoInternal(versionedPackage.getPackageName(),
3429                // TODO: We will change version code to long, so in the new API it is long
3430                (int) versionedPackage.getVersionCode(), flags, userId);
3431    }
3432
3433    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3434            int flags, int userId) {
3435        if (!sUserManager.exists(userId)) return null;
3436        flags = updateFlagsForPackage(flags, userId, packageName);
3437        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3438                false /* requireFullPermission */, false /* checkShell */, "get package info");
3439
3440        // reader
3441        synchronized (mPackages) {
3442            // Normalize package name to handle renamed packages and static libs
3443            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3444
3445            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3446            if (matchFactoryOnly) {
3447                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3448                if (ps != null) {
3449                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3450                        return null;
3451                    }
3452                    return generatePackageInfo(ps, flags, userId);
3453                }
3454            }
3455
3456            PackageParser.Package p = mPackages.get(packageName);
3457            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3458                return null;
3459            }
3460            if (DEBUG_PACKAGE_INFO)
3461                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3462            if (p != null) {
3463                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3464                        Binder.getCallingUid(), userId)) {
3465                    return null;
3466                }
3467                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3468            }
3469            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3470                final PackageSetting ps = mSettings.mPackages.get(packageName);
3471                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3472                    return null;
3473                }
3474                return generatePackageInfo(ps, flags, userId);
3475            }
3476        }
3477        return null;
3478    }
3479
3480
3481    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3482        // System/shell/root get to see all static libs
3483        final int appId = UserHandle.getAppId(uid);
3484        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3485                || appId == Process.ROOT_UID) {
3486            return false;
3487        }
3488
3489        // No package means no static lib as it is always on internal storage
3490        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3491            return false;
3492        }
3493
3494        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3495                ps.pkg.staticSharedLibVersion);
3496        if (libEntry == null) {
3497            return false;
3498        }
3499
3500        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3501        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3502        if (uidPackageNames == null) {
3503            return true;
3504        }
3505
3506        for (String uidPackageName : uidPackageNames) {
3507            if (ps.name.equals(uidPackageName)) {
3508                return false;
3509            }
3510            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3511            if (uidPs != null) {
3512                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3513                        libEntry.info.getName());
3514                if (index < 0) {
3515                    continue;
3516                }
3517                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3518                    return false;
3519                }
3520            }
3521        }
3522        return true;
3523    }
3524
3525    @Override
3526    public String[] currentToCanonicalPackageNames(String[] names) {
3527        String[] out = new String[names.length];
3528        // reader
3529        synchronized (mPackages) {
3530            for (int i=names.length-1; i>=0; i--) {
3531                PackageSetting ps = mSettings.mPackages.get(names[i]);
3532                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3533            }
3534        }
3535        return out;
3536    }
3537
3538    @Override
3539    public String[] canonicalToCurrentPackageNames(String[] names) {
3540        String[] out = new String[names.length];
3541        // reader
3542        synchronized (mPackages) {
3543            for (int i=names.length-1; i>=0; i--) {
3544                String cur = mSettings.getRenamedPackageLPr(names[i]);
3545                out[i] = cur != null ? cur : names[i];
3546            }
3547        }
3548        return out;
3549    }
3550
3551    @Override
3552    public int getPackageUid(String packageName, int flags, int userId) {
3553        if (!sUserManager.exists(userId)) return -1;
3554        flags = updateFlagsForPackage(flags, userId, packageName);
3555        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3556                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3557
3558        // reader
3559        synchronized (mPackages) {
3560            final PackageParser.Package p = mPackages.get(packageName);
3561            if (p != null && p.isMatch(flags)) {
3562                return UserHandle.getUid(userId, p.applicationInfo.uid);
3563            }
3564            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3565                final PackageSetting ps = mSettings.mPackages.get(packageName);
3566                if (ps != null && ps.isMatch(flags)) {
3567                    return UserHandle.getUid(userId, ps.appId);
3568                }
3569            }
3570        }
3571
3572        return -1;
3573    }
3574
3575    @Override
3576    public int[] getPackageGids(String packageName, int flags, int userId) {
3577        if (!sUserManager.exists(userId)) return null;
3578        flags = updateFlagsForPackage(flags, userId, packageName);
3579        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3580                false /* requireFullPermission */, false /* checkShell */,
3581                "getPackageGids");
3582
3583        // reader
3584        synchronized (mPackages) {
3585            final PackageParser.Package p = mPackages.get(packageName);
3586            if (p != null && p.isMatch(flags)) {
3587                PackageSetting ps = (PackageSetting) p.mExtras;
3588                // TODO: Shouldn't this be checking for package installed state for userId and
3589                // return null?
3590                return ps.getPermissionsState().computeGids(userId);
3591            }
3592            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3593                final PackageSetting ps = mSettings.mPackages.get(packageName);
3594                if (ps != null && ps.isMatch(flags)) {
3595                    return ps.getPermissionsState().computeGids(userId);
3596                }
3597            }
3598        }
3599
3600        return null;
3601    }
3602
3603    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3604        if (bp.perm != null) {
3605            return PackageParser.generatePermissionInfo(bp.perm, flags);
3606        }
3607        PermissionInfo pi = new PermissionInfo();
3608        pi.name = bp.name;
3609        pi.packageName = bp.sourcePackage;
3610        pi.nonLocalizedLabel = bp.name;
3611        pi.protectionLevel = bp.protectionLevel;
3612        return pi;
3613    }
3614
3615    @Override
3616    public PermissionInfo getPermissionInfo(String name, int flags) {
3617        // reader
3618        synchronized (mPackages) {
3619            final BasePermission p = mSettings.mPermissions.get(name);
3620            if (p != null) {
3621                return generatePermissionInfo(p, flags);
3622            }
3623            return null;
3624        }
3625    }
3626
3627    @Override
3628    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3629            int flags) {
3630        // reader
3631        synchronized (mPackages) {
3632            if (group != null && !mPermissionGroups.containsKey(group)) {
3633                // This is thrown as NameNotFoundException
3634                return null;
3635            }
3636
3637            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3638            for (BasePermission p : mSettings.mPermissions.values()) {
3639                if (group == null) {
3640                    if (p.perm == null || p.perm.info.group == null) {
3641                        out.add(generatePermissionInfo(p, flags));
3642                    }
3643                } else {
3644                    if (p.perm != null && group.equals(p.perm.info.group)) {
3645                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3646                    }
3647                }
3648            }
3649            return new ParceledListSlice<>(out);
3650        }
3651    }
3652
3653    @Override
3654    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3655        // reader
3656        synchronized (mPackages) {
3657            return PackageParser.generatePermissionGroupInfo(
3658                    mPermissionGroups.get(name), flags);
3659        }
3660    }
3661
3662    @Override
3663    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3664        // reader
3665        synchronized (mPackages) {
3666            final int N = mPermissionGroups.size();
3667            ArrayList<PermissionGroupInfo> out
3668                    = new ArrayList<PermissionGroupInfo>(N);
3669            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3670                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3671            }
3672            return new ParceledListSlice<>(out);
3673        }
3674    }
3675
3676    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3677            int uid, int userId) {
3678        if (!sUserManager.exists(userId)) return null;
3679        PackageSetting ps = mSettings.mPackages.get(packageName);
3680        if (ps != null) {
3681            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3682                return null;
3683            }
3684            if (ps.pkg == null) {
3685                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3686                if (pInfo != null) {
3687                    return pInfo.applicationInfo;
3688                }
3689                return null;
3690            }
3691            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3692                    ps.readUserState(userId), userId);
3693            if (ai != null) {
3694                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3695            }
3696            return ai;
3697        }
3698        return null;
3699    }
3700
3701    @Override
3702    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3703        if (!sUserManager.exists(userId)) return null;
3704        flags = updateFlagsForApplication(flags, userId, packageName);
3705        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3706                false /* requireFullPermission */, false /* checkShell */, "get application info");
3707
3708        // writer
3709        synchronized (mPackages) {
3710            // Normalize package name to handle renamed packages and static libs
3711            packageName = resolveInternalPackageNameLPr(packageName,
3712                    PackageManager.VERSION_CODE_HIGHEST);
3713
3714            PackageParser.Package p = mPackages.get(packageName);
3715            if (DEBUG_PACKAGE_INFO) Log.v(
3716                    TAG, "getApplicationInfo " + packageName
3717                    + ": " + p);
3718            if (p != null) {
3719                PackageSetting ps = mSettings.mPackages.get(packageName);
3720                if (ps == null) return null;
3721                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3722                    return null;
3723                }
3724                // Note: isEnabledLP() does not apply here - always return info
3725                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3726                        p, flags, ps.readUserState(userId), userId);
3727                if (ai != null) {
3728                    ai.packageName = resolveExternalPackageNameLPr(p);
3729                }
3730                return ai;
3731            }
3732            if ("android".equals(packageName)||"system".equals(packageName)) {
3733                return mAndroidApplication;
3734            }
3735            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3736                // Already generates the external package name
3737                return generateApplicationInfoFromSettingsLPw(packageName,
3738                        Binder.getCallingUid(), flags, userId);
3739            }
3740        }
3741        return null;
3742    }
3743
3744    private String normalizePackageNameLPr(String packageName) {
3745        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3746        return normalizedPackageName != null ? normalizedPackageName : packageName;
3747    }
3748
3749    @Override
3750    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3751            final IPackageDataObserver observer) {
3752        mContext.enforceCallingOrSelfPermission(
3753                android.Manifest.permission.CLEAR_APP_CACHE, null);
3754        // Queue up an async operation since clearing cache may take a little while.
3755        mHandler.post(new Runnable() {
3756            public void run() {
3757                mHandler.removeCallbacks(this);
3758                boolean success = true;
3759                synchronized (mInstallLock) {
3760                    try {
3761                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3762                    } catch (InstallerException e) {
3763                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3764                        success = false;
3765                    }
3766                }
3767                if (observer != null) {
3768                    try {
3769                        observer.onRemoveCompleted(null, success);
3770                    } catch (RemoteException e) {
3771                        Slog.w(TAG, "RemoveException when invoking call back");
3772                    }
3773                }
3774            }
3775        });
3776    }
3777
3778    @Override
3779    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3780            final IntentSender pi) {
3781        mContext.enforceCallingOrSelfPermission(
3782                android.Manifest.permission.CLEAR_APP_CACHE, null);
3783        // Queue up an async operation since clearing cache may take a little while.
3784        mHandler.post(new Runnable() {
3785            public void run() {
3786                mHandler.removeCallbacks(this);
3787                boolean success = true;
3788                synchronized (mInstallLock) {
3789                    try {
3790                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3791                    } catch (InstallerException e) {
3792                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3793                        success = false;
3794                    }
3795                }
3796                if(pi != null) {
3797                    try {
3798                        // Callback via pending intent
3799                        int code = success ? 1 : 0;
3800                        pi.sendIntent(null, code, null,
3801                                null, null);
3802                    } catch (SendIntentException e1) {
3803                        Slog.i(TAG, "Failed to send pending intent");
3804                    }
3805                }
3806            }
3807        });
3808    }
3809
3810    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3811        synchronized (mInstallLock) {
3812            try {
3813                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3814            } catch (InstallerException e) {
3815                throw new IOException("Failed to free enough space", e);
3816            }
3817        }
3818    }
3819
3820    /**
3821     * Update given flags based on encryption status of current user.
3822     */
3823    private int updateFlags(int flags, int userId) {
3824        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3825                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3826            // Caller expressed an explicit opinion about what encryption
3827            // aware/unaware components they want to see, so fall through and
3828            // give them what they want
3829        } else {
3830            // Caller expressed no opinion, so match based on user state
3831            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3832                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3833            } else {
3834                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3835            }
3836        }
3837        return flags;
3838    }
3839
3840    private UserManagerInternal getUserManagerInternal() {
3841        if (mUserManagerInternal == null) {
3842            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3843        }
3844        return mUserManagerInternal;
3845    }
3846
3847    private DeviceIdleController.LocalService getDeviceIdleController() {
3848        if (mDeviceIdleController == null) {
3849            mDeviceIdleController =
3850                    LocalServices.getService(DeviceIdleController.LocalService.class);
3851        }
3852        return mDeviceIdleController;
3853    }
3854
3855    /**
3856     * Update given flags when being used to request {@link PackageInfo}.
3857     */
3858    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3859        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3860        boolean triaged = true;
3861        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3862                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3863            // Caller is asking for component details, so they'd better be
3864            // asking for specific encryption matching behavior, or be triaged
3865            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3866                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3867                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3868                triaged = false;
3869            }
3870        }
3871        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3872                | PackageManager.MATCH_SYSTEM_ONLY
3873                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3874            triaged = false;
3875        }
3876        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3877            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3878                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3879                    + Debug.getCallers(5));
3880        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3881                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3882            // If the caller wants all packages and has a restricted profile associated with it,
3883            // then match all users. This is to make sure that launchers that need to access work
3884            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3885            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3886            flags |= PackageManager.MATCH_ANY_USER;
3887        }
3888        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3889            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3890                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3891        }
3892        return updateFlags(flags, userId);
3893    }
3894
3895    /**
3896     * Update given flags when being used to request {@link ApplicationInfo}.
3897     */
3898    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3899        return updateFlagsForPackage(flags, userId, cookie);
3900    }
3901
3902    /**
3903     * Update given flags when being used to request {@link ComponentInfo}.
3904     */
3905    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3906        if (cookie instanceof Intent) {
3907            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3908                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3909            }
3910        }
3911
3912        boolean triaged = true;
3913        // Caller is asking for component details, so they'd better be
3914        // asking for specific encryption matching behavior, or be triaged
3915        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3916                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3917                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3918            triaged = false;
3919        }
3920        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3921            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3922                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3923        }
3924
3925        return updateFlags(flags, userId);
3926    }
3927
3928    /**
3929     * Update given intent when being used to request {@link ResolveInfo}.
3930     */
3931    private Intent updateIntentForResolve(Intent intent) {
3932        if (intent.getSelector() != null) {
3933            intent = intent.getSelector();
3934        }
3935        if (DEBUG_PREFERRED) {
3936            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3937        }
3938        return intent;
3939    }
3940
3941    /**
3942     * Update given flags when being used to request {@link ResolveInfo}.
3943     */
3944    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3945        // Safe mode means we shouldn't match any third-party components
3946        if (mSafeMode) {
3947            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3948        }
3949        final int callingUid = Binder.getCallingUid();
3950        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3951            // The system sees all components
3952            flags |= PackageManager.MATCH_EPHEMERAL;
3953        } else if (getEphemeralPackageName(callingUid) != null) {
3954            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3955            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3956            flags |= PackageManager.MATCH_EPHEMERAL;
3957        } else {
3958            // Otherwise, prevent leaking ephemeral components
3959            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3960            flags &= ~PackageManager.MATCH_EPHEMERAL;
3961        }
3962        return updateFlagsForComponent(flags, userId, cookie);
3963    }
3964
3965    @Override
3966    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3967        if (!sUserManager.exists(userId)) return null;
3968        flags = updateFlagsForComponent(flags, userId, component);
3969        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3970                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3971        synchronized (mPackages) {
3972            PackageParser.Activity a = mActivities.mActivities.get(component);
3973
3974            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3975            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3976                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3977                if (ps == null) return null;
3978                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3979                        userId);
3980            }
3981            if (mResolveComponentName.equals(component)) {
3982                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3983                        new PackageUserState(), userId);
3984            }
3985        }
3986        return null;
3987    }
3988
3989    @Override
3990    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3991            String resolvedType) {
3992        synchronized (mPackages) {
3993            if (component.equals(mResolveComponentName)) {
3994                // The resolver supports EVERYTHING!
3995                return true;
3996            }
3997            PackageParser.Activity a = mActivities.mActivities.get(component);
3998            if (a == null) {
3999                return false;
4000            }
4001            for (int i=0; i<a.intents.size(); i++) {
4002                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4003                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4004                    return true;
4005                }
4006            }
4007            return false;
4008        }
4009    }
4010
4011    @Override
4012    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4013        if (!sUserManager.exists(userId)) return null;
4014        flags = updateFlagsForComponent(flags, userId, component);
4015        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4016                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4017        synchronized (mPackages) {
4018            PackageParser.Activity a = mReceivers.mActivities.get(component);
4019            if (DEBUG_PACKAGE_INFO) Log.v(
4020                TAG, "getReceiverInfo " + component + ": " + a);
4021            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4022                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4023                if (ps == null) return null;
4024                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4025                        userId);
4026            }
4027        }
4028        return null;
4029    }
4030
4031    @Override
4032    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4033        if (!sUserManager.exists(userId)) return null;
4034        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4035
4036        flags = updateFlagsForPackage(flags, userId, null);
4037
4038        final boolean canSeeStaticLibraries =
4039                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4040                        == PERMISSION_GRANTED
4041                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4042                        == PERMISSION_GRANTED
4043                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4044                        == PERMISSION_GRANTED
4045                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4046                        == PERMISSION_GRANTED;
4047
4048        synchronized (mPackages) {
4049            List<SharedLibraryInfo> result = null;
4050
4051            final int libCount = mSharedLibraries.size();
4052            for (int i = 0; i < libCount; i++) {
4053                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4054                if (versionedLib == null) {
4055                    continue;
4056                }
4057
4058                final int versionCount = versionedLib.size();
4059                for (int j = 0; j < versionCount; j++) {
4060                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4061                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4062                        break;
4063                    }
4064                    final long identity = Binder.clearCallingIdentity();
4065                    try {
4066                        // TODO: We will change version code to long, so in the new API it is long
4067                        PackageInfo packageInfo = getPackageInfoVersioned(
4068                                libInfo.getDeclaringPackage(), flags, userId);
4069                        if (packageInfo == null) {
4070                            continue;
4071                        }
4072                    } finally {
4073                        Binder.restoreCallingIdentity(identity);
4074                    }
4075
4076                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4077                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4078                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4079
4080                    if (result == null) {
4081                        result = new ArrayList<>();
4082                    }
4083                    result.add(resLibInfo);
4084                }
4085            }
4086
4087            return result != null ? new ParceledListSlice<>(result) : null;
4088        }
4089    }
4090
4091    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4092            SharedLibraryInfo libInfo, int flags, int userId) {
4093        List<VersionedPackage> versionedPackages = null;
4094        final int packageCount = mSettings.mPackages.size();
4095        for (int i = 0; i < packageCount; i++) {
4096            PackageSetting ps = mSettings.mPackages.valueAt(i);
4097
4098            if (ps == null) {
4099                continue;
4100            }
4101
4102            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4103                continue;
4104            }
4105
4106            final String libName = libInfo.getName();
4107            if (libInfo.isStatic()) {
4108                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4109                if (libIdx < 0) {
4110                    continue;
4111                }
4112                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4113                    continue;
4114                }
4115                if (versionedPackages == null) {
4116                    versionedPackages = new ArrayList<>();
4117                }
4118                // If the dependent is a static shared lib, use the public package name
4119                String dependentPackageName = ps.name;
4120                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4121                    dependentPackageName = ps.pkg.manifestPackageName;
4122                }
4123                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4124            } else if (ps.pkg != null) {
4125                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4126                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4127                    if (versionedPackages == null) {
4128                        versionedPackages = new ArrayList<>();
4129                    }
4130                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4131                }
4132            }
4133        }
4134
4135        return versionedPackages;
4136    }
4137
4138    @Override
4139    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4140        if (!sUserManager.exists(userId)) return null;
4141        flags = updateFlagsForComponent(flags, userId, component);
4142        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4143                false /* requireFullPermission */, false /* checkShell */, "get service info");
4144        synchronized (mPackages) {
4145            PackageParser.Service s = mServices.mServices.get(component);
4146            if (DEBUG_PACKAGE_INFO) Log.v(
4147                TAG, "getServiceInfo " + component + ": " + s);
4148            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4149                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4150                if (ps == null) return null;
4151                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4152                        userId);
4153            }
4154        }
4155        return null;
4156    }
4157
4158    @Override
4159    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4160        if (!sUserManager.exists(userId)) return null;
4161        flags = updateFlagsForComponent(flags, userId, component);
4162        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4163                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4164        synchronized (mPackages) {
4165            PackageParser.Provider p = mProviders.mProviders.get(component);
4166            if (DEBUG_PACKAGE_INFO) Log.v(
4167                TAG, "getProviderInfo " + component + ": " + p);
4168            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4169                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4170                if (ps == null) return null;
4171                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4172                        userId);
4173            }
4174        }
4175        return null;
4176    }
4177
4178    @Override
4179    public String[] getSystemSharedLibraryNames() {
4180        synchronized (mPackages) {
4181            Set<String> libs = null;
4182            final int libCount = mSharedLibraries.size();
4183            for (int i = 0; i < libCount; i++) {
4184                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4185                if (versionedLib == null) {
4186                    continue;
4187                }
4188                final int versionCount = versionedLib.size();
4189                for (int j = 0; j < versionCount; j++) {
4190                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4191                    if (!libEntry.info.isStatic()) {
4192                        if (libs == null) {
4193                            libs = new ArraySet<>();
4194                        }
4195                        libs.add(libEntry.info.getName());
4196                        break;
4197                    }
4198                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4199                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4200                            UserHandle.getUserId(Binder.getCallingUid()))) {
4201                        if (libs == null) {
4202                            libs = new ArraySet<>();
4203                        }
4204                        libs.add(libEntry.info.getName());
4205                        break;
4206                    }
4207                }
4208            }
4209
4210            if (libs != null) {
4211                String[] libsArray = new String[libs.size()];
4212                libs.toArray(libsArray);
4213                return libsArray;
4214            }
4215
4216            return null;
4217        }
4218    }
4219
4220    @Override
4221    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4222        synchronized (mPackages) {
4223            return mServicesSystemSharedLibraryPackageName;
4224        }
4225    }
4226
4227    @Override
4228    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4229        synchronized (mPackages) {
4230            return mSharedSystemSharedLibraryPackageName;
4231        }
4232    }
4233
4234    @Override
4235    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4236        ArrayList<FeatureInfo> res;
4237        synchronized (mAvailableFeatures) {
4238            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4239            res.addAll(mAvailableFeatures.values());
4240        }
4241        final FeatureInfo fi = new FeatureInfo();
4242        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4243                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4244        res.add(fi);
4245
4246        return new ParceledListSlice<>(res);
4247    }
4248
4249    @Override
4250    public boolean hasSystemFeature(String name, int version) {
4251        synchronized (mAvailableFeatures) {
4252            final FeatureInfo feat = mAvailableFeatures.get(name);
4253            if (feat == null) {
4254                return false;
4255            } else {
4256                return feat.version >= version;
4257            }
4258        }
4259    }
4260
4261    @Override
4262    public int checkPermission(String permName, String pkgName, int userId) {
4263        if (!sUserManager.exists(userId)) {
4264            return PackageManager.PERMISSION_DENIED;
4265        }
4266
4267        synchronized (mPackages) {
4268            final PackageParser.Package p = mPackages.get(pkgName);
4269            if (p != null && p.mExtras != null) {
4270                final PackageSetting ps = (PackageSetting) p.mExtras;
4271                final PermissionsState permissionsState = ps.getPermissionsState();
4272                if (permissionsState.hasPermission(permName, userId)) {
4273                    return PackageManager.PERMISSION_GRANTED;
4274                }
4275                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4276                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4277                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4278                    return PackageManager.PERMISSION_GRANTED;
4279                }
4280            }
4281        }
4282
4283        return PackageManager.PERMISSION_DENIED;
4284    }
4285
4286    @Override
4287    public int checkUidPermission(String permName, int uid) {
4288        final int userId = UserHandle.getUserId(uid);
4289
4290        if (!sUserManager.exists(userId)) {
4291            return PackageManager.PERMISSION_DENIED;
4292        }
4293
4294        synchronized (mPackages) {
4295            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4296            if (obj != null) {
4297                final SettingBase ps = (SettingBase) obj;
4298                final PermissionsState permissionsState = ps.getPermissionsState();
4299                if (permissionsState.hasPermission(permName, userId)) {
4300                    return PackageManager.PERMISSION_GRANTED;
4301                }
4302                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4303                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4304                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4305                    return PackageManager.PERMISSION_GRANTED;
4306                }
4307            } else {
4308                ArraySet<String> perms = mSystemPermissions.get(uid);
4309                if (perms != null) {
4310                    if (perms.contains(permName)) {
4311                        return PackageManager.PERMISSION_GRANTED;
4312                    }
4313                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4314                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4315                        return PackageManager.PERMISSION_GRANTED;
4316                    }
4317                }
4318            }
4319        }
4320
4321        return PackageManager.PERMISSION_DENIED;
4322    }
4323
4324    @Override
4325    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4326        if (UserHandle.getCallingUserId() != userId) {
4327            mContext.enforceCallingPermission(
4328                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4329                    "isPermissionRevokedByPolicy for user " + userId);
4330        }
4331
4332        if (checkPermission(permission, packageName, userId)
4333                == PackageManager.PERMISSION_GRANTED) {
4334            return false;
4335        }
4336
4337        final long identity = Binder.clearCallingIdentity();
4338        try {
4339            final int flags = getPermissionFlags(permission, packageName, userId);
4340            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4341        } finally {
4342            Binder.restoreCallingIdentity(identity);
4343        }
4344    }
4345
4346    @Override
4347    public String getPermissionControllerPackageName() {
4348        synchronized (mPackages) {
4349            return mRequiredInstallerPackage;
4350        }
4351    }
4352
4353    /**
4354     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4355     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4356     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4357     * @param message the message to log on security exception
4358     */
4359    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4360            boolean checkShell, String message) {
4361        if (userId < 0) {
4362            throw new IllegalArgumentException("Invalid userId " + userId);
4363        }
4364        if (checkShell) {
4365            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4366        }
4367        if (userId == UserHandle.getUserId(callingUid)) return;
4368        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4369            if (requireFullPermission) {
4370                mContext.enforceCallingOrSelfPermission(
4371                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4372            } else {
4373                try {
4374                    mContext.enforceCallingOrSelfPermission(
4375                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4376                } catch (SecurityException se) {
4377                    mContext.enforceCallingOrSelfPermission(
4378                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4379                }
4380            }
4381        }
4382    }
4383
4384    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4385        if (callingUid == Process.SHELL_UID) {
4386            if (userHandle >= 0
4387                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4388                throw new SecurityException("Shell does not have permission to access user "
4389                        + userHandle);
4390            } else if (userHandle < 0) {
4391                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4392                        + Debug.getCallers(3));
4393            }
4394        }
4395    }
4396
4397    private BasePermission findPermissionTreeLP(String permName) {
4398        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4399            if (permName.startsWith(bp.name) &&
4400                    permName.length() > bp.name.length() &&
4401                    permName.charAt(bp.name.length()) == '.') {
4402                return bp;
4403            }
4404        }
4405        return null;
4406    }
4407
4408    private BasePermission checkPermissionTreeLP(String permName) {
4409        if (permName != null) {
4410            BasePermission bp = findPermissionTreeLP(permName);
4411            if (bp != null) {
4412                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4413                    return bp;
4414                }
4415                throw new SecurityException("Calling uid "
4416                        + Binder.getCallingUid()
4417                        + " is not allowed to add to permission tree "
4418                        + bp.name + " owned by uid " + bp.uid);
4419            }
4420        }
4421        throw new SecurityException("No permission tree found for " + permName);
4422    }
4423
4424    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4425        if (s1 == null) {
4426            return s2 == null;
4427        }
4428        if (s2 == null) {
4429            return false;
4430        }
4431        if (s1.getClass() != s2.getClass()) {
4432            return false;
4433        }
4434        return s1.equals(s2);
4435    }
4436
4437    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4438        if (pi1.icon != pi2.icon) return false;
4439        if (pi1.logo != pi2.logo) return false;
4440        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4441        if (!compareStrings(pi1.name, pi2.name)) return false;
4442        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4443        // We'll take care of setting this one.
4444        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4445        // These are not currently stored in settings.
4446        //if (!compareStrings(pi1.group, pi2.group)) return false;
4447        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4448        //if (pi1.labelRes != pi2.labelRes) return false;
4449        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4450        return true;
4451    }
4452
4453    int permissionInfoFootprint(PermissionInfo info) {
4454        int size = info.name.length();
4455        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4456        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4457        return size;
4458    }
4459
4460    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4461        int size = 0;
4462        for (BasePermission perm : mSettings.mPermissions.values()) {
4463            if (perm.uid == tree.uid) {
4464                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4465            }
4466        }
4467        return size;
4468    }
4469
4470    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4471        // We calculate the max size of permissions defined by this uid and throw
4472        // if that plus the size of 'info' would exceed our stated maximum.
4473        if (tree.uid != Process.SYSTEM_UID) {
4474            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4475            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4476                throw new SecurityException("Permission tree size cap exceeded");
4477            }
4478        }
4479    }
4480
4481    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4482        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4483            throw new SecurityException("Label must be specified in permission");
4484        }
4485        BasePermission tree = checkPermissionTreeLP(info.name);
4486        BasePermission bp = mSettings.mPermissions.get(info.name);
4487        boolean added = bp == null;
4488        boolean changed = true;
4489        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4490        if (added) {
4491            enforcePermissionCapLocked(info, tree);
4492            bp = new BasePermission(info.name, tree.sourcePackage,
4493                    BasePermission.TYPE_DYNAMIC);
4494        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4495            throw new SecurityException(
4496                    "Not allowed to modify non-dynamic permission "
4497                    + info.name);
4498        } else {
4499            if (bp.protectionLevel == fixedLevel
4500                    && bp.perm.owner.equals(tree.perm.owner)
4501                    && bp.uid == tree.uid
4502                    && comparePermissionInfos(bp.perm.info, info)) {
4503                changed = false;
4504            }
4505        }
4506        bp.protectionLevel = fixedLevel;
4507        info = new PermissionInfo(info);
4508        info.protectionLevel = fixedLevel;
4509        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4510        bp.perm.info.packageName = tree.perm.info.packageName;
4511        bp.uid = tree.uid;
4512        if (added) {
4513            mSettings.mPermissions.put(info.name, bp);
4514        }
4515        if (changed) {
4516            if (!async) {
4517                mSettings.writeLPr();
4518            } else {
4519                scheduleWriteSettingsLocked();
4520            }
4521        }
4522        return added;
4523    }
4524
4525    @Override
4526    public boolean addPermission(PermissionInfo info) {
4527        synchronized (mPackages) {
4528            return addPermissionLocked(info, false);
4529        }
4530    }
4531
4532    @Override
4533    public boolean addPermissionAsync(PermissionInfo info) {
4534        synchronized (mPackages) {
4535            return addPermissionLocked(info, true);
4536        }
4537    }
4538
4539    @Override
4540    public void removePermission(String name) {
4541        synchronized (mPackages) {
4542            checkPermissionTreeLP(name);
4543            BasePermission bp = mSettings.mPermissions.get(name);
4544            if (bp != null) {
4545                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4546                    throw new SecurityException(
4547                            "Not allowed to modify non-dynamic permission "
4548                            + name);
4549                }
4550                mSettings.mPermissions.remove(name);
4551                mSettings.writeLPr();
4552            }
4553        }
4554    }
4555
4556    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4557            BasePermission bp) {
4558        int index = pkg.requestedPermissions.indexOf(bp.name);
4559        if (index == -1) {
4560            throw new SecurityException("Package " + pkg.packageName
4561                    + " has not requested permission " + bp.name);
4562        }
4563        if (!bp.isRuntime() && !bp.isDevelopment()) {
4564            throw new SecurityException("Permission " + bp.name
4565                    + " is not a changeable permission type");
4566        }
4567    }
4568
4569    @Override
4570    public void grantRuntimePermission(String packageName, String name, final int userId) {
4571        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4572    }
4573
4574    private void grantRuntimePermission(String packageName, String name, final int userId,
4575            boolean overridePolicy) {
4576        if (!sUserManager.exists(userId)) {
4577            Log.e(TAG, "No such user:" + userId);
4578            return;
4579        }
4580
4581        mContext.enforceCallingOrSelfPermission(
4582                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4583                "grantRuntimePermission");
4584
4585        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4586                true /* requireFullPermission */, true /* checkShell */,
4587                "grantRuntimePermission");
4588
4589        final int uid;
4590        final SettingBase sb;
4591
4592        synchronized (mPackages) {
4593            final PackageParser.Package pkg = mPackages.get(packageName);
4594            if (pkg == null) {
4595                throw new IllegalArgumentException("Unknown package: " + packageName);
4596            }
4597
4598            final BasePermission bp = mSettings.mPermissions.get(name);
4599            if (bp == null) {
4600                throw new IllegalArgumentException("Unknown permission: " + name);
4601            }
4602
4603            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4604
4605            // If a permission review is required for legacy apps we represent
4606            // their permissions as always granted runtime ones since we need
4607            // to keep the review required permission flag per user while an
4608            // install permission's state is shared across all users.
4609            if (mPermissionReviewRequired
4610                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4611                    && bp.isRuntime()) {
4612                return;
4613            }
4614
4615            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4616            sb = (SettingBase) pkg.mExtras;
4617            if (sb == null) {
4618                throw new IllegalArgumentException("Unknown package: " + packageName);
4619            }
4620
4621            final PermissionsState permissionsState = sb.getPermissionsState();
4622
4623            final int flags = permissionsState.getPermissionFlags(name, userId);
4624            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4625                throw new SecurityException("Cannot grant system fixed permission "
4626                        + name + " for package " + packageName);
4627            }
4628            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4629                throw new SecurityException("Cannot grant policy fixed permission "
4630                        + name + " for package " + packageName);
4631            }
4632
4633            if (bp.isDevelopment()) {
4634                // Development permissions must be handled specially, since they are not
4635                // normal runtime permissions.  For now they apply to all users.
4636                if (permissionsState.grantInstallPermission(bp) !=
4637                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4638                    scheduleWriteSettingsLocked();
4639                }
4640                return;
4641            }
4642
4643            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
4644                throw new SecurityException("Cannot grant non-ephemeral permission"
4645                        + name + " for package " + packageName);
4646            }
4647
4648            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4649                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4650                return;
4651            }
4652
4653            final int result = permissionsState.grantRuntimePermission(bp, userId);
4654            switch (result) {
4655                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4656                    return;
4657                }
4658
4659                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4660                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4661                    mHandler.post(new Runnable() {
4662                        @Override
4663                        public void run() {
4664                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4665                        }
4666                    });
4667                }
4668                break;
4669            }
4670
4671            if (bp.isRuntime()) {
4672                logPermissionGranted(mContext, name, packageName);
4673            }
4674
4675            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4676
4677            // Not critical if that is lost - app has to request again.
4678            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4679        }
4680
4681        // Only need to do this if user is initialized. Otherwise it's a new user
4682        // and there are no processes running as the user yet and there's no need
4683        // to make an expensive call to remount processes for the changed permissions.
4684        if (READ_EXTERNAL_STORAGE.equals(name)
4685                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4686            final long token = Binder.clearCallingIdentity();
4687            try {
4688                if (sUserManager.isInitialized(userId)) {
4689                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4690                            StorageManagerInternal.class);
4691                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4692                }
4693            } finally {
4694                Binder.restoreCallingIdentity(token);
4695            }
4696        }
4697    }
4698
4699    @Override
4700    public void revokeRuntimePermission(String packageName, String name, int userId) {
4701        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4702    }
4703
4704    private void revokeRuntimePermission(String packageName, String name, int userId,
4705            boolean overridePolicy) {
4706        if (!sUserManager.exists(userId)) {
4707            Log.e(TAG, "No such user:" + userId);
4708            return;
4709        }
4710
4711        mContext.enforceCallingOrSelfPermission(
4712                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4713                "revokeRuntimePermission");
4714
4715        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4716                true /* requireFullPermission */, true /* checkShell */,
4717                "revokeRuntimePermission");
4718
4719        final int appId;
4720
4721        synchronized (mPackages) {
4722            final PackageParser.Package pkg = mPackages.get(packageName);
4723            if (pkg == null) {
4724                throw new IllegalArgumentException("Unknown package: " + packageName);
4725            }
4726
4727            final BasePermission bp = mSettings.mPermissions.get(name);
4728            if (bp == null) {
4729                throw new IllegalArgumentException("Unknown permission: " + name);
4730            }
4731
4732            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4733
4734            // If a permission review is required for legacy apps we represent
4735            // their permissions as always granted runtime ones since we need
4736            // to keep the review required permission flag per user while an
4737            // install permission's state is shared across all users.
4738            if (mPermissionReviewRequired
4739                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4740                    && bp.isRuntime()) {
4741                return;
4742            }
4743
4744            SettingBase sb = (SettingBase) pkg.mExtras;
4745            if (sb == null) {
4746                throw new IllegalArgumentException("Unknown package: " + packageName);
4747            }
4748
4749            final PermissionsState permissionsState = sb.getPermissionsState();
4750
4751            final int flags = permissionsState.getPermissionFlags(name, userId);
4752            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4753                throw new SecurityException("Cannot revoke system fixed permission "
4754                        + name + " for package " + packageName);
4755            }
4756            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4757                throw new SecurityException("Cannot revoke policy fixed permission "
4758                        + name + " for package " + packageName);
4759            }
4760
4761            if (bp.isDevelopment()) {
4762                // Development permissions must be handled specially, since they are not
4763                // normal runtime permissions.  For now they apply to all users.
4764                if (permissionsState.revokeInstallPermission(bp) !=
4765                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4766                    scheduleWriteSettingsLocked();
4767                }
4768                return;
4769            }
4770
4771            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4772                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4773                return;
4774            }
4775
4776            if (bp.isRuntime()) {
4777                logPermissionRevoked(mContext, name, packageName);
4778            }
4779
4780            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4781
4782            // Critical, after this call app should never have the permission.
4783            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4784
4785            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4786        }
4787
4788        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4789    }
4790
4791    /**
4792     * Get the first event id for the permission.
4793     *
4794     * <p>There are four events for each permission: <ul>
4795     *     <li>Request permission: first id + 0</li>
4796     *     <li>Grant permission: first id + 1</li>
4797     *     <li>Request for permission denied: first id + 2</li>
4798     *     <li>Revoke permission: first id + 3</li>
4799     * </ul></p>
4800     *
4801     * @param name name of the permission
4802     *
4803     * @return The first event id for the permission
4804     */
4805    private static int getBaseEventId(@NonNull String name) {
4806        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4807
4808        if (eventIdIndex == -1) {
4809            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4810                    || "user".equals(Build.TYPE)) {
4811                Log.i(TAG, "Unknown permission " + name);
4812
4813                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4814            } else {
4815                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4816                //
4817                // Also update
4818                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4819                // - metrics_constants.proto
4820                throw new IllegalStateException("Unknown permission " + name);
4821            }
4822        }
4823
4824        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4825    }
4826
4827    /**
4828     * Log that a permission was revoked.
4829     *
4830     * @param context Context of the caller
4831     * @param name name of the permission
4832     * @param packageName package permission if for
4833     */
4834    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4835            @NonNull String packageName) {
4836        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4837    }
4838
4839    /**
4840     * Log that a permission request was granted.
4841     *
4842     * @param context Context of the caller
4843     * @param name name of the permission
4844     * @param packageName package permission if for
4845     */
4846    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4847            @NonNull String packageName) {
4848        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4849    }
4850
4851    @Override
4852    public void resetRuntimePermissions() {
4853        mContext.enforceCallingOrSelfPermission(
4854                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4855                "revokeRuntimePermission");
4856
4857        int callingUid = Binder.getCallingUid();
4858        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4859            mContext.enforceCallingOrSelfPermission(
4860                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4861                    "resetRuntimePermissions");
4862        }
4863
4864        synchronized (mPackages) {
4865            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4866            for (int userId : UserManagerService.getInstance().getUserIds()) {
4867                final int packageCount = mPackages.size();
4868                for (int i = 0; i < packageCount; i++) {
4869                    PackageParser.Package pkg = mPackages.valueAt(i);
4870                    if (!(pkg.mExtras instanceof PackageSetting)) {
4871                        continue;
4872                    }
4873                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4874                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4875                }
4876            }
4877        }
4878    }
4879
4880    @Override
4881    public int getPermissionFlags(String name, String packageName, int userId) {
4882        if (!sUserManager.exists(userId)) {
4883            return 0;
4884        }
4885
4886        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4887
4888        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4889                true /* requireFullPermission */, false /* checkShell */,
4890                "getPermissionFlags");
4891
4892        synchronized (mPackages) {
4893            final PackageParser.Package pkg = mPackages.get(packageName);
4894            if (pkg == null) {
4895                return 0;
4896            }
4897
4898            final BasePermission bp = mSettings.mPermissions.get(name);
4899            if (bp == null) {
4900                return 0;
4901            }
4902
4903            SettingBase sb = (SettingBase) pkg.mExtras;
4904            if (sb == null) {
4905                return 0;
4906            }
4907
4908            PermissionsState permissionsState = sb.getPermissionsState();
4909            return permissionsState.getPermissionFlags(name, userId);
4910        }
4911    }
4912
4913    @Override
4914    public void updatePermissionFlags(String name, String packageName, int flagMask,
4915            int flagValues, int userId) {
4916        if (!sUserManager.exists(userId)) {
4917            return;
4918        }
4919
4920        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4921
4922        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4923                true /* requireFullPermission */, true /* checkShell */,
4924                "updatePermissionFlags");
4925
4926        // Only the system can change these flags and nothing else.
4927        if (getCallingUid() != Process.SYSTEM_UID) {
4928            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4929            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4930            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4931            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4932            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4933        }
4934
4935        synchronized (mPackages) {
4936            final PackageParser.Package pkg = mPackages.get(packageName);
4937            if (pkg == null) {
4938                throw new IllegalArgumentException("Unknown package: " + packageName);
4939            }
4940
4941            final BasePermission bp = mSettings.mPermissions.get(name);
4942            if (bp == null) {
4943                throw new IllegalArgumentException("Unknown permission: " + name);
4944            }
4945
4946            SettingBase sb = (SettingBase) pkg.mExtras;
4947            if (sb == null) {
4948                throw new IllegalArgumentException("Unknown package: " + packageName);
4949            }
4950
4951            PermissionsState permissionsState = sb.getPermissionsState();
4952
4953            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4954
4955            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4956                // Install and runtime permissions are stored in different places,
4957                // so figure out what permission changed and persist the change.
4958                if (permissionsState.getInstallPermissionState(name) != null) {
4959                    scheduleWriteSettingsLocked();
4960                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4961                        || hadState) {
4962                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4963                }
4964            }
4965        }
4966    }
4967
4968    /**
4969     * Update the permission flags for all packages and runtime permissions of a user in order
4970     * to allow device or profile owner to remove POLICY_FIXED.
4971     */
4972    @Override
4973    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4974        if (!sUserManager.exists(userId)) {
4975            return;
4976        }
4977
4978        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4979
4980        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4981                true /* requireFullPermission */, true /* checkShell */,
4982                "updatePermissionFlagsForAllApps");
4983
4984        // Only the system can change system fixed flags.
4985        if (getCallingUid() != Process.SYSTEM_UID) {
4986            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4987            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4988        }
4989
4990        synchronized (mPackages) {
4991            boolean changed = false;
4992            final int packageCount = mPackages.size();
4993            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4994                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4995                SettingBase sb = (SettingBase) pkg.mExtras;
4996                if (sb == null) {
4997                    continue;
4998                }
4999                PermissionsState permissionsState = sb.getPermissionsState();
5000                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5001                        userId, flagMask, flagValues);
5002            }
5003            if (changed) {
5004                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5005            }
5006        }
5007    }
5008
5009    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5010        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5011                != PackageManager.PERMISSION_GRANTED
5012            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5013                != PackageManager.PERMISSION_GRANTED) {
5014            throw new SecurityException(message + " requires "
5015                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5016                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5017        }
5018    }
5019
5020    @Override
5021    public boolean shouldShowRequestPermissionRationale(String permissionName,
5022            String packageName, int userId) {
5023        if (UserHandle.getCallingUserId() != userId) {
5024            mContext.enforceCallingPermission(
5025                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5026                    "canShowRequestPermissionRationale for user " + userId);
5027        }
5028
5029        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5030        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5031            return false;
5032        }
5033
5034        if (checkPermission(permissionName, packageName, userId)
5035                == PackageManager.PERMISSION_GRANTED) {
5036            return false;
5037        }
5038
5039        final int flags;
5040
5041        final long identity = Binder.clearCallingIdentity();
5042        try {
5043            flags = getPermissionFlags(permissionName,
5044                    packageName, userId);
5045        } finally {
5046            Binder.restoreCallingIdentity(identity);
5047        }
5048
5049        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5050                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5051                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5052
5053        if ((flags & fixedFlags) != 0) {
5054            return false;
5055        }
5056
5057        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5058    }
5059
5060    @Override
5061    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5062        mContext.enforceCallingOrSelfPermission(
5063                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5064                "addOnPermissionsChangeListener");
5065
5066        synchronized (mPackages) {
5067            mOnPermissionChangeListeners.addListenerLocked(listener);
5068        }
5069    }
5070
5071    @Override
5072    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5073        synchronized (mPackages) {
5074            mOnPermissionChangeListeners.removeListenerLocked(listener);
5075        }
5076    }
5077
5078    @Override
5079    public boolean isProtectedBroadcast(String actionName) {
5080        synchronized (mPackages) {
5081            if (mProtectedBroadcasts.contains(actionName)) {
5082                return true;
5083            } else if (actionName != null) {
5084                // TODO: remove these terrible hacks
5085                if (actionName.startsWith("android.net.netmon.lingerExpired")
5086                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5087                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5088                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5089                    return true;
5090                }
5091            }
5092        }
5093        return false;
5094    }
5095
5096    @Override
5097    public int checkSignatures(String pkg1, String pkg2) {
5098        synchronized (mPackages) {
5099            final PackageParser.Package p1 = mPackages.get(pkg1);
5100            final PackageParser.Package p2 = mPackages.get(pkg2);
5101            if (p1 == null || p1.mExtras == null
5102                    || p2 == null || p2.mExtras == null) {
5103                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5104            }
5105            return compareSignatures(p1.mSignatures, p2.mSignatures);
5106        }
5107    }
5108
5109    @Override
5110    public int checkUidSignatures(int uid1, int uid2) {
5111        // Map to base uids.
5112        uid1 = UserHandle.getAppId(uid1);
5113        uid2 = UserHandle.getAppId(uid2);
5114        // reader
5115        synchronized (mPackages) {
5116            Signature[] s1;
5117            Signature[] s2;
5118            Object obj = mSettings.getUserIdLPr(uid1);
5119            if (obj != null) {
5120                if (obj instanceof SharedUserSetting) {
5121                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5122                } else if (obj instanceof PackageSetting) {
5123                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5124                } else {
5125                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5126                }
5127            } else {
5128                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5129            }
5130            obj = mSettings.getUserIdLPr(uid2);
5131            if (obj != null) {
5132                if (obj instanceof SharedUserSetting) {
5133                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5134                } else if (obj instanceof PackageSetting) {
5135                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5136                } else {
5137                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5138                }
5139            } else {
5140                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5141            }
5142            return compareSignatures(s1, s2);
5143        }
5144    }
5145
5146    /**
5147     * This method should typically only be used when granting or revoking
5148     * permissions, since the app may immediately restart after this call.
5149     * <p>
5150     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5151     * guard your work against the app being relaunched.
5152     */
5153    private void killUid(int appId, int userId, String reason) {
5154        final long identity = Binder.clearCallingIdentity();
5155        try {
5156            IActivityManager am = ActivityManager.getService();
5157            if (am != null) {
5158                try {
5159                    am.killUid(appId, userId, reason);
5160                } catch (RemoteException e) {
5161                    /* ignore - same process */
5162                }
5163            }
5164        } finally {
5165            Binder.restoreCallingIdentity(identity);
5166        }
5167    }
5168
5169    /**
5170     * Compares two sets of signatures. Returns:
5171     * <br />
5172     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5173     * <br />
5174     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5175     * <br />
5176     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5177     * <br />
5178     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5179     * <br />
5180     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5181     */
5182    static int compareSignatures(Signature[] s1, Signature[] s2) {
5183        if (s1 == null) {
5184            return s2 == null
5185                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5186                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5187        }
5188
5189        if (s2 == null) {
5190            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5191        }
5192
5193        if (s1.length != s2.length) {
5194            return PackageManager.SIGNATURE_NO_MATCH;
5195        }
5196
5197        // Since both signature sets are of size 1, we can compare without HashSets.
5198        if (s1.length == 1) {
5199            return s1[0].equals(s2[0]) ?
5200                    PackageManager.SIGNATURE_MATCH :
5201                    PackageManager.SIGNATURE_NO_MATCH;
5202        }
5203
5204        ArraySet<Signature> set1 = new ArraySet<Signature>();
5205        for (Signature sig : s1) {
5206            set1.add(sig);
5207        }
5208        ArraySet<Signature> set2 = new ArraySet<Signature>();
5209        for (Signature sig : s2) {
5210            set2.add(sig);
5211        }
5212        // Make sure s2 contains all signatures in s1.
5213        if (set1.equals(set2)) {
5214            return PackageManager.SIGNATURE_MATCH;
5215        }
5216        return PackageManager.SIGNATURE_NO_MATCH;
5217    }
5218
5219    /**
5220     * If the database version for this type of package (internal storage or
5221     * external storage) is less than the version where package signatures
5222     * were updated, return true.
5223     */
5224    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5225        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5226        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5227    }
5228
5229    /**
5230     * Used for backward compatibility to make sure any packages with
5231     * certificate chains get upgraded to the new style. {@code existingSigs}
5232     * will be in the old format (since they were stored on disk from before the
5233     * system upgrade) and {@code scannedSigs} will be in the newer format.
5234     */
5235    private int compareSignaturesCompat(PackageSignatures existingSigs,
5236            PackageParser.Package scannedPkg) {
5237        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5238            return PackageManager.SIGNATURE_NO_MATCH;
5239        }
5240
5241        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5242        for (Signature sig : existingSigs.mSignatures) {
5243            existingSet.add(sig);
5244        }
5245        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5246        for (Signature sig : scannedPkg.mSignatures) {
5247            try {
5248                Signature[] chainSignatures = sig.getChainSignatures();
5249                for (Signature chainSig : chainSignatures) {
5250                    scannedCompatSet.add(chainSig);
5251                }
5252            } catch (CertificateEncodingException e) {
5253                scannedCompatSet.add(sig);
5254            }
5255        }
5256        /*
5257         * Make sure the expanded scanned set contains all signatures in the
5258         * existing one.
5259         */
5260        if (scannedCompatSet.equals(existingSet)) {
5261            // Migrate the old signatures to the new scheme.
5262            existingSigs.assignSignatures(scannedPkg.mSignatures);
5263            // The new KeySets will be re-added later in the scanning process.
5264            synchronized (mPackages) {
5265                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5266            }
5267            return PackageManager.SIGNATURE_MATCH;
5268        }
5269        return PackageManager.SIGNATURE_NO_MATCH;
5270    }
5271
5272    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5273        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5274        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5275    }
5276
5277    private int compareSignaturesRecover(PackageSignatures existingSigs,
5278            PackageParser.Package scannedPkg) {
5279        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5280            return PackageManager.SIGNATURE_NO_MATCH;
5281        }
5282
5283        String msg = null;
5284        try {
5285            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5286                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5287                        + scannedPkg.packageName);
5288                return PackageManager.SIGNATURE_MATCH;
5289            }
5290        } catch (CertificateException e) {
5291            msg = e.getMessage();
5292        }
5293
5294        logCriticalInfo(Log.INFO,
5295                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5296        return PackageManager.SIGNATURE_NO_MATCH;
5297    }
5298
5299    @Override
5300    public List<String> getAllPackages() {
5301        synchronized (mPackages) {
5302            return new ArrayList<String>(mPackages.keySet());
5303        }
5304    }
5305
5306    @Override
5307    public String[] getPackagesForUid(int uid) {
5308        final int userId = UserHandle.getUserId(uid);
5309        uid = UserHandle.getAppId(uid);
5310        // reader
5311        synchronized (mPackages) {
5312            Object obj = mSettings.getUserIdLPr(uid);
5313            if (obj instanceof SharedUserSetting) {
5314                final SharedUserSetting sus = (SharedUserSetting) obj;
5315                final int N = sus.packages.size();
5316                String[] res = new String[N];
5317                final Iterator<PackageSetting> it = sus.packages.iterator();
5318                int i = 0;
5319                while (it.hasNext()) {
5320                    PackageSetting ps = it.next();
5321                    if (ps.getInstalled(userId)) {
5322                        res[i++] = ps.name;
5323                    } else {
5324                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5325                    }
5326                }
5327                return res;
5328            } else if (obj instanceof PackageSetting) {
5329                final PackageSetting ps = (PackageSetting) obj;
5330                if (ps.getInstalled(userId)) {
5331                    return new String[]{ps.name};
5332                }
5333            }
5334        }
5335        return null;
5336    }
5337
5338    @Override
5339    public String getNameForUid(int uid) {
5340        // reader
5341        synchronized (mPackages) {
5342            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5343            if (obj instanceof SharedUserSetting) {
5344                final SharedUserSetting sus = (SharedUserSetting) obj;
5345                return sus.name + ":" + sus.userId;
5346            } else if (obj instanceof PackageSetting) {
5347                final PackageSetting ps = (PackageSetting) obj;
5348                return ps.name;
5349            }
5350        }
5351        return null;
5352    }
5353
5354    @Override
5355    public int getUidForSharedUser(String sharedUserName) {
5356        if(sharedUserName == null) {
5357            return -1;
5358        }
5359        // reader
5360        synchronized (mPackages) {
5361            SharedUserSetting suid;
5362            try {
5363                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5364                if (suid != null) {
5365                    return suid.userId;
5366                }
5367            } catch (PackageManagerException ignore) {
5368                // can't happen, but, still need to catch it
5369            }
5370            return -1;
5371        }
5372    }
5373
5374    @Override
5375    public int getFlagsForUid(int uid) {
5376        synchronized (mPackages) {
5377            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5378            if (obj instanceof SharedUserSetting) {
5379                final SharedUserSetting sus = (SharedUserSetting) obj;
5380                return sus.pkgFlags;
5381            } else if (obj instanceof PackageSetting) {
5382                final PackageSetting ps = (PackageSetting) obj;
5383                return ps.pkgFlags;
5384            }
5385        }
5386        return 0;
5387    }
5388
5389    @Override
5390    public int getPrivateFlagsForUid(int uid) {
5391        synchronized (mPackages) {
5392            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5393            if (obj instanceof SharedUserSetting) {
5394                final SharedUserSetting sus = (SharedUserSetting) obj;
5395                return sus.pkgPrivateFlags;
5396            } else if (obj instanceof PackageSetting) {
5397                final PackageSetting ps = (PackageSetting) obj;
5398                return ps.pkgPrivateFlags;
5399            }
5400        }
5401        return 0;
5402    }
5403
5404    @Override
5405    public boolean isUidPrivileged(int uid) {
5406        uid = UserHandle.getAppId(uid);
5407        // reader
5408        synchronized (mPackages) {
5409            Object obj = mSettings.getUserIdLPr(uid);
5410            if (obj instanceof SharedUserSetting) {
5411                final SharedUserSetting sus = (SharedUserSetting) obj;
5412                final Iterator<PackageSetting> it = sus.packages.iterator();
5413                while (it.hasNext()) {
5414                    if (it.next().isPrivileged()) {
5415                        return true;
5416                    }
5417                }
5418            } else if (obj instanceof PackageSetting) {
5419                final PackageSetting ps = (PackageSetting) obj;
5420                return ps.isPrivileged();
5421            }
5422        }
5423        return false;
5424    }
5425
5426    @Override
5427    public String[] getAppOpPermissionPackages(String permissionName) {
5428        synchronized (mPackages) {
5429            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5430            if (pkgs == null) {
5431                return null;
5432            }
5433            return pkgs.toArray(new String[pkgs.size()]);
5434        }
5435    }
5436
5437    @Override
5438    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5439            int flags, int userId) {
5440        try {
5441            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5442
5443            if (!sUserManager.exists(userId)) return null;
5444            flags = updateFlagsForResolve(flags, userId, intent);
5445            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5446                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5447
5448            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5449            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5450                    flags, userId);
5451            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5452
5453            final ResolveInfo bestChoice =
5454                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5455            return bestChoice;
5456        } finally {
5457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5458        }
5459    }
5460
5461    @Override
5462    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5463        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5464            throw new SecurityException(
5465                    "findPersistentPreferredActivity can only be run by the system");
5466        }
5467        if (!sUserManager.exists(userId)) {
5468            return null;
5469        }
5470        intent = updateIntentForResolve(intent);
5471        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5472        final int flags = updateFlagsForResolve(0, userId, intent);
5473        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5474                userId);
5475        synchronized (mPackages) {
5476            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5477                    userId);
5478        }
5479    }
5480
5481    @Override
5482    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5483            IntentFilter filter, int match, ComponentName activity) {
5484        final int userId = UserHandle.getCallingUserId();
5485        if (DEBUG_PREFERRED) {
5486            Log.v(TAG, "setLastChosenActivity intent=" + intent
5487                + " resolvedType=" + resolvedType
5488                + " flags=" + flags
5489                + " filter=" + filter
5490                + " match=" + match
5491                + " activity=" + activity);
5492            filter.dump(new PrintStreamPrinter(System.out), "    ");
5493        }
5494        intent.setComponent(null);
5495        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5496                userId);
5497        // Find any earlier preferred or last chosen entries and nuke them
5498        findPreferredActivity(intent, resolvedType,
5499                flags, query, 0, false, true, false, userId);
5500        // Add the new activity as the last chosen for this filter
5501        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5502                "Setting last chosen");
5503    }
5504
5505    @Override
5506    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5507        final int userId = UserHandle.getCallingUserId();
5508        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5509        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5510                userId);
5511        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5512                false, false, false, userId);
5513    }
5514
5515    private boolean isEphemeralDisabled() {
5516        // ephemeral apps have been disabled across the board
5517        if (DISABLE_EPHEMERAL_APPS) {
5518            return true;
5519        }
5520        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5521        if (!mSystemReady) {
5522            return true;
5523        }
5524        // we can't get a content resolver until the system is ready; these checks must happen last
5525        final ContentResolver resolver = mContext.getContentResolver();
5526        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5527            return true;
5528        }
5529        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5530    }
5531
5532    private boolean isEphemeralAllowed(
5533            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5534            boolean skipPackageCheck) {
5535        // Short circuit and return early if possible.
5536        if (isEphemeralDisabled()) {
5537            return false;
5538        }
5539        final int callingUser = UserHandle.getCallingUserId();
5540        if (callingUser != UserHandle.USER_SYSTEM) {
5541            return false;
5542        }
5543        if (mEphemeralResolverConnection == null) {
5544            return false;
5545        }
5546        if (mEphemeralInstallerComponent == null) {
5547            return false;
5548        }
5549        if (intent.getComponent() != null) {
5550            return false;
5551        }
5552        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5553            return false;
5554        }
5555        if (!skipPackageCheck && intent.getPackage() != null) {
5556            return false;
5557        }
5558        final boolean isWebUri = hasWebURI(intent);
5559        if (!isWebUri || intent.getData().getHost() == null) {
5560            return false;
5561        }
5562        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5563        synchronized (mPackages) {
5564            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5565            for (int n = 0; n < count; n++) {
5566                ResolveInfo info = resolvedActivities.get(n);
5567                String packageName = info.activityInfo.packageName;
5568                PackageSetting ps = mSettings.mPackages.get(packageName);
5569                if (ps != null) {
5570                    // Try to get the status from User settings first
5571                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5572                    int status = (int) (packedStatus >> 32);
5573                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5574                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5575                        if (DEBUG_EPHEMERAL) {
5576                            Slog.v(TAG, "DENY ephemeral apps;"
5577                                + " pkg: " + packageName + ", status: " + status);
5578                        }
5579                        return false;
5580                    }
5581                }
5582            }
5583        }
5584        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5585        return true;
5586    }
5587
5588    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5589            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5590            int userId) {
5591        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5592                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5593                        callingPackage, userId));
5594        mHandler.sendMessage(msg);
5595    }
5596
5597    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5598            int flags, List<ResolveInfo> query, int userId) {
5599        if (query != null) {
5600            final int N = query.size();
5601            if (N == 1) {
5602                return query.get(0);
5603            } else if (N > 1) {
5604                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5605                // If there is more than one activity with the same priority,
5606                // then let the user decide between them.
5607                ResolveInfo r0 = query.get(0);
5608                ResolveInfo r1 = query.get(1);
5609                if (DEBUG_INTENT_MATCHING || debug) {
5610                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5611                            + r1.activityInfo.name + "=" + r1.priority);
5612                }
5613                // If the first activity has a higher priority, or a different
5614                // default, then it is always desirable to pick it.
5615                if (r0.priority != r1.priority
5616                        || r0.preferredOrder != r1.preferredOrder
5617                        || r0.isDefault != r1.isDefault) {
5618                    return query.get(0);
5619                }
5620                // If we have saved a preference for a preferred activity for
5621                // this Intent, use that.
5622                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5623                        flags, query, r0.priority, true, false, debug, userId);
5624                if (ri != null) {
5625                    return ri;
5626                }
5627                ri = new ResolveInfo(mResolveInfo);
5628                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5629                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5630                // If all of the options come from the same package, show the application's
5631                // label and icon instead of the generic resolver's.
5632                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5633                // and then throw away the ResolveInfo itself, meaning that the caller loses
5634                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5635                // a fallback for this case; we only set the target package's resources on
5636                // the ResolveInfo, not the ActivityInfo.
5637                final String intentPackage = intent.getPackage();
5638                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5639                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5640                    ri.resolvePackageName = intentPackage;
5641                    if (userNeedsBadging(userId)) {
5642                        ri.noResourceId = true;
5643                    } else {
5644                        ri.icon = appi.icon;
5645                    }
5646                    ri.iconResourceId = appi.icon;
5647                    ri.labelRes = appi.labelRes;
5648                }
5649                ri.activityInfo.applicationInfo = new ApplicationInfo(
5650                        ri.activityInfo.applicationInfo);
5651                if (userId != 0) {
5652                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5653                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5654                }
5655                // Make sure that the resolver is displayable in car mode
5656                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5657                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5658                return ri;
5659            }
5660        }
5661        return null;
5662    }
5663
5664    /**
5665     * Return true if the given list is not empty and all of its contents have
5666     * an activityInfo with the given package name.
5667     */
5668    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5669        if (ArrayUtils.isEmpty(list)) {
5670            return false;
5671        }
5672        for (int i = 0, N = list.size(); i < N; i++) {
5673            final ResolveInfo ri = list.get(i);
5674            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5675            if (ai == null || !packageName.equals(ai.packageName)) {
5676                return false;
5677            }
5678        }
5679        return true;
5680    }
5681
5682    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5683            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5684        final int N = query.size();
5685        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5686                .get(userId);
5687        // Get the list of persistent preferred activities that handle the intent
5688        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5689        List<PersistentPreferredActivity> pprefs = ppir != null
5690                ? ppir.queryIntent(intent, resolvedType,
5691                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5692                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5693                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5694                : null;
5695        if (pprefs != null && pprefs.size() > 0) {
5696            final int M = pprefs.size();
5697            for (int i=0; i<M; i++) {
5698                final PersistentPreferredActivity ppa = pprefs.get(i);
5699                if (DEBUG_PREFERRED || debug) {
5700                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5701                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5702                            + "\n  component=" + ppa.mComponent);
5703                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5704                }
5705                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5706                        flags | MATCH_DISABLED_COMPONENTS, userId);
5707                if (DEBUG_PREFERRED || debug) {
5708                    Slog.v(TAG, "Found persistent preferred activity:");
5709                    if (ai != null) {
5710                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5711                    } else {
5712                        Slog.v(TAG, "  null");
5713                    }
5714                }
5715                if (ai == null) {
5716                    // This previously registered persistent preferred activity
5717                    // component is no longer known. Ignore it and do NOT remove it.
5718                    continue;
5719                }
5720                for (int j=0; j<N; j++) {
5721                    final ResolveInfo ri = query.get(j);
5722                    if (!ri.activityInfo.applicationInfo.packageName
5723                            .equals(ai.applicationInfo.packageName)) {
5724                        continue;
5725                    }
5726                    if (!ri.activityInfo.name.equals(ai.name)) {
5727                        continue;
5728                    }
5729                    //  Found a persistent preference that can handle the intent.
5730                    if (DEBUG_PREFERRED || debug) {
5731                        Slog.v(TAG, "Returning persistent preferred activity: " +
5732                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5733                    }
5734                    return ri;
5735                }
5736            }
5737        }
5738        return null;
5739    }
5740
5741    // TODO: handle preferred activities missing while user has amnesia
5742    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5743            List<ResolveInfo> query, int priority, boolean always,
5744            boolean removeMatches, boolean debug, int userId) {
5745        if (!sUserManager.exists(userId)) return null;
5746        flags = updateFlagsForResolve(flags, userId, intent);
5747        intent = updateIntentForResolve(intent);
5748        // writer
5749        synchronized (mPackages) {
5750            // Try to find a matching persistent preferred activity.
5751            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5752                    debug, userId);
5753
5754            // If a persistent preferred activity matched, use it.
5755            if (pri != null) {
5756                return pri;
5757            }
5758
5759            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5760            // Get the list of preferred activities that handle the intent
5761            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5762            List<PreferredActivity> prefs = pir != null
5763                    ? pir.queryIntent(intent, resolvedType,
5764                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5765                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5766                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5767                    : null;
5768            if (prefs != null && prefs.size() > 0) {
5769                boolean changed = false;
5770                try {
5771                    // First figure out how good the original match set is.
5772                    // We will only allow preferred activities that came
5773                    // from the same match quality.
5774                    int match = 0;
5775
5776                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5777
5778                    final int N = query.size();
5779                    for (int j=0; j<N; j++) {
5780                        final ResolveInfo ri = query.get(j);
5781                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5782                                + ": 0x" + Integer.toHexString(match));
5783                        if (ri.match > match) {
5784                            match = ri.match;
5785                        }
5786                    }
5787
5788                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5789                            + Integer.toHexString(match));
5790
5791                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5792                    final int M = prefs.size();
5793                    for (int i=0; i<M; i++) {
5794                        final PreferredActivity pa = prefs.get(i);
5795                        if (DEBUG_PREFERRED || debug) {
5796                            Slog.v(TAG, "Checking PreferredActivity ds="
5797                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5798                                    + "\n  component=" + pa.mPref.mComponent);
5799                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5800                        }
5801                        if (pa.mPref.mMatch != match) {
5802                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5803                                    + Integer.toHexString(pa.mPref.mMatch));
5804                            continue;
5805                        }
5806                        // If it's not an "always" type preferred activity and that's what we're
5807                        // looking for, skip it.
5808                        if (always && !pa.mPref.mAlways) {
5809                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5810                            continue;
5811                        }
5812                        final ActivityInfo ai = getActivityInfo(
5813                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5814                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5815                                userId);
5816                        if (DEBUG_PREFERRED || debug) {
5817                            Slog.v(TAG, "Found preferred activity:");
5818                            if (ai != null) {
5819                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5820                            } else {
5821                                Slog.v(TAG, "  null");
5822                            }
5823                        }
5824                        if (ai == null) {
5825                            // This previously registered preferred activity
5826                            // component is no longer known.  Most likely an update
5827                            // to the app was installed and in the new version this
5828                            // component no longer exists.  Clean it up by removing
5829                            // it from the preferred activities list, and skip it.
5830                            Slog.w(TAG, "Removing dangling preferred activity: "
5831                                    + pa.mPref.mComponent);
5832                            pir.removeFilter(pa);
5833                            changed = true;
5834                            continue;
5835                        }
5836                        for (int j=0; j<N; j++) {
5837                            final ResolveInfo ri = query.get(j);
5838                            if (!ri.activityInfo.applicationInfo.packageName
5839                                    .equals(ai.applicationInfo.packageName)) {
5840                                continue;
5841                            }
5842                            if (!ri.activityInfo.name.equals(ai.name)) {
5843                                continue;
5844                            }
5845
5846                            if (removeMatches) {
5847                                pir.removeFilter(pa);
5848                                changed = true;
5849                                if (DEBUG_PREFERRED) {
5850                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5851                                }
5852                                break;
5853                            }
5854
5855                            // Okay we found a previously set preferred or last chosen app.
5856                            // If the result set is different from when this
5857                            // was created, we need to clear it and re-ask the
5858                            // user their preference, if we're looking for an "always" type entry.
5859                            if (always && !pa.mPref.sameSet(query)) {
5860                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5861                                        + intent + " type " + resolvedType);
5862                                if (DEBUG_PREFERRED) {
5863                                    Slog.v(TAG, "Removing preferred activity since set changed "
5864                                            + pa.mPref.mComponent);
5865                                }
5866                                pir.removeFilter(pa);
5867                                // Re-add the filter as a "last chosen" entry (!always)
5868                                PreferredActivity lastChosen = new PreferredActivity(
5869                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5870                                pir.addFilter(lastChosen);
5871                                changed = true;
5872                                return null;
5873                            }
5874
5875                            // Yay! Either the set matched or we're looking for the last chosen
5876                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5877                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5878                            return ri;
5879                        }
5880                    }
5881                } finally {
5882                    if (changed) {
5883                        if (DEBUG_PREFERRED) {
5884                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5885                        }
5886                        scheduleWritePackageRestrictionsLocked(userId);
5887                    }
5888                }
5889            }
5890        }
5891        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5892        return null;
5893    }
5894
5895    /*
5896     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5897     */
5898    @Override
5899    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5900            int targetUserId) {
5901        mContext.enforceCallingOrSelfPermission(
5902                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5903        List<CrossProfileIntentFilter> matches =
5904                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5905        if (matches != null) {
5906            int size = matches.size();
5907            for (int i = 0; i < size; i++) {
5908                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5909            }
5910        }
5911        if (hasWebURI(intent)) {
5912            // cross-profile app linking works only towards the parent.
5913            final UserInfo parent = getProfileParent(sourceUserId);
5914            synchronized(mPackages) {
5915                int flags = updateFlagsForResolve(0, parent.id, intent);
5916                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5917                        intent, resolvedType, flags, sourceUserId, parent.id);
5918                return xpDomainInfo != null;
5919            }
5920        }
5921        return false;
5922    }
5923
5924    private UserInfo getProfileParent(int userId) {
5925        final long identity = Binder.clearCallingIdentity();
5926        try {
5927            return sUserManager.getProfileParent(userId);
5928        } finally {
5929            Binder.restoreCallingIdentity(identity);
5930        }
5931    }
5932
5933    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5934            String resolvedType, int userId) {
5935        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5936        if (resolver != null) {
5937            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5938                    false /*visibleToEphemeral*/, false /*isInstant*/, userId);
5939        }
5940        return null;
5941    }
5942
5943    @Override
5944    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5945            String resolvedType, int flags, int userId) {
5946        try {
5947            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5948
5949            return new ParceledListSlice<>(
5950                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5951        } finally {
5952            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5953        }
5954    }
5955
5956    /**
5957     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5958     * ephemeral, returns {@code null}.
5959     */
5960    private String getEphemeralPackageName(int callingUid) {
5961        final int appId = UserHandle.getAppId(callingUid);
5962        synchronized (mPackages) {
5963            final Object obj = mSettings.getUserIdLPr(appId);
5964            if (obj instanceof PackageSetting) {
5965                final PackageSetting ps = (PackageSetting) obj;
5966                return ps.pkg.applicationInfo.isInstantApp() ? ps.pkg.packageName : null;
5967            }
5968        }
5969        return null;
5970    }
5971
5972    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5973            String resolvedType, int flags, int userId) {
5974        if (!sUserManager.exists(userId)) return Collections.emptyList();
5975        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5976        flags = updateFlagsForResolve(flags, userId, intent);
5977        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5978                false /* requireFullPermission */, false /* checkShell */,
5979                "query intent activities");
5980        ComponentName comp = intent.getComponent();
5981        if (comp == null) {
5982            if (intent.getSelector() != null) {
5983                intent = intent.getSelector();
5984                comp = intent.getComponent();
5985            }
5986        }
5987
5988        if (comp != null) {
5989            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5990            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5991            if (ai != null) {
5992                // When specifying an explicit component, we prevent the activity from being
5993                // used when either 1) the calling package is normal and the activity is within
5994                // an ephemeral application or 2) the calling package is ephemeral and the
5995                // activity is not visible to ephemeral applications.
5996                boolean matchEphemeral =
5997                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5998                boolean ephemeralVisibleOnly =
5999                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
6000                boolean blockResolution =
6001                        (!matchEphemeral && ephemeralPkgName == null
6002                                && (ai.applicationInfo.privateFlags
6003                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
6004                        || (ephemeralVisibleOnly && ephemeralPkgName != null
6005                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
6006                if (!blockResolution) {
6007                    final ResolveInfo ri = new ResolveInfo();
6008                    ri.activityInfo = ai;
6009                    list.add(ri);
6010                }
6011            }
6012            return list;
6013        }
6014
6015        // reader
6016        boolean sortResult = false;
6017        boolean addEphemeral = false;
6018        List<ResolveInfo> result;
6019        final String pkgName = intent.getPackage();
6020        synchronized (mPackages) {
6021            if (pkgName == null) {
6022                List<CrossProfileIntentFilter> matchingFilters =
6023                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6024                // Check for results that need to skip the current profile.
6025                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6026                        resolvedType, flags, userId);
6027                if (xpResolveInfo != null) {
6028                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6029                    xpResult.add(xpResolveInfo);
6030                    return filterForEphemeral(
6031                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
6032                }
6033
6034                // Check for results in the current profile.
6035                result = filterIfNotSystemUser(mActivities.queryIntent(
6036                        intent, resolvedType, flags, userId), userId);
6037                addEphemeral =
6038                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6039
6040                // Check for cross profile results.
6041                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6042                xpResolveInfo = queryCrossProfileIntents(
6043                        matchingFilters, intent, resolvedType, flags, userId,
6044                        hasNonNegativePriorityResult);
6045                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6046                    boolean isVisibleToUser = filterIfNotSystemUser(
6047                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6048                    if (isVisibleToUser) {
6049                        result.add(xpResolveInfo);
6050                        sortResult = true;
6051                    }
6052                }
6053                if (hasWebURI(intent)) {
6054                    CrossProfileDomainInfo xpDomainInfo = null;
6055                    final UserInfo parent = getProfileParent(userId);
6056                    if (parent != null) {
6057                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6058                                flags, userId, parent.id);
6059                    }
6060                    if (xpDomainInfo != null) {
6061                        if (xpResolveInfo != null) {
6062                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6063                            // in the result.
6064                            result.remove(xpResolveInfo);
6065                        }
6066                        if (result.size() == 0 && !addEphemeral) {
6067                            // No result in current profile, but found candidate in parent user.
6068                            // And we are not going to add emphemeral app, so we can return the
6069                            // result straight away.
6070                            result.add(xpDomainInfo.resolveInfo);
6071                            return filterForEphemeral(result, ephemeralPkgName);
6072                        }
6073                    } else if (result.size() <= 1 && !addEphemeral) {
6074                        // No result in parent user and <= 1 result in current profile, and we
6075                        // are not going to add emphemeral app, so we can return the result without
6076                        // further processing.
6077                        return filterForEphemeral(result, ephemeralPkgName);
6078                    }
6079                    // We have more than one candidate (combining results from current and parent
6080                    // profile), so we need filtering and sorting.
6081                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6082                            intent, flags, result, xpDomainInfo, userId);
6083                    sortResult = true;
6084                }
6085            } else {
6086                final PackageParser.Package pkg = mPackages.get(pkgName);
6087                if (pkg != null) {
6088                    result = filterForEphemeral(filterIfNotSystemUser(
6089                            mActivities.queryIntentForPackage(
6090                                    intent, resolvedType, flags, pkg.activities, userId),
6091                            userId), ephemeralPkgName);
6092                } else {
6093                    // the caller wants to resolve for a particular package; however, there
6094                    // were no installed results, so, try to find an ephemeral result
6095                    addEphemeral = isEphemeralAllowed(
6096                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6097                    result = new ArrayList<ResolveInfo>();
6098                }
6099            }
6100        }
6101        if (addEphemeral) {
6102            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6103            final EphemeralRequest requestObject = new EphemeralRequest(
6104                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6105                    null /*launchIntent*/, null /*callingPackage*/, userId);
6106            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6107                    mContext, mEphemeralResolverConnection, requestObject);
6108            if (intentInfo != null) {
6109                if (DEBUG_EPHEMERAL) {
6110                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6111                }
6112                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6113                ephemeralInstaller.ephemeralResponse = intentInfo;
6114                // make sure this resolver is the default
6115                ephemeralInstaller.isDefault = true;
6116                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6117                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6118                // add a non-generic filter
6119                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6120                ephemeralInstaller.filter.addDataPath(
6121                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6122                result.add(ephemeralInstaller);
6123            }
6124            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6125        }
6126        if (sortResult) {
6127            Collections.sort(result, mResolvePrioritySorter);
6128        }
6129        return filterForEphemeral(result, ephemeralPkgName);
6130    }
6131
6132    private static class CrossProfileDomainInfo {
6133        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6134        ResolveInfo resolveInfo;
6135        /* Best domain verification status of the activities found in the other profile */
6136        int bestDomainVerificationStatus;
6137    }
6138
6139    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6140            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6141        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6142                sourceUserId)) {
6143            return null;
6144        }
6145        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6146                resolvedType, flags, parentUserId);
6147
6148        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6149            return null;
6150        }
6151        CrossProfileDomainInfo result = null;
6152        int size = resultTargetUser.size();
6153        for (int i = 0; i < size; i++) {
6154            ResolveInfo riTargetUser = resultTargetUser.get(i);
6155            // Intent filter verification is only for filters that specify a host. So don't return
6156            // those that handle all web uris.
6157            if (riTargetUser.handleAllWebDataURI) {
6158                continue;
6159            }
6160            String packageName = riTargetUser.activityInfo.packageName;
6161            PackageSetting ps = mSettings.mPackages.get(packageName);
6162            if (ps == null) {
6163                continue;
6164            }
6165            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6166            int status = (int)(verificationState >> 32);
6167            if (result == null) {
6168                result = new CrossProfileDomainInfo();
6169                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6170                        sourceUserId, parentUserId);
6171                result.bestDomainVerificationStatus = status;
6172            } else {
6173                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6174                        result.bestDomainVerificationStatus);
6175            }
6176        }
6177        // Don't consider matches with status NEVER across profiles.
6178        if (result != null && result.bestDomainVerificationStatus
6179                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6180            return null;
6181        }
6182        return result;
6183    }
6184
6185    /**
6186     * Verification statuses are ordered from the worse to the best, except for
6187     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6188     */
6189    private int bestDomainVerificationStatus(int status1, int status2) {
6190        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6191            return status2;
6192        }
6193        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6194            return status1;
6195        }
6196        return (int) MathUtils.max(status1, status2);
6197    }
6198
6199    private boolean isUserEnabled(int userId) {
6200        long callingId = Binder.clearCallingIdentity();
6201        try {
6202            UserInfo userInfo = sUserManager.getUserInfo(userId);
6203            return userInfo != null && userInfo.isEnabled();
6204        } finally {
6205            Binder.restoreCallingIdentity(callingId);
6206        }
6207    }
6208
6209    /**
6210     * Filter out activities with systemUserOnly flag set, when current user is not System.
6211     *
6212     * @return filtered list
6213     */
6214    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6215        if (userId == UserHandle.USER_SYSTEM) {
6216            return resolveInfos;
6217        }
6218        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6219            ResolveInfo info = resolveInfos.get(i);
6220            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6221                resolveInfos.remove(i);
6222            }
6223        }
6224        return resolveInfos;
6225    }
6226
6227    /**
6228     * Filters out ephemeral activities.
6229     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6230     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6231     *
6232     * @param resolveInfos The pre-filtered list of resolved activities
6233     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6234     *          is performed.
6235     * @return A filtered list of resolved activities.
6236     */
6237    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6238            String ephemeralPkgName) {
6239        if (ephemeralPkgName == null) {
6240            return resolveInfos;
6241        }
6242        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6243            ResolveInfo info = resolveInfos.get(i);
6244            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6245            // allow activities that are defined in the provided package
6246            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6247                continue;
6248            }
6249            // allow activities that have been explicitly exposed to ephemeral apps
6250            if (!isEphemeralApp
6251                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6252                continue;
6253            }
6254            resolveInfos.remove(i);
6255        }
6256        return resolveInfos;
6257    }
6258
6259    /**
6260     * @param resolveInfos list of resolve infos in descending priority order
6261     * @return if the list contains a resolve info with non-negative priority
6262     */
6263    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6264        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6265    }
6266
6267    private static boolean hasWebURI(Intent intent) {
6268        if (intent.getData() == null) {
6269            return false;
6270        }
6271        final String scheme = intent.getScheme();
6272        if (TextUtils.isEmpty(scheme)) {
6273            return false;
6274        }
6275        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6276    }
6277
6278    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6279            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6280            int userId) {
6281        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6282
6283        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6284            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6285                    candidates.size());
6286        }
6287
6288        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6289        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6290        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6291        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6292        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6293        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6294
6295        synchronized (mPackages) {
6296            final int count = candidates.size();
6297            // First, try to use linked apps. Partition the candidates into four lists:
6298            // one for the final results, one for the "do not use ever", one for "undefined status"
6299            // and finally one for "browser app type".
6300            for (int n=0; n<count; n++) {
6301                ResolveInfo info = candidates.get(n);
6302                String packageName = info.activityInfo.packageName;
6303                PackageSetting ps = mSettings.mPackages.get(packageName);
6304                if (ps != null) {
6305                    // Add to the special match all list (Browser use case)
6306                    if (info.handleAllWebDataURI) {
6307                        matchAllList.add(info);
6308                        continue;
6309                    }
6310                    // Try to get the status from User settings first
6311                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6312                    int status = (int)(packedStatus >> 32);
6313                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6314                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6315                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6316                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6317                                    + " : linkgen=" + linkGeneration);
6318                        }
6319                        // Use link-enabled generation as preferredOrder, i.e.
6320                        // prefer newly-enabled over earlier-enabled.
6321                        info.preferredOrder = linkGeneration;
6322                        alwaysList.add(info);
6323                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6324                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6325                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6326                        }
6327                        neverList.add(info);
6328                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6329                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6330                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6331                        }
6332                        alwaysAskList.add(info);
6333                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6334                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6335                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6336                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6337                        }
6338                        undefinedList.add(info);
6339                    }
6340                }
6341            }
6342
6343            // We'll want to include browser possibilities in a few cases
6344            boolean includeBrowser = false;
6345
6346            // First try to add the "always" resolution(s) for the current user, if any
6347            if (alwaysList.size() > 0) {
6348                result.addAll(alwaysList);
6349            } else {
6350                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6351                result.addAll(undefinedList);
6352                // Maybe add one for the other profile.
6353                if (xpDomainInfo != null && (
6354                        xpDomainInfo.bestDomainVerificationStatus
6355                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6356                    result.add(xpDomainInfo.resolveInfo);
6357                }
6358                includeBrowser = true;
6359            }
6360
6361            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6362            // If there were 'always' entries their preferred order has been set, so we also
6363            // back that off to make the alternatives equivalent
6364            if (alwaysAskList.size() > 0) {
6365                for (ResolveInfo i : result) {
6366                    i.preferredOrder = 0;
6367                }
6368                result.addAll(alwaysAskList);
6369                includeBrowser = true;
6370            }
6371
6372            if (includeBrowser) {
6373                // Also add browsers (all of them or only the default one)
6374                if (DEBUG_DOMAIN_VERIFICATION) {
6375                    Slog.v(TAG, "   ...including browsers in candidate set");
6376                }
6377                if ((matchFlags & MATCH_ALL) != 0) {
6378                    result.addAll(matchAllList);
6379                } else {
6380                    // Browser/generic handling case.  If there's a default browser, go straight
6381                    // to that (but only if there is no other higher-priority match).
6382                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6383                    int maxMatchPrio = 0;
6384                    ResolveInfo defaultBrowserMatch = null;
6385                    final int numCandidates = matchAllList.size();
6386                    for (int n = 0; n < numCandidates; n++) {
6387                        ResolveInfo info = matchAllList.get(n);
6388                        // track the highest overall match priority...
6389                        if (info.priority > maxMatchPrio) {
6390                            maxMatchPrio = info.priority;
6391                        }
6392                        // ...and the highest-priority default browser match
6393                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6394                            if (defaultBrowserMatch == null
6395                                    || (defaultBrowserMatch.priority < info.priority)) {
6396                                if (debug) {
6397                                    Slog.v(TAG, "Considering default browser match " + info);
6398                                }
6399                                defaultBrowserMatch = info;
6400                            }
6401                        }
6402                    }
6403                    if (defaultBrowserMatch != null
6404                            && defaultBrowserMatch.priority >= maxMatchPrio
6405                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6406                    {
6407                        if (debug) {
6408                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6409                        }
6410                        result.add(defaultBrowserMatch);
6411                    } else {
6412                        result.addAll(matchAllList);
6413                    }
6414                }
6415
6416                // If there is nothing selected, add all candidates and remove the ones that the user
6417                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6418                if (result.size() == 0) {
6419                    result.addAll(candidates);
6420                    result.removeAll(neverList);
6421                }
6422            }
6423        }
6424        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6425            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6426                    result.size());
6427            for (ResolveInfo info : result) {
6428                Slog.v(TAG, "  + " + info.activityInfo);
6429            }
6430        }
6431        return result;
6432    }
6433
6434    // Returns a packed value as a long:
6435    //
6436    // high 'int'-sized word: link status: undefined/ask/never/always.
6437    // low 'int'-sized word: relative priority among 'always' results.
6438    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6439        long result = ps.getDomainVerificationStatusForUser(userId);
6440        // if none available, get the master status
6441        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6442            if (ps.getIntentFilterVerificationInfo() != null) {
6443                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6444            }
6445        }
6446        return result;
6447    }
6448
6449    private ResolveInfo querySkipCurrentProfileIntents(
6450            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6451            int flags, int sourceUserId) {
6452        if (matchingFilters != null) {
6453            int size = matchingFilters.size();
6454            for (int i = 0; i < size; i ++) {
6455                CrossProfileIntentFilter filter = matchingFilters.get(i);
6456                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6457                    // Checking if there are activities in the target user that can handle the
6458                    // intent.
6459                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6460                            resolvedType, flags, sourceUserId);
6461                    if (resolveInfo != null) {
6462                        return resolveInfo;
6463                    }
6464                }
6465            }
6466        }
6467        return null;
6468    }
6469
6470    // Return matching ResolveInfo in target user if any.
6471    private ResolveInfo queryCrossProfileIntents(
6472            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6473            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6474        if (matchingFilters != null) {
6475            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6476            // match the same intent. For performance reasons, it is better not to
6477            // run queryIntent twice for the same userId
6478            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6479            int size = matchingFilters.size();
6480            for (int i = 0; i < size; i++) {
6481                CrossProfileIntentFilter filter = matchingFilters.get(i);
6482                int targetUserId = filter.getTargetUserId();
6483                boolean skipCurrentProfile =
6484                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6485                boolean skipCurrentProfileIfNoMatchFound =
6486                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6487                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6488                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6489                    // Checking if there are activities in the target user that can handle the
6490                    // intent.
6491                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6492                            resolvedType, flags, sourceUserId);
6493                    if (resolveInfo != null) return resolveInfo;
6494                    alreadyTriedUserIds.put(targetUserId, true);
6495                }
6496            }
6497        }
6498        return null;
6499    }
6500
6501    /**
6502     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6503     * will forward the intent to the filter's target user.
6504     * Otherwise, returns null.
6505     */
6506    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6507            String resolvedType, int flags, int sourceUserId) {
6508        int targetUserId = filter.getTargetUserId();
6509        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6510                resolvedType, flags, targetUserId);
6511        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6512            // If all the matches in the target profile are suspended, return null.
6513            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6514                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6515                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6516                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6517                            targetUserId);
6518                }
6519            }
6520        }
6521        return null;
6522    }
6523
6524    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6525            int sourceUserId, int targetUserId) {
6526        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6527        long ident = Binder.clearCallingIdentity();
6528        boolean targetIsProfile;
6529        try {
6530            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6531        } finally {
6532            Binder.restoreCallingIdentity(ident);
6533        }
6534        String className;
6535        if (targetIsProfile) {
6536            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6537        } else {
6538            className = FORWARD_INTENT_TO_PARENT;
6539        }
6540        ComponentName forwardingActivityComponentName = new ComponentName(
6541                mAndroidApplication.packageName, className);
6542        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6543                sourceUserId);
6544        if (!targetIsProfile) {
6545            forwardingActivityInfo.showUserIcon = targetUserId;
6546            forwardingResolveInfo.noResourceId = true;
6547        }
6548        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6549        forwardingResolveInfo.priority = 0;
6550        forwardingResolveInfo.preferredOrder = 0;
6551        forwardingResolveInfo.match = 0;
6552        forwardingResolveInfo.isDefault = true;
6553        forwardingResolveInfo.filter = filter;
6554        forwardingResolveInfo.targetUserId = targetUserId;
6555        return forwardingResolveInfo;
6556    }
6557
6558    @Override
6559    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6560            Intent[] specifics, String[] specificTypes, Intent intent,
6561            String resolvedType, int flags, int userId) {
6562        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6563                specificTypes, intent, resolvedType, flags, userId));
6564    }
6565
6566    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6567            Intent[] specifics, String[] specificTypes, Intent intent,
6568            String resolvedType, int flags, int userId) {
6569        if (!sUserManager.exists(userId)) return Collections.emptyList();
6570        flags = updateFlagsForResolve(flags, userId, intent);
6571        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6572                false /* requireFullPermission */, false /* checkShell */,
6573                "query intent activity options");
6574        final String resultsAction = intent.getAction();
6575
6576        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6577                | PackageManager.GET_RESOLVED_FILTER, userId);
6578
6579        if (DEBUG_INTENT_MATCHING) {
6580            Log.v(TAG, "Query " + intent + ": " + results);
6581        }
6582
6583        int specificsPos = 0;
6584        int N;
6585
6586        // todo: note that the algorithm used here is O(N^2).  This
6587        // isn't a problem in our current environment, but if we start running
6588        // into situations where we have more than 5 or 10 matches then this
6589        // should probably be changed to something smarter...
6590
6591        // First we go through and resolve each of the specific items
6592        // that were supplied, taking care of removing any corresponding
6593        // duplicate items in the generic resolve list.
6594        if (specifics != null) {
6595            for (int i=0; i<specifics.length; i++) {
6596                final Intent sintent = specifics[i];
6597                if (sintent == null) {
6598                    continue;
6599                }
6600
6601                if (DEBUG_INTENT_MATCHING) {
6602                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6603                }
6604
6605                String action = sintent.getAction();
6606                if (resultsAction != null && resultsAction.equals(action)) {
6607                    // If this action was explicitly requested, then don't
6608                    // remove things that have it.
6609                    action = null;
6610                }
6611
6612                ResolveInfo ri = null;
6613                ActivityInfo ai = null;
6614
6615                ComponentName comp = sintent.getComponent();
6616                if (comp == null) {
6617                    ri = resolveIntent(
6618                        sintent,
6619                        specificTypes != null ? specificTypes[i] : null,
6620                            flags, userId);
6621                    if (ri == null) {
6622                        continue;
6623                    }
6624                    if (ri == mResolveInfo) {
6625                        // ACK!  Must do something better with this.
6626                    }
6627                    ai = ri.activityInfo;
6628                    comp = new ComponentName(ai.applicationInfo.packageName,
6629                            ai.name);
6630                } else {
6631                    ai = getActivityInfo(comp, flags, userId);
6632                    if (ai == null) {
6633                        continue;
6634                    }
6635                }
6636
6637                // Look for any generic query activities that are duplicates
6638                // of this specific one, and remove them from the results.
6639                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6640                N = results.size();
6641                int j;
6642                for (j=specificsPos; j<N; j++) {
6643                    ResolveInfo sri = results.get(j);
6644                    if ((sri.activityInfo.name.equals(comp.getClassName())
6645                            && sri.activityInfo.applicationInfo.packageName.equals(
6646                                    comp.getPackageName()))
6647                        || (action != null && sri.filter.matchAction(action))) {
6648                        results.remove(j);
6649                        if (DEBUG_INTENT_MATCHING) Log.v(
6650                            TAG, "Removing duplicate item from " + j
6651                            + " due to specific " + specificsPos);
6652                        if (ri == null) {
6653                            ri = sri;
6654                        }
6655                        j--;
6656                        N--;
6657                    }
6658                }
6659
6660                // Add this specific item to its proper place.
6661                if (ri == null) {
6662                    ri = new ResolveInfo();
6663                    ri.activityInfo = ai;
6664                }
6665                results.add(specificsPos, ri);
6666                ri.specificIndex = i;
6667                specificsPos++;
6668            }
6669        }
6670
6671        // Now we go through the remaining generic results and remove any
6672        // duplicate actions that are found here.
6673        N = results.size();
6674        for (int i=specificsPos; i<N-1; i++) {
6675            final ResolveInfo rii = results.get(i);
6676            if (rii.filter == null) {
6677                continue;
6678            }
6679
6680            // Iterate over all of the actions of this result's intent
6681            // filter...  typically this should be just one.
6682            final Iterator<String> it = rii.filter.actionsIterator();
6683            if (it == null) {
6684                continue;
6685            }
6686            while (it.hasNext()) {
6687                final String action = it.next();
6688                if (resultsAction != null && resultsAction.equals(action)) {
6689                    // If this action was explicitly requested, then don't
6690                    // remove things that have it.
6691                    continue;
6692                }
6693                for (int j=i+1; j<N; j++) {
6694                    final ResolveInfo rij = results.get(j);
6695                    if (rij.filter != null && rij.filter.hasAction(action)) {
6696                        results.remove(j);
6697                        if (DEBUG_INTENT_MATCHING) Log.v(
6698                            TAG, "Removing duplicate item from " + j
6699                            + " due to action " + action + " at " + i);
6700                        j--;
6701                        N--;
6702                    }
6703                }
6704            }
6705
6706            // If the caller didn't request filter information, drop it now
6707            // so we don't have to marshall/unmarshall it.
6708            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6709                rii.filter = null;
6710            }
6711        }
6712
6713        // Filter out the caller activity if so requested.
6714        if (caller != null) {
6715            N = results.size();
6716            for (int i=0; i<N; i++) {
6717                ActivityInfo ainfo = results.get(i).activityInfo;
6718                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6719                        && caller.getClassName().equals(ainfo.name)) {
6720                    results.remove(i);
6721                    break;
6722                }
6723            }
6724        }
6725
6726        // If the caller didn't request filter information,
6727        // drop them now so we don't have to
6728        // marshall/unmarshall it.
6729        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6730            N = results.size();
6731            for (int i=0; i<N; i++) {
6732                results.get(i).filter = null;
6733            }
6734        }
6735
6736        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6737        return results;
6738    }
6739
6740    @Override
6741    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6742            String resolvedType, int flags, int userId) {
6743        return new ParceledListSlice<>(
6744                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6745    }
6746
6747    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6748            String resolvedType, int flags, int userId) {
6749        if (!sUserManager.exists(userId)) return Collections.emptyList();
6750        flags = updateFlagsForResolve(flags, userId, intent);
6751        ComponentName comp = intent.getComponent();
6752        if (comp == null) {
6753            if (intent.getSelector() != null) {
6754                intent = intent.getSelector();
6755                comp = intent.getComponent();
6756            }
6757        }
6758        if (comp != null) {
6759            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6760            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6761            if (ai != null) {
6762                ResolveInfo ri = new ResolveInfo();
6763                ri.activityInfo = ai;
6764                list.add(ri);
6765            }
6766            return list;
6767        }
6768
6769        // reader
6770        synchronized (mPackages) {
6771            String pkgName = intent.getPackage();
6772            if (pkgName == null) {
6773                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6774            }
6775            final PackageParser.Package pkg = mPackages.get(pkgName);
6776            if (pkg != null) {
6777                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6778                        userId);
6779            }
6780            return Collections.emptyList();
6781        }
6782    }
6783
6784    @Override
6785    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6786        if (!sUserManager.exists(userId)) return null;
6787        flags = updateFlagsForResolve(flags, userId, intent);
6788        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6789        if (query != null) {
6790            if (query.size() >= 1) {
6791                // If there is more than one service with the same priority,
6792                // just arbitrarily pick the first one.
6793                return query.get(0);
6794            }
6795        }
6796        return null;
6797    }
6798
6799    @Override
6800    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6801            String resolvedType, int flags, int userId) {
6802        return new ParceledListSlice<>(
6803                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6804    }
6805
6806    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6807            String resolvedType, int flags, int userId) {
6808        if (!sUserManager.exists(userId)) return Collections.emptyList();
6809        flags = updateFlagsForResolve(flags, userId, intent);
6810        ComponentName comp = intent.getComponent();
6811        if (comp == null) {
6812            if (intent.getSelector() != null) {
6813                intent = intent.getSelector();
6814                comp = intent.getComponent();
6815            }
6816        }
6817        if (comp != null) {
6818            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6819            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6820            if (si != null) {
6821                final ResolveInfo ri = new ResolveInfo();
6822                ri.serviceInfo = si;
6823                list.add(ri);
6824            }
6825            return list;
6826        }
6827
6828        // reader
6829        synchronized (mPackages) {
6830            String pkgName = intent.getPackage();
6831            if (pkgName == null) {
6832                return mServices.queryIntent(intent, resolvedType, flags, userId);
6833            }
6834            final PackageParser.Package pkg = mPackages.get(pkgName);
6835            if (pkg != null) {
6836                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6837                        userId);
6838            }
6839            return Collections.emptyList();
6840        }
6841    }
6842
6843    @Override
6844    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6845            String resolvedType, int flags, int userId) {
6846        return new ParceledListSlice<>(
6847                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6848    }
6849
6850    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6851            Intent intent, String resolvedType, int flags, int userId) {
6852        if (!sUserManager.exists(userId)) return Collections.emptyList();
6853        flags = updateFlagsForResolve(flags, userId, intent);
6854        ComponentName comp = intent.getComponent();
6855        if (comp == null) {
6856            if (intent.getSelector() != null) {
6857                intent = intent.getSelector();
6858                comp = intent.getComponent();
6859            }
6860        }
6861        if (comp != null) {
6862            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6863            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6864            if (pi != null) {
6865                final ResolveInfo ri = new ResolveInfo();
6866                ri.providerInfo = pi;
6867                list.add(ri);
6868            }
6869            return list;
6870        }
6871
6872        // reader
6873        synchronized (mPackages) {
6874            String pkgName = intent.getPackage();
6875            if (pkgName == null) {
6876                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6877            }
6878            final PackageParser.Package pkg = mPackages.get(pkgName);
6879            if (pkg != null) {
6880                return mProviders.queryIntentForPackage(
6881                        intent, resolvedType, flags, pkg.providers, userId);
6882            }
6883            return Collections.emptyList();
6884        }
6885    }
6886
6887    @Override
6888    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6889        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6890        flags = updateFlagsForPackage(flags, userId, null);
6891        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6892        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6893                true /* requireFullPermission */, false /* checkShell */,
6894                "get installed packages");
6895
6896        // writer
6897        synchronized (mPackages) {
6898            ArrayList<PackageInfo> list;
6899            if (listUninstalled) {
6900                list = new ArrayList<>(mSettings.mPackages.size());
6901                for (PackageSetting ps : mSettings.mPackages.values()) {
6902                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6903                        continue;
6904                    }
6905                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6906                    if (pi != null) {
6907                        list.add(pi);
6908                    }
6909                }
6910            } else {
6911                list = new ArrayList<>(mPackages.size());
6912                for (PackageParser.Package p : mPackages.values()) {
6913                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6914                            Binder.getCallingUid(), userId)) {
6915                        continue;
6916                    }
6917                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6918                            p.mExtras, flags, userId);
6919                    if (pi != null) {
6920                        list.add(pi);
6921                    }
6922                }
6923            }
6924
6925            return new ParceledListSlice<>(list);
6926        }
6927    }
6928
6929    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6930            String[] permissions, boolean[] tmp, int flags, int userId) {
6931        int numMatch = 0;
6932        final PermissionsState permissionsState = ps.getPermissionsState();
6933        for (int i=0; i<permissions.length; i++) {
6934            final String permission = permissions[i];
6935            if (permissionsState.hasPermission(permission, userId)) {
6936                tmp[i] = true;
6937                numMatch++;
6938            } else {
6939                tmp[i] = false;
6940            }
6941        }
6942        if (numMatch == 0) {
6943            return;
6944        }
6945        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6946
6947        // The above might return null in cases of uninstalled apps or install-state
6948        // skew across users/profiles.
6949        if (pi != null) {
6950            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6951                if (numMatch == permissions.length) {
6952                    pi.requestedPermissions = permissions;
6953                } else {
6954                    pi.requestedPermissions = new String[numMatch];
6955                    numMatch = 0;
6956                    for (int i=0; i<permissions.length; i++) {
6957                        if (tmp[i]) {
6958                            pi.requestedPermissions[numMatch] = permissions[i];
6959                            numMatch++;
6960                        }
6961                    }
6962                }
6963            }
6964            list.add(pi);
6965        }
6966    }
6967
6968    @Override
6969    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6970            String[] permissions, int flags, int userId) {
6971        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6972        flags = updateFlagsForPackage(flags, userId, permissions);
6973        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6974                true /* requireFullPermission */, false /* checkShell */,
6975                "get packages holding permissions");
6976        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6977
6978        // writer
6979        synchronized (mPackages) {
6980            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6981            boolean[] tmpBools = new boolean[permissions.length];
6982            if (listUninstalled) {
6983                for (PackageSetting ps : mSettings.mPackages.values()) {
6984                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6985                            userId);
6986                }
6987            } else {
6988                for (PackageParser.Package pkg : mPackages.values()) {
6989                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6990                    if (ps != null) {
6991                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6992                                userId);
6993                    }
6994                }
6995            }
6996
6997            return new ParceledListSlice<PackageInfo>(list);
6998        }
6999    }
7000
7001    @Override
7002    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7003        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7004        flags = updateFlagsForApplication(flags, userId, null);
7005        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7006
7007        // writer
7008        synchronized (mPackages) {
7009            ArrayList<ApplicationInfo> list;
7010            if (listUninstalled) {
7011                list = new ArrayList<>(mSettings.mPackages.size());
7012                for (PackageSetting ps : mSettings.mPackages.values()) {
7013                    ApplicationInfo ai;
7014                    int effectiveFlags = flags;
7015                    if (ps.isSystem()) {
7016                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7017                    }
7018                    if (ps.pkg != null) {
7019                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7020                            continue;
7021                        }
7022                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7023                                ps.readUserState(userId), userId);
7024                        if (ai != null) {
7025                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7026                        }
7027                    } else {
7028                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7029                        // and already converts to externally visible package name
7030                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7031                                Binder.getCallingUid(), effectiveFlags, userId);
7032                    }
7033                    if (ai != null) {
7034                        list.add(ai);
7035                    }
7036                }
7037            } else {
7038                list = new ArrayList<>(mPackages.size());
7039                for (PackageParser.Package p : mPackages.values()) {
7040                    if (p.mExtras != null) {
7041                        PackageSetting ps = (PackageSetting) p.mExtras;
7042                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7043                            continue;
7044                        }
7045                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7046                                ps.readUserState(userId), userId);
7047                        if (ai != null) {
7048                            ai.packageName = resolveExternalPackageNameLPr(p);
7049                            list.add(ai);
7050                        }
7051                    }
7052                }
7053            }
7054
7055            return new ParceledListSlice<>(list);
7056        }
7057    }
7058
7059    @Override
7060    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7061        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7062            return null;
7063        }
7064
7065        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7066                "getEphemeralApplications");
7067        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7068                true /* requireFullPermission */, false /* checkShell */,
7069                "getEphemeralApplications");
7070        synchronized (mPackages) {
7071            List<InstantAppInfo> instantApps = mInstantAppRegistry
7072                    .getInstantAppsLPr(userId);
7073            if (instantApps != null) {
7074                return new ParceledListSlice<>(instantApps);
7075            }
7076        }
7077        return null;
7078    }
7079
7080    @Override
7081    public boolean isInstantApp(String packageName, int userId) {
7082        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7083                true /* requireFullPermission */, false /* checkShell */,
7084                "isInstantApp");
7085        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7086            return false;
7087        }
7088
7089        if (!isCallerSameApp(packageName)) {
7090            return false;
7091        }
7092        synchronized (mPackages) {
7093            PackageParser.Package pkg = mPackages.get(packageName);
7094            if (pkg != null) {
7095                return pkg.applicationInfo.isInstantApp();
7096            }
7097        }
7098        return false;
7099    }
7100
7101    @Override
7102    public byte[] getInstantAppCookie(String packageName, int userId) {
7103        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7104            return null;
7105        }
7106
7107        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7108                true /* requireFullPermission */, false /* checkShell */,
7109                "getInstantAppCookie");
7110        if (!isCallerSameApp(packageName)) {
7111            return null;
7112        }
7113        synchronized (mPackages) {
7114            return mInstantAppRegistry.getInstantAppCookieLPw(
7115                    packageName, userId);
7116        }
7117    }
7118
7119    @Override
7120    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7121        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7122            return true;
7123        }
7124
7125        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7126                true /* requireFullPermission */, true /* checkShell */,
7127                "setInstantAppCookie");
7128        if (!isCallerSameApp(packageName)) {
7129            return false;
7130        }
7131        synchronized (mPackages) {
7132            return mInstantAppRegistry.setInstantAppCookieLPw(
7133                    packageName, cookie, userId);
7134        }
7135    }
7136
7137    @Override
7138    public Bitmap getInstantAppIcon(String packageName, int userId) {
7139        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7140            return null;
7141        }
7142
7143        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7144                "getInstantAppIcon");
7145
7146        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7147                true /* requireFullPermission */, false /* checkShell */,
7148                "getInstantAppIcon");
7149
7150        synchronized (mPackages) {
7151            return mInstantAppRegistry.getInstantAppIconLPw(
7152                    packageName, userId);
7153        }
7154    }
7155
7156    private boolean isCallerSameApp(String packageName) {
7157        PackageParser.Package pkg = mPackages.get(packageName);
7158        return pkg != null
7159                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7160    }
7161
7162    @Override
7163    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7164        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7165    }
7166
7167    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7168        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7169
7170        // reader
7171        synchronized (mPackages) {
7172            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7173            final int userId = UserHandle.getCallingUserId();
7174            while (i.hasNext()) {
7175                final PackageParser.Package p = i.next();
7176                if (p.applicationInfo == null) continue;
7177
7178                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7179                        && !p.applicationInfo.isDirectBootAware();
7180                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7181                        && p.applicationInfo.isDirectBootAware();
7182
7183                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7184                        && (!mSafeMode || isSystemApp(p))
7185                        && (matchesUnaware || matchesAware)) {
7186                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7187                    if (ps != null) {
7188                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7189                                ps.readUserState(userId), userId);
7190                        if (ai != null) {
7191                            finalList.add(ai);
7192                        }
7193                    }
7194                }
7195            }
7196        }
7197
7198        return finalList;
7199    }
7200
7201    @Override
7202    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7203        if (!sUserManager.exists(userId)) return null;
7204        flags = updateFlagsForComponent(flags, userId, name);
7205        // reader
7206        synchronized (mPackages) {
7207            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7208            PackageSetting ps = provider != null
7209                    ? mSettings.mPackages.get(provider.owner.packageName)
7210                    : null;
7211            return ps != null
7212                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7213                    ? PackageParser.generateProviderInfo(provider, flags,
7214                            ps.readUserState(userId), userId)
7215                    : null;
7216        }
7217    }
7218
7219    /**
7220     * @deprecated
7221     */
7222    @Deprecated
7223    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7224        // reader
7225        synchronized (mPackages) {
7226            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7227                    .entrySet().iterator();
7228            final int userId = UserHandle.getCallingUserId();
7229            while (i.hasNext()) {
7230                Map.Entry<String, PackageParser.Provider> entry = i.next();
7231                PackageParser.Provider p = entry.getValue();
7232                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7233
7234                if (ps != null && p.syncable
7235                        && (!mSafeMode || (p.info.applicationInfo.flags
7236                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7237                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7238                            ps.readUserState(userId), userId);
7239                    if (info != null) {
7240                        outNames.add(entry.getKey());
7241                        outInfo.add(info);
7242                    }
7243                }
7244            }
7245        }
7246    }
7247
7248    @Override
7249    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7250            int uid, int flags) {
7251        final int userId = processName != null ? UserHandle.getUserId(uid)
7252                : UserHandle.getCallingUserId();
7253        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7254        flags = updateFlagsForComponent(flags, userId, processName);
7255
7256        ArrayList<ProviderInfo> finalList = null;
7257        // reader
7258        synchronized (mPackages) {
7259            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7260            while (i.hasNext()) {
7261                final PackageParser.Provider p = i.next();
7262                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7263                if (ps != null && p.info.authority != null
7264                        && (processName == null
7265                                || (p.info.processName.equals(processName)
7266                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7267                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7268                    if (finalList == null) {
7269                        finalList = new ArrayList<ProviderInfo>(3);
7270                    }
7271                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7272                            ps.readUserState(userId), userId);
7273                    if (info != null) {
7274                        finalList.add(info);
7275                    }
7276                }
7277            }
7278        }
7279
7280        if (finalList != null) {
7281            Collections.sort(finalList, mProviderInitOrderSorter);
7282            return new ParceledListSlice<ProviderInfo>(finalList);
7283        }
7284
7285        return ParceledListSlice.emptyList();
7286    }
7287
7288    @Override
7289    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7290        // reader
7291        synchronized (mPackages) {
7292            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7293            return PackageParser.generateInstrumentationInfo(i, flags);
7294        }
7295    }
7296
7297    @Override
7298    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7299            String targetPackage, int flags) {
7300        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7301    }
7302
7303    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7304            int flags) {
7305        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7306
7307        // reader
7308        synchronized (mPackages) {
7309            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7310            while (i.hasNext()) {
7311                final PackageParser.Instrumentation p = i.next();
7312                if (targetPackage == null
7313                        || targetPackage.equals(p.info.targetPackage)) {
7314                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7315                            flags);
7316                    if (ii != null) {
7317                        finalList.add(ii);
7318                    }
7319                }
7320            }
7321        }
7322
7323        return finalList;
7324    }
7325
7326    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7327        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7328        if (overlays == null) {
7329            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7330            return;
7331        }
7332        for (PackageParser.Package opkg : overlays.values()) {
7333            // Not much to do if idmap fails: we already logged the error
7334            // and we certainly don't want to abort installation of pkg simply
7335            // because an overlay didn't fit properly. For these reasons,
7336            // ignore the return value of createIdmapForPackagePairLI.
7337            createIdmapForPackagePairLI(pkg, opkg);
7338        }
7339    }
7340
7341    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7342            PackageParser.Package opkg) {
7343        if (!opkg.mTrustedOverlay) {
7344            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7345                    opkg.baseCodePath + ": overlay not trusted");
7346            return false;
7347        }
7348        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7349        if (overlaySet == null) {
7350            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7351                    opkg.baseCodePath + " but target package has no known overlays");
7352            return false;
7353        }
7354        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7355        // TODO: generate idmap for split APKs
7356        try {
7357            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7358        } catch (InstallerException e) {
7359            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7360                    + opkg.baseCodePath);
7361            return false;
7362        }
7363        PackageParser.Package[] overlayArray =
7364            overlaySet.values().toArray(new PackageParser.Package[0]);
7365        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7366            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7367                return p1.mOverlayPriority - p2.mOverlayPriority;
7368            }
7369        };
7370        Arrays.sort(overlayArray, cmp);
7371
7372        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7373        int i = 0;
7374        for (PackageParser.Package p : overlayArray) {
7375            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7376        }
7377        return true;
7378    }
7379
7380    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7381        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7382        try {
7383            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7384        } finally {
7385            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7386        }
7387    }
7388
7389    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7390        final File[] files = dir.listFiles();
7391        if (ArrayUtils.isEmpty(files)) {
7392            Log.d(TAG, "No files in app dir " + dir);
7393            return;
7394        }
7395
7396        if (DEBUG_PACKAGE_SCANNING) {
7397            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7398                    + " flags=0x" + Integer.toHexString(parseFlags));
7399        }
7400        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7401                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7402
7403        // Submit files for parsing in parallel
7404        int fileCount = 0;
7405        for (File file : files) {
7406            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7407                    && !PackageInstallerService.isStageName(file.getName());
7408            if (!isPackage) {
7409                // Ignore entries which are not packages
7410                continue;
7411            }
7412            parallelPackageParser.submit(file, parseFlags);
7413            fileCount++;
7414        }
7415
7416        // Process results one by one
7417        for (; fileCount > 0; fileCount--) {
7418            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7419            Throwable throwable = parseResult.throwable;
7420            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7421
7422            if (throwable == null) {
7423                // Static shared libraries have synthetic package names
7424                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7425                    renameStaticSharedLibraryPackage(parseResult.pkg);
7426                }
7427                try {
7428                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7429                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7430                                currentTime, null);
7431                    }
7432                } catch (PackageManagerException e) {
7433                    errorCode = e.error;
7434                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7435                }
7436            } else if (throwable instanceof PackageParser.PackageParserException) {
7437                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7438                        throwable;
7439                errorCode = e.error;
7440                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7441            } else {
7442                throw new IllegalStateException("Unexpected exception occurred while parsing "
7443                        + parseResult.scanFile, throwable);
7444            }
7445
7446            // Delete invalid userdata apps
7447            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7448                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7449                logCriticalInfo(Log.WARN,
7450                        "Deleting invalid package at " + parseResult.scanFile);
7451                removeCodePathLI(parseResult.scanFile);
7452            }
7453        }
7454        parallelPackageParser.close();
7455    }
7456
7457    private static File getSettingsProblemFile() {
7458        File dataDir = Environment.getDataDirectory();
7459        File systemDir = new File(dataDir, "system");
7460        File fname = new File(systemDir, "uiderrors.txt");
7461        return fname;
7462    }
7463
7464    static void reportSettingsProblem(int priority, String msg) {
7465        logCriticalInfo(priority, msg);
7466    }
7467
7468    static void logCriticalInfo(int priority, String msg) {
7469        Slog.println(priority, TAG, msg);
7470        EventLogTags.writePmCriticalInfo(msg);
7471        try {
7472            File fname = getSettingsProblemFile();
7473            FileOutputStream out = new FileOutputStream(fname, true);
7474            PrintWriter pw = new FastPrintWriter(out);
7475            SimpleDateFormat formatter = new SimpleDateFormat();
7476            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7477            pw.println(dateString + ": " + msg);
7478            pw.close();
7479            FileUtils.setPermissions(
7480                    fname.toString(),
7481                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7482                    -1, -1);
7483        } catch (java.io.IOException e) {
7484        }
7485    }
7486
7487    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7488        if (srcFile.isDirectory()) {
7489            final File baseFile = new File(pkg.baseCodePath);
7490            long maxModifiedTime = baseFile.lastModified();
7491            if (pkg.splitCodePaths != null) {
7492                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7493                    final File splitFile = new File(pkg.splitCodePaths[i]);
7494                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7495                }
7496            }
7497            return maxModifiedTime;
7498        }
7499        return srcFile.lastModified();
7500    }
7501
7502    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7503            final int policyFlags) throws PackageManagerException {
7504        // When upgrading from pre-N MR1, verify the package time stamp using the package
7505        // directory and not the APK file.
7506        final long lastModifiedTime = mIsPreNMR1Upgrade
7507                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7508        if (ps != null
7509                && ps.codePath.equals(srcFile)
7510                && ps.timeStamp == lastModifiedTime
7511                && !isCompatSignatureUpdateNeeded(pkg)
7512                && !isRecoverSignatureUpdateNeeded(pkg)) {
7513            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7514            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7515            ArraySet<PublicKey> signingKs;
7516            synchronized (mPackages) {
7517                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7518            }
7519            if (ps.signatures.mSignatures != null
7520                    && ps.signatures.mSignatures.length != 0
7521                    && signingKs != null) {
7522                // Optimization: reuse the existing cached certificates
7523                // if the package appears to be unchanged.
7524                pkg.mSignatures = ps.signatures.mSignatures;
7525                pkg.mSigningKeys = signingKs;
7526                return;
7527            }
7528
7529            Slog.w(TAG, "PackageSetting for " + ps.name
7530                    + " is missing signatures.  Collecting certs again to recover them.");
7531        } else {
7532            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7533        }
7534
7535        try {
7536            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7537            PackageParser.collectCertificates(pkg, policyFlags);
7538        } catch (PackageParserException e) {
7539            throw PackageManagerException.from(e);
7540        } finally {
7541            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7542        }
7543    }
7544
7545    /**
7546     *  Traces a package scan.
7547     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7548     */
7549    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7550            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7551        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7552        try {
7553            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7554        } finally {
7555            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7556        }
7557    }
7558
7559    /**
7560     *  Scans a package and returns the newly parsed package.
7561     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7562     */
7563    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7564            long currentTime, UserHandle user) throws PackageManagerException {
7565        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7566        PackageParser pp = new PackageParser();
7567        pp.setSeparateProcesses(mSeparateProcesses);
7568        pp.setOnlyCoreApps(mOnlyCore);
7569        pp.setDisplayMetrics(mMetrics);
7570
7571        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7572            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7573        }
7574
7575        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7576        final PackageParser.Package pkg;
7577        try {
7578            pkg = pp.parsePackage(scanFile, parseFlags);
7579        } catch (PackageParserException e) {
7580            throw PackageManagerException.from(e);
7581        } finally {
7582            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7583        }
7584
7585        // Static shared libraries have synthetic package names
7586        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7587            renameStaticSharedLibraryPackage(pkg);
7588        }
7589
7590        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7591    }
7592
7593    /**
7594     *  Scans a package and returns the newly parsed package.
7595     *  @throws PackageManagerException on a parse error.
7596     */
7597    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7598            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7599            throws PackageManagerException {
7600        // If the package has children and this is the first dive in the function
7601        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7602        // packages (parent and children) would be successfully scanned before the
7603        // actual scan since scanning mutates internal state and we want to atomically
7604        // install the package and its children.
7605        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7606            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7607                scanFlags |= SCAN_CHECK_ONLY;
7608            }
7609        } else {
7610            scanFlags &= ~SCAN_CHECK_ONLY;
7611        }
7612
7613        // Scan the parent
7614        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7615                scanFlags, currentTime, user);
7616
7617        // Scan the children
7618        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7619        for (int i = 0; i < childCount; i++) {
7620            PackageParser.Package childPackage = pkg.childPackages.get(i);
7621            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7622                    currentTime, user);
7623        }
7624
7625
7626        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7627            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7628        }
7629
7630        return scannedPkg;
7631    }
7632
7633    /**
7634     *  Scans a package and returns the newly parsed package.
7635     *  @throws PackageManagerException on a parse error.
7636     */
7637    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7638            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7639            throws PackageManagerException {
7640        PackageSetting ps = null;
7641        PackageSetting updatedPkg;
7642        // reader
7643        synchronized (mPackages) {
7644            // Look to see if we already know about this package.
7645            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7646            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7647                // This package has been renamed to its original name.  Let's
7648                // use that.
7649                ps = mSettings.getPackageLPr(oldName);
7650            }
7651            // If there was no original package, see one for the real package name.
7652            if (ps == null) {
7653                ps = mSettings.getPackageLPr(pkg.packageName);
7654            }
7655            // Check to see if this package could be hiding/updating a system
7656            // package.  Must look for it either under the original or real
7657            // package name depending on our state.
7658            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7659            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7660
7661            // If this is a package we don't know about on the system partition, we
7662            // may need to remove disabled child packages on the system partition
7663            // or may need to not add child packages if the parent apk is updated
7664            // on the data partition and no longer defines this child package.
7665            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7666                // If this is a parent package for an updated system app and this system
7667                // app got an OTA update which no longer defines some of the child packages
7668                // we have to prune them from the disabled system packages.
7669                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7670                if (disabledPs != null) {
7671                    final int scannedChildCount = (pkg.childPackages != null)
7672                            ? pkg.childPackages.size() : 0;
7673                    final int disabledChildCount = disabledPs.childPackageNames != null
7674                            ? disabledPs.childPackageNames.size() : 0;
7675                    for (int i = 0; i < disabledChildCount; i++) {
7676                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7677                        boolean disabledPackageAvailable = false;
7678                        for (int j = 0; j < scannedChildCount; j++) {
7679                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7680                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7681                                disabledPackageAvailable = true;
7682                                break;
7683                            }
7684                         }
7685                         if (!disabledPackageAvailable) {
7686                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7687                         }
7688                    }
7689                }
7690            }
7691        }
7692
7693        boolean updatedPkgBetter = false;
7694        // First check if this is a system package that may involve an update
7695        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7696            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7697            // it needs to drop FLAG_PRIVILEGED.
7698            if (locationIsPrivileged(scanFile)) {
7699                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7700            } else {
7701                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7702            }
7703
7704            if (ps != null && !ps.codePath.equals(scanFile)) {
7705                // The path has changed from what was last scanned...  check the
7706                // version of the new path against what we have stored to determine
7707                // what to do.
7708                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7709                if (pkg.mVersionCode <= ps.versionCode) {
7710                    // The system package has been updated and the code path does not match
7711                    // Ignore entry. Skip it.
7712                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7713                            + " ignored: updated version " + ps.versionCode
7714                            + " better than this " + pkg.mVersionCode);
7715                    if (!updatedPkg.codePath.equals(scanFile)) {
7716                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7717                                + ps.name + " changing from " + updatedPkg.codePathString
7718                                + " to " + scanFile);
7719                        updatedPkg.codePath = scanFile;
7720                        updatedPkg.codePathString = scanFile.toString();
7721                        updatedPkg.resourcePath = scanFile;
7722                        updatedPkg.resourcePathString = scanFile.toString();
7723                    }
7724                    updatedPkg.pkg = pkg;
7725                    updatedPkg.versionCode = pkg.mVersionCode;
7726
7727                    // Update the disabled system child packages to point to the package too.
7728                    final int childCount = updatedPkg.childPackageNames != null
7729                            ? updatedPkg.childPackageNames.size() : 0;
7730                    for (int i = 0; i < childCount; i++) {
7731                        String childPackageName = updatedPkg.childPackageNames.get(i);
7732                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7733                                childPackageName);
7734                        if (updatedChildPkg != null) {
7735                            updatedChildPkg.pkg = pkg;
7736                            updatedChildPkg.versionCode = pkg.mVersionCode;
7737                        }
7738                    }
7739
7740                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7741                            + scanFile + " ignored: updated version " + ps.versionCode
7742                            + " better than this " + pkg.mVersionCode);
7743                } else {
7744                    // The current app on the system partition is better than
7745                    // what we have updated to on the data partition; switch
7746                    // back to the system partition version.
7747                    // At this point, its safely assumed that package installation for
7748                    // apps in system partition will go through. If not there won't be a working
7749                    // version of the app
7750                    // writer
7751                    synchronized (mPackages) {
7752                        // Just remove the loaded entries from package lists.
7753                        mPackages.remove(ps.name);
7754                    }
7755
7756                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7757                            + " reverting from " + ps.codePathString
7758                            + ": new version " + pkg.mVersionCode
7759                            + " better than installed " + ps.versionCode);
7760
7761                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7762                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7763                    synchronized (mInstallLock) {
7764                        args.cleanUpResourcesLI();
7765                    }
7766                    synchronized (mPackages) {
7767                        mSettings.enableSystemPackageLPw(ps.name);
7768                    }
7769                    updatedPkgBetter = true;
7770                }
7771            }
7772        }
7773
7774        if (updatedPkg != null) {
7775            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7776            // initially
7777            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7778
7779            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7780            // flag set initially
7781            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7782                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7783            }
7784        }
7785
7786        // Verify certificates against what was last scanned
7787        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7788
7789        /*
7790         * A new system app appeared, but we already had a non-system one of the
7791         * same name installed earlier.
7792         */
7793        boolean shouldHideSystemApp = false;
7794        if (updatedPkg == null && ps != null
7795                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7796            /*
7797             * Check to make sure the signatures match first. If they don't,
7798             * wipe the installed application and its data.
7799             */
7800            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7801                    != PackageManager.SIGNATURE_MATCH) {
7802                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7803                        + " signatures don't match existing userdata copy; removing");
7804                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7805                        "scanPackageInternalLI")) {
7806                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7807                }
7808                ps = null;
7809            } else {
7810                /*
7811                 * If the newly-added system app is an older version than the
7812                 * already installed version, hide it. It will be scanned later
7813                 * and re-added like an update.
7814                 */
7815                if (pkg.mVersionCode <= ps.versionCode) {
7816                    shouldHideSystemApp = true;
7817                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7818                            + " but new version " + pkg.mVersionCode + " better than installed "
7819                            + ps.versionCode + "; hiding system");
7820                } else {
7821                    /*
7822                     * The newly found system app is a newer version that the
7823                     * one previously installed. Simply remove the
7824                     * already-installed application and replace it with our own
7825                     * while keeping the application data.
7826                     */
7827                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7828                            + " reverting from " + ps.codePathString + ": new version "
7829                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7830                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7831                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7832                    synchronized (mInstallLock) {
7833                        args.cleanUpResourcesLI();
7834                    }
7835                }
7836            }
7837        }
7838
7839        // The apk is forward locked (not public) if its code and resources
7840        // are kept in different files. (except for app in either system or
7841        // vendor path).
7842        // TODO grab this value from PackageSettings
7843        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7844            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7845                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7846            }
7847        }
7848
7849        // TODO: extend to support forward-locked splits
7850        String resourcePath = null;
7851        String baseResourcePath = null;
7852        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7853            if (ps != null && ps.resourcePathString != null) {
7854                resourcePath = ps.resourcePathString;
7855                baseResourcePath = ps.resourcePathString;
7856            } else {
7857                // Should not happen at all. Just log an error.
7858                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7859            }
7860        } else {
7861            resourcePath = pkg.codePath;
7862            baseResourcePath = pkg.baseCodePath;
7863        }
7864
7865        // Set application objects path explicitly.
7866        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7867        pkg.setApplicationInfoCodePath(pkg.codePath);
7868        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7869        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7870        pkg.setApplicationInfoResourcePath(resourcePath);
7871        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7872        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7873
7874        // Note that we invoke the following method only if we are about to unpack an application
7875        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7876                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7877
7878        /*
7879         * If the system app should be overridden by a previously installed
7880         * data, hide the system app now and let the /data/app scan pick it up
7881         * again.
7882         */
7883        if (shouldHideSystemApp) {
7884            synchronized (mPackages) {
7885                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7886            }
7887        }
7888
7889        return scannedPkg;
7890    }
7891
7892    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7893        // Derive the new package synthetic package name
7894        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7895                + pkg.staticSharedLibVersion);
7896    }
7897
7898    private static String fixProcessName(String defProcessName,
7899            String processName) {
7900        if (processName == null) {
7901            return defProcessName;
7902        }
7903        return processName;
7904    }
7905
7906    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7907            throws PackageManagerException {
7908        if (pkgSetting.signatures.mSignatures != null) {
7909            // Already existing package. Make sure signatures match
7910            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7911                    == PackageManager.SIGNATURE_MATCH;
7912            if (!match) {
7913                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7914                        == PackageManager.SIGNATURE_MATCH;
7915            }
7916            if (!match) {
7917                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7918                        == PackageManager.SIGNATURE_MATCH;
7919            }
7920            if (!match) {
7921                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7922                        + pkg.packageName + " signatures do not match the "
7923                        + "previously installed version; ignoring!");
7924            }
7925        }
7926
7927        // Check for shared user signatures
7928        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7929            // Already existing package. Make sure signatures match
7930            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7931                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7932            if (!match) {
7933                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7934                        == PackageManager.SIGNATURE_MATCH;
7935            }
7936            if (!match) {
7937                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7938                        == PackageManager.SIGNATURE_MATCH;
7939            }
7940            if (!match) {
7941                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7942                        "Package " + pkg.packageName
7943                        + " has no signatures that match those in shared user "
7944                        + pkgSetting.sharedUser.name + "; ignoring!");
7945            }
7946        }
7947    }
7948
7949    /**
7950     * Enforces that only the system UID or root's UID can call a method exposed
7951     * via Binder.
7952     *
7953     * @param message used as message if SecurityException is thrown
7954     * @throws SecurityException if the caller is not system or root
7955     */
7956    private static final void enforceSystemOrRoot(String message) {
7957        final int uid = Binder.getCallingUid();
7958        if (uid != Process.SYSTEM_UID && uid != 0) {
7959            throw new SecurityException(message);
7960        }
7961    }
7962
7963    @Override
7964    public void performFstrimIfNeeded() {
7965        enforceSystemOrRoot("Only the system can request fstrim");
7966
7967        // Before everything else, see whether we need to fstrim.
7968        try {
7969            IStorageManager sm = PackageHelper.getStorageManager();
7970            if (sm != null) {
7971                boolean doTrim = false;
7972                final long interval = android.provider.Settings.Global.getLong(
7973                        mContext.getContentResolver(),
7974                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7975                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7976                if (interval > 0) {
7977                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7978                    if (timeSinceLast > interval) {
7979                        doTrim = true;
7980                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7981                                + "; running immediately");
7982                    }
7983                }
7984                if (doTrim) {
7985                    final boolean dexOptDialogShown;
7986                    synchronized (mPackages) {
7987                        dexOptDialogShown = mDexOptDialogShown;
7988                    }
7989                    if (!isFirstBoot() && dexOptDialogShown) {
7990                        try {
7991                            ActivityManager.getService().showBootMessage(
7992                                    mContext.getResources().getString(
7993                                            R.string.android_upgrading_fstrim), true);
7994                        } catch (RemoteException e) {
7995                        }
7996                    }
7997                    sm.runMaintenance();
7998                }
7999            } else {
8000                Slog.e(TAG, "storageManager service unavailable!");
8001            }
8002        } catch (RemoteException e) {
8003            // Can't happen; StorageManagerService is local
8004        }
8005    }
8006
8007    @Override
8008    public void updatePackagesIfNeeded() {
8009        enforceSystemOrRoot("Only the system can request package update");
8010
8011        // We need to re-extract after an OTA.
8012        boolean causeUpgrade = isUpgrade();
8013
8014        // First boot or factory reset.
8015        // Note: we also handle devices that are upgrading to N right now as if it is their
8016        //       first boot, as they do not have profile data.
8017        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8018
8019        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8020        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8021
8022        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8023            return;
8024        }
8025
8026        List<PackageParser.Package> pkgs;
8027        synchronized (mPackages) {
8028            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8029        }
8030
8031        final long startTime = System.nanoTime();
8032        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8033                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8034
8035        final int elapsedTimeSeconds =
8036                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8037
8038        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8039        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8040        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8041        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8042        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8043    }
8044
8045    /**
8046     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8047     * containing statistics about the invocation. The array consists of three elements,
8048     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8049     * and {@code numberOfPackagesFailed}.
8050     */
8051    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8052            String compilerFilter) {
8053
8054        int numberOfPackagesVisited = 0;
8055        int numberOfPackagesOptimized = 0;
8056        int numberOfPackagesSkipped = 0;
8057        int numberOfPackagesFailed = 0;
8058        final int numberOfPackagesToDexopt = pkgs.size();
8059
8060        for (PackageParser.Package pkg : pkgs) {
8061            numberOfPackagesVisited++;
8062
8063            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8064                if (DEBUG_DEXOPT) {
8065                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8066                }
8067                numberOfPackagesSkipped++;
8068                continue;
8069            }
8070
8071            if (DEBUG_DEXOPT) {
8072                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8073                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8074            }
8075
8076            if (showDialog) {
8077                try {
8078                    ActivityManager.getService().showBootMessage(
8079                            mContext.getResources().getString(R.string.android_upgrading_apk,
8080                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8081                } catch (RemoteException e) {
8082                }
8083                synchronized (mPackages) {
8084                    mDexOptDialogShown = true;
8085                }
8086            }
8087
8088            // If the OTA updates a system app which was previously preopted to a non-preopted state
8089            // the app might end up being verified at runtime. That's because by default the apps
8090            // are verify-profile but for preopted apps there's no profile.
8091            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8092            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8093            // filter (by default interpret-only).
8094            // Note that at this stage unused apps are already filtered.
8095            if (isSystemApp(pkg) &&
8096                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8097                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8098                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8099            }
8100
8101            // checkProfiles is false to avoid merging profiles during boot which
8102            // might interfere with background compilation (b/28612421).
8103            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8104            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8105            // trade-off worth doing to save boot time work.
8106            int dexOptStatus = performDexOptTraced(pkg.packageName,
8107                    false /* checkProfiles */,
8108                    compilerFilter,
8109                    false /* force */);
8110            switch (dexOptStatus) {
8111                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8112                    numberOfPackagesOptimized++;
8113                    break;
8114                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8115                    numberOfPackagesSkipped++;
8116                    break;
8117                case PackageDexOptimizer.DEX_OPT_FAILED:
8118                    numberOfPackagesFailed++;
8119                    break;
8120                default:
8121                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8122                    break;
8123            }
8124        }
8125
8126        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8127                numberOfPackagesFailed };
8128    }
8129
8130    @Override
8131    public void notifyPackageUse(String packageName, int reason) {
8132        synchronized (mPackages) {
8133            PackageParser.Package p = mPackages.get(packageName);
8134            if (p == null) {
8135                return;
8136            }
8137            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8138        }
8139    }
8140
8141    @Override
8142    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8143        int userId = UserHandle.getCallingUserId();
8144        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8145        if (ai == null) {
8146            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8147                + loadingPackageName + ", user=" + userId);
8148            return;
8149        }
8150        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8151    }
8152
8153    // TODO: this is not used nor needed. Delete it.
8154    @Override
8155    public boolean performDexOptIfNeeded(String packageName) {
8156        int dexOptStatus = performDexOptTraced(packageName,
8157                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8158        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8159    }
8160
8161    @Override
8162    public boolean performDexOpt(String packageName,
8163            boolean checkProfiles, int compileReason, boolean force) {
8164        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8165                getCompilerFilterForReason(compileReason), force);
8166        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8167    }
8168
8169    @Override
8170    public boolean performDexOptMode(String packageName,
8171            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8172        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8173                targetCompilerFilter, force);
8174        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8175    }
8176
8177    private int performDexOptTraced(String packageName,
8178                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8179        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8180        try {
8181            return performDexOptInternal(packageName, checkProfiles,
8182                    targetCompilerFilter, force);
8183        } finally {
8184            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8185        }
8186    }
8187
8188    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8189    // if the package can now be considered up to date for the given filter.
8190    private int performDexOptInternal(String packageName,
8191                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8192        PackageParser.Package p;
8193        synchronized (mPackages) {
8194            p = mPackages.get(packageName);
8195            if (p == null) {
8196                // Package could not be found. Report failure.
8197                return PackageDexOptimizer.DEX_OPT_FAILED;
8198            }
8199            mPackageUsage.maybeWriteAsync(mPackages);
8200            mCompilerStats.maybeWriteAsync();
8201        }
8202        long callingId = Binder.clearCallingIdentity();
8203        try {
8204            synchronized (mInstallLock) {
8205                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8206                        targetCompilerFilter, force);
8207            }
8208        } finally {
8209            Binder.restoreCallingIdentity(callingId);
8210        }
8211    }
8212
8213    public ArraySet<String> getOptimizablePackages() {
8214        ArraySet<String> pkgs = new ArraySet<String>();
8215        synchronized (mPackages) {
8216            for (PackageParser.Package p : mPackages.values()) {
8217                if (PackageDexOptimizer.canOptimizePackage(p)) {
8218                    pkgs.add(p.packageName);
8219                }
8220            }
8221        }
8222        return pkgs;
8223    }
8224
8225    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8226            boolean checkProfiles, String targetCompilerFilter,
8227            boolean force) {
8228        // Select the dex optimizer based on the force parameter.
8229        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8230        //       allocate an object here.
8231        PackageDexOptimizer pdo = force
8232                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8233                : mPackageDexOptimizer;
8234
8235        // Optimize all dependencies first. Note: we ignore the return value and march on
8236        // on errors.
8237        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8238        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8239        if (!deps.isEmpty()) {
8240            for (PackageParser.Package depPackage : deps) {
8241                // TODO: Analyze and investigate if we (should) profile libraries.
8242                // Currently this will do a full compilation of the library by default.
8243                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8244                        false /* checkProfiles */,
8245                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8246                        getOrCreateCompilerPackageStats(depPackage));
8247            }
8248        }
8249        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8250                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8251    }
8252
8253    // Performs dexopt on the used secondary dex files belonging to the given package.
8254    // Returns true if all dex files were process successfully (which could mean either dexopt or
8255    // skip). Returns false if any of the files caused errors.
8256    @Override
8257    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8258            boolean force) {
8259        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8260    }
8261
8262    /**
8263     * Reconcile the information we have about the secondary dex files belonging to
8264     * {@code packagName} and the actual dex files. For all dex files that were
8265     * deleted, update the internal records and delete the generated oat files.
8266     */
8267    @Override
8268    public void reconcileSecondaryDexFiles(String packageName) {
8269        mDexManager.reconcileSecondaryDexFiles(packageName);
8270    }
8271
8272    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8273    // a reference there.
8274    /*package*/ DexManager getDexManager() {
8275        return mDexManager;
8276    }
8277
8278    /**
8279     * Execute the background dexopt job immediately.
8280     */
8281    @Override
8282    public boolean runBackgroundDexoptJob() {
8283        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8284    }
8285
8286    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8287        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8288                || p.usesStaticLibraries != null) {
8289            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8290            Set<String> collectedNames = new HashSet<>();
8291            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8292
8293            retValue.remove(p);
8294
8295            return retValue;
8296        } else {
8297            return Collections.emptyList();
8298        }
8299    }
8300
8301    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8302            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8303        if (!collectedNames.contains(p.packageName)) {
8304            collectedNames.add(p.packageName);
8305            collected.add(p);
8306
8307            if (p.usesLibraries != null) {
8308                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8309                        null, collected, collectedNames);
8310            }
8311            if (p.usesOptionalLibraries != null) {
8312                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8313                        null, collected, collectedNames);
8314            }
8315            if (p.usesStaticLibraries != null) {
8316                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8317                        p.usesStaticLibrariesVersions, collected, collectedNames);
8318            }
8319        }
8320    }
8321
8322    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8323            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8324        final int libNameCount = libs.size();
8325        for (int i = 0; i < libNameCount; i++) {
8326            String libName = libs.get(i);
8327            int version = (versions != null && versions.length == libNameCount)
8328                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8329            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8330            if (libPkg != null) {
8331                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8332            }
8333        }
8334    }
8335
8336    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8337        synchronized (mPackages) {
8338            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8339            if (libEntry != null) {
8340                return mPackages.get(libEntry.apk);
8341            }
8342            return null;
8343        }
8344    }
8345
8346    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8347        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8348        if (versionedLib == null) {
8349            return null;
8350        }
8351        return versionedLib.get(version);
8352    }
8353
8354    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8355        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8356                pkg.staticSharedLibName);
8357        if (versionedLib == null) {
8358            return null;
8359        }
8360        int previousLibVersion = -1;
8361        final int versionCount = versionedLib.size();
8362        for (int i = 0; i < versionCount; i++) {
8363            final int libVersion = versionedLib.keyAt(i);
8364            if (libVersion < pkg.staticSharedLibVersion) {
8365                previousLibVersion = Math.max(previousLibVersion, libVersion);
8366            }
8367        }
8368        if (previousLibVersion >= 0) {
8369            return versionedLib.get(previousLibVersion);
8370        }
8371        return null;
8372    }
8373
8374    public void shutdown() {
8375        mPackageUsage.writeNow(mPackages);
8376        mCompilerStats.writeNow();
8377    }
8378
8379    @Override
8380    public void dumpProfiles(String packageName) {
8381        PackageParser.Package pkg;
8382        synchronized (mPackages) {
8383            pkg = mPackages.get(packageName);
8384            if (pkg == null) {
8385                throw new IllegalArgumentException("Unknown package: " + packageName);
8386            }
8387        }
8388        /* Only the shell, root, or the app user should be able to dump profiles. */
8389        int callingUid = Binder.getCallingUid();
8390        if (callingUid != Process.SHELL_UID &&
8391            callingUid != Process.ROOT_UID &&
8392            callingUid != pkg.applicationInfo.uid) {
8393            throw new SecurityException("dumpProfiles");
8394        }
8395
8396        synchronized (mInstallLock) {
8397            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8398            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8399            try {
8400                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8401                String codePaths = TextUtils.join(";", allCodePaths);
8402                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8403            } catch (InstallerException e) {
8404                Slog.w(TAG, "Failed to dump profiles", e);
8405            }
8406            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8407        }
8408    }
8409
8410    @Override
8411    public void forceDexOpt(String packageName) {
8412        enforceSystemOrRoot("forceDexOpt");
8413
8414        PackageParser.Package pkg;
8415        synchronized (mPackages) {
8416            pkg = mPackages.get(packageName);
8417            if (pkg == null) {
8418                throw new IllegalArgumentException("Unknown package: " + packageName);
8419            }
8420        }
8421
8422        synchronized (mInstallLock) {
8423            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8424
8425            // Whoever is calling forceDexOpt wants a fully compiled package.
8426            // Don't use profiles since that may cause compilation to be skipped.
8427            final int res = performDexOptInternalWithDependenciesLI(pkg,
8428                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8429                    true /* force */);
8430
8431            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8432            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8433                throw new IllegalStateException("Failed to dexopt: " + res);
8434            }
8435        }
8436    }
8437
8438    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8439        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8440            Slog.w(TAG, "Unable to update from " + oldPkg.name
8441                    + " to " + newPkg.packageName
8442                    + ": old package not in system partition");
8443            return false;
8444        } else if (mPackages.get(oldPkg.name) != null) {
8445            Slog.w(TAG, "Unable to update from " + oldPkg.name
8446                    + " to " + newPkg.packageName
8447                    + ": old package still exists");
8448            return false;
8449        }
8450        return true;
8451    }
8452
8453    void removeCodePathLI(File codePath) {
8454        if (codePath.isDirectory()) {
8455            try {
8456                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8457            } catch (InstallerException e) {
8458                Slog.w(TAG, "Failed to remove code path", e);
8459            }
8460        } else {
8461            codePath.delete();
8462        }
8463    }
8464
8465    private int[] resolveUserIds(int userId) {
8466        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8467    }
8468
8469    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8470        if (pkg == null) {
8471            Slog.wtf(TAG, "Package was null!", new Throwable());
8472            return;
8473        }
8474        clearAppDataLeafLIF(pkg, userId, flags);
8475        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8476        for (int i = 0; i < childCount; i++) {
8477            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8478        }
8479    }
8480
8481    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8482        final PackageSetting ps;
8483        synchronized (mPackages) {
8484            ps = mSettings.mPackages.get(pkg.packageName);
8485        }
8486        for (int realUserId : resolveUserIds(userId)) {
8487            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8488            try {
8489                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8490                        ceDataInode);
8491            } catch (InstallerException e) {
8492                Slog.w(TAG, String.valueOf(e));
8493            }
8494        }
8495    }
8496
8497    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8498        if (pkg == null) {
8499            Slog.wtf(TAG, "Package was null!", new Throwable());
8500            return;
8501        }
8502        destroyAppDataLeafLIF(pkg, userId, flags);
8503        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8504        for (int i = 0; i < childCount; i++) {
8505            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8506        }
8507    }
8508
8509    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8510        final PackageSetting ps;
8511        synchronized (mPackages) {
8512            ps = mSettings.mPackages.get(pkg.packageName);
8513        }
8514        for (int realUserId : resolveUserIds(userId)) {
8515            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8516            try {
8517                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8518                        ceDataInode);
8519            } catch (InstallerException e) {
8520                Slog.w(TAG, String.valueOf(e));
8521            }
8522        }
8523    }
8524
8525    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8526        if (pkg == null) {
8527            Slog.wtf(TAG, "Package was null!", new Throwable());
8528            return;
8529        }
8530        destroyAppProfilesLeafLIF(pkg);
8531        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8532        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8533        for (int i = 0; i < childCount; i++) {
8534            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8535            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8536                    true /* removeBaseMarker */);
8537        }
8538    }
8539
8540    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8541            boolean removeBaseMarker) {
8542        if (pkg.isForwardLocked()) {
8543            return;
8544        }
8545
8546        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8547            try {
8548                path = PackageManagerServiceUtils.realpath(new File(path));
8549            } catch (IOException e) {
8550                // TODO: Should we return early here ?
8551                Slog.w(TAG, "Failed to get canonical path", e);
8552                continue;
8553            }
8554
8555            final String useMarker = path.replace('/', '@');
8556            for (int realUserId : resolveUserIds(userId)) {
8557                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8558                if (removeBaseMarker) {
8559                    File foreignUseMark = new File(profileDir, useMarker);
8560                    if (foreignUseMark.exists()) {
8561                        if (!foreignUseMark.delete()) {
8562                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8563                                    + pkg.packageName);
8564                        }
8565                    }
8566                }
8567
8568                File[] markers = profileDir.listFiles();
8569                if (markers != null) {
8570                    final String searchString = "@" + pkg.packageName + "@";
8571                    // We also delete all markers that contain the package name we're
8572                    // uninstalling. These are associated with secondary dex-files belonging
8573                    // to the package. Reconstructing the path of these dex files is messy
8574                    // in general.
8575                    for (File marker : markers) {
8576                        if (marker.getName().indexOf(searchString) > 0) {
8577                            if (!marker.delete()) {
8578                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8579                                    + pkg.packageName);
8580                            }
8581                        }
8582                    }
8583                }
8584            }
8585        }
8586    }
8587
8588    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8589        try {
8590            mInstaller.destroyAppProfiles(pkg.packageName);
8591        } catch (InstallerException e) {
8592            Slog.w(TAG, String.valueOf(e));
8593        }
8594    }
8595
8596    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8597        if (pkg == null) {
8598            Slog.wtf(TAG, "Package was null!", new Throwable());
8599            return;
8600        }
8601        clearAppProfilesLeafLIF(pkg);
8602        // We don't remove the base foreign use marker when clearing profiles because
8603        // we will rename it when the app is updated. Unlike the actual profile contents,
8604        // the foreign use marker is good across installs.
8605        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8606        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8607        for (int i = 0; i < childCount; i++) {
8608            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8609        }
8610    }
8611
8612    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8613        try {
8614            mInstaller.clearAppProfiles(pkg.packageName);
8615        } catch (InstallerException e) {
8616            Slog.w(TAG, String.valueOf(e));
8617        }
8618    }
8619
8620    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8621            long lastUpdateTime) {
8622        // Set parent install/update time
8623        PackageSetting ps = (PackageSetting) pkg.mExtras;
8624        if (ps != null) {
8625            ps.firstInstallTime = firstInstallTime;
8626            ps.lastUpdateTime = lastUpdateTime;
8627        }
8628        // Set children install/update time
8629        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8630        for (int i = 0; i < childCount; i++) {
8631            PackageParser.Package childPkg = pkg.childPackages.get(i);
8632            ps = (PackageSetting) childPkg.mExtras;
8633            if (ps != null) {
8634                ps.firstInstallTime = firstInstallTime;
8635                ps.lastUpdateTime = lastUpdateTime;
8636            }
8637        }
8638    }
8639
8640    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8641            PackageParser.Package changingLib) {
8642        if (file.path != null) {
8643            usesLibraryFiles.add(file.path);
8644            return;
8645        }
8646        PackageParser.Package p = mPackages.get(file.apk);
8647        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8648            // If we are doing this while in the middle of updating a library apk,
8649            // then we need to make sure to use that new apk for determining the
8650            // dependencies here.  (We haven't yet finished committing the new apk
8651            // to the package manager state.)
8652            if (p == null || p.packageName.equals(changingLib.packageName)) {
8653                p = changingLib;
8654            }
8655        }
8656        if (p != null) {
8657            usesLibraryFiles.addAll(p.getAllCodePaths());
8658        }
8659    }
8660
8661    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8662            PackageParser.Package changingLib) throws PackageManagerException {
8663        if (pkg == null) {
8664            return;
8665        }
8666        ArraySet<String> usesLibraryFiles = null;
8667        if (pkg.usesLibraries != null) {
8668            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8669                    null, null, pkg.packageName, changingLib, true, null);
8670        }
8671        if (pkg.usesStaticLibraries != null) {
8672            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8673                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8674                    pkg.packageName, changingLib, true, usesLibraryFiles);
8675        }
8676        if (pkg.usesOptionalLibraries != null) {
8677            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8678                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8679        }
8680        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8681            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8682        } else {
8683            pkg.usesLibraryFiles = null;
8684        }
8685    }
8686
8687    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8688            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8689            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8690            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8691            throws PackageManagerException {
8692        final int libCount = requestedLibraries.size();
8693        for (int i = 0; i < libCount; i++) {
8694            final String libName = requestedLibraries.get(i);
8695            final int libVersion = requiredVersions != null ? requiredVersions[i]
8696                    : SharedLibraryInfo.VERSION_UNDEFINED;
8697            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8698            if (libEntry == null) {
8699                if (required) {
8700                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8701                            "Package " + packageName + " requires unavailable shared library "
8702                                    + libName + "; failing!");
8703                } else {
8704                    Slog.w(TAG, "Package " + packageName
8705                            + " desires unavailable shared library "
8706                            + libName + "; ignoring!");
8707                }
8708            } else {
8709                if (requiredVersions != null && requiredCertDigests != null) {
8710                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8711                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8712                            "Package " + packageName + " requires unavailable static shared"
8713                                    + " library " + libName + " version "
8714                                    + libEntry.info.getVersion() + "; failing!");
8715                    }
8716
8717                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8718                    if (libPkg == null) {
8719                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8720                                "Package " + packageName + " requires unavailable static shared"
8721                                        + " library; failing!");
8722                    }
8723
8724                    String expectedCertDigest = requiredCertDigests[i];
8725                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8726                                libPkg.mSignatures[0]);
8727                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8728                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8729                                "Package " + packageName + " requires differently signed" +
8730                                        " static shared library; failing!");
8731                    }
8732                }
8733
8734                if (outUsedLibraries == null) {
8735                    outUsedLibraries = new ArraySet<>();
8736                }
8737                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8738            }
8739        }
8740        return outUsedLibraries;
8741    }
8742
8743    private static boolean hasString(List<String> list, List<String> which) {
8744        if (list == null) {
8745            return false;
8746        }
8747        for (int i=list.size()-1; i>=0; i--) {
8748            for (int j=which.size()-1; j>=0; j--) {
8749                if (which.get(j).equals(list.get(i))) {
8750                    return true;
8751                }
8752            }
8753        }
8754        return false;
8755    }
8756
8757    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8758            PackageParser.Package changingPkg) {
8759        ArrayList<PackageParser.Package> res = null;
8760        for (PackageParser.Package pkg : mPackages.values()) {
8761            if (changingPkg != null
8762                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8763                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8764                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8765                            changingPkg.staticSharedLibName)) {
8766                return null;
8767            }
8768            if (res == null) {
8769                res = new ArrayList<>();
8770            }
8771            res.add(pkg);
8772            try {
8773                updateSharedLibrariesLPr(pkg, changingPkg);
8774            } catch (PackageManagerException e) {
8775                // If a system app update or an app and a required lib missing we
8776                // delete the package and for updated system apps keep the data as
8777                // it is better for the user to reinstall than to be in an limbo
8778                // state. Also libs disappearing under an app should never happen
8779                // - just in case.
8780                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8781                    final int flags = pkg.isUpdatedSystemApp()
8782                            ? PackageManager.DELETE_KEEP_DATA : 0;
8783                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8784                            flags , null, true, null);
8785                }
8786                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8787            }
8788        }
8789        return res;
8790    }
8791
8792    /**
8793     * Derive the value of the {@code cpuAbiOverride} based on the provided
8794     * value and an optional stored value from the package settings.
8795     */
8796    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8797        String cpuAbiOverride = null;
8798
8799        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8800            cpuAbiOverride = null;
8801        } else if (abiOverride != null) {
8802            cpuAbiOverride = abiOverride;
8803        } else if (settings != null) {
8804            cpuAbiOverride = settings.cpuAbiOverrideString;
8805        }
8806
8807        return cpuAbiOverride;
8808    }
8809
8810    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8811            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8812                    throws PackageManagerException {
8813        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8814        // If the package has children and this is the first dive in the function
8815        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8816        // whether all packages (parent and children) would be successfully scanned
8817        // before the actual scan since scanning mutates internal state and we want
8818        // to atomically install the package and its children.
8819        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8820            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8821                scanFlags |= SCAN_CHECK_ONLY;
8822            }
8823        } else {
8824            scanFlags &= ~SCAN_CHECK_ONLY;
8825        }
8826
8827        final PackageParser.Package scannedPkg;
8828        try {
8829            // Scan the parent
8830            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8831            // Scan the children
8832            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8833            for (int i = 0; i < childCount; i++) {
8834                PackageParser.Package childPkg = pkg.childPackages.get(i);
8835                scanPackageLI(childPkg, policyFlags,
8836                        scanFlags, currentTime, user);
8837            }
8838        } finally {
8839            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8840        }
8841
8842        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8843            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8844        }
8845
8846        return scannedPkg;
8847    }
8848
8849    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8850            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8851        boolean success = false;
8852        try {
8853            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8854                    currentTime, user);
8855            success = true;
8856            return res;
8857        } finally {
8858            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8859                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8860                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8861                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8862                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8863            }
8864        }
8865    }
8866
8867    /**
8868     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8869     */
8870    private static boolean apkHasCode(String fileName) {
8871        StrictJarFile jarFile = null;
8872        try {
8873            jarFile = new StrictJarFile(fileName,
8874                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8875            return jarFile.findEntry("classes.dex") != null;
8876        } catch (IOException ignore) {
8877        } finally {
8878            try {
8879                if (jarFile != null) {
8880                    jarFile.close();
8881                }
8882            } catch (IOException ignore) {}
8883        }
8884        return false;
8885    }
8886
8887    /**
8888     * Enforces code policy for the package. This ensures that if an APK has
8889     * declared hasCode="true" in its manifest that the APK actually contains
8890     * code.
8891     *
8892     * @throws PackageManagerException If bytecode could not be found when it should exist
8893     */
8894    private static void assertCodePolicy(PackageParser.Package pkg)
8895            throws PackageManagerException {
8896        final boolean shouldHaveCode =
8897                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8898        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8899            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8900                    "Package " + pkg.baseCodePath + " code is missing");
8901        }
8902
8903        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8904            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8905                final boolean splitShouldHaveCode =
8906                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8907                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8908                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8909                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8910                }
8911            }
8912        }
8913    }
8914
8915    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8916            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8917                    throws PackageManagerException {
8918        if (DEBUG_PACKAGE_SCANNING) {
8919            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8920                Log.d(TAG, "Scanning package " + pkg.packageName);
8921        }
8922
8923        applyPolicy(pkg, policyFlags);
8924
8925        assertPackageIsValid(pkg, policyFlags, scanFlags);
8926
8927        // Initialize package source and resource directories
8928        final File scanFile = new File(pkg.codePath);
8929        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8930        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8931
8932        SharedUserSetting suid = null;
8933        PackageSetting pkgSetting = null;
8934
8935        // Getting the package setting may have a side-effect, so if we
8936        // are only checking if scan would succeed, stash a copy of the
8937        // old setting to restore at the end.
8938        PackageSetting nonMutatedPs = null;
8939
8940        // We keep references to the derived CPU Abis from settings in oder to reuse
8941        // them in the case where we're not upgrading or booting for the first time.
8942        String primaryCpuAbiFromSettings = null;
8943        String secondaryCpuAbiFromSettings = null;
8944
8945        // writer
8946        synchronized (mPackages) {
8947            if (pkg.mSharedUserId != null) {
8948                // SIDE EFFECTS; may potentially allocate a new shared user
8949                suid = mSettings.getSharedUserLPw(
8950                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8951                if (DEBUG_PACKAGE_SCANNING) {
8952                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8953                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8954                                + "): packages=" + suid.packages);
8955                }
8956            }
8957
8958            // Check if we are renaming from an original package name.
8959            PackageSetting origPackage = null;
8960            String realName = null;
8961            if (pkg.mOriginalPackages != null) {
8962                // This package may need to be renamed to a previously
8963                // installed name.  Let's check on that...
8964                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8965                if (pkg.mOriginalPackages.contains(renamed)) {
8966                    // This package had originally been installed as the
8967                    // original name, and we have already taken care of
8968                    // transitioning to the new one.  Just update the new
8969                    // one to continue using the old name.
8970                    realName = pkg.mRealPackage;
8971                    if (!pkg.packageName.equals(renamed)) {
8972                        // Callers into this function may have already taken
8973                        // care of renaming the package; only do it here if
8974                        // it is not already done.
8975                        pkg.setPackageName(renamed);
8976                    }
8977                } else {
8978                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8979                        if ((origPackage = mSettings.getPackageLPr(
8980                                pkg.mOriginalPackages.get(i))) != null) {
8981                            // We do have the package already installed under its
8982                            // original name...  should we use it?
8983                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8984                                // New package is not compatible with original.
8985                                origPackage = null;
8986                                continue;
8987                            } else if (origPackage.sharedUser != null) {
8988                                // Make sure uid is compatible between packages.
8989                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8990                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8991                                            + " to " + pkg.packageName + ": old uid "
8992                                            + origPackage.sharedUser.name
8993                                            + " differs from " + pkg.mSharedUserId);
8994                                    origPackage = null;
8995                                    continue;
8996                                }
8997                                // TODO: Add case when shared user id is added [b/28144775]
8998                            } else {
8999                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9000                                        + pkg.packageName + " to old name " + origPackage.name);
9001                            }
9002                            break;
9003                        }
9004                    }
9005                }
9006            }
9007
9008            if (mTransferedPackages.contains(pkg.packageName)) {
9009                Slog.w(TAG, "Package " + pkg.packageName
9010                        + " was transferred to another, but its .apk remains");
9011            }
9012
9013            // See comments in nonMutatedPs declaration
9014            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9015                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9016                if (foundPs != null) {
9017                    nonMutatedPs = new PackageSetting(foundPs);
9018                }
9019            }
9020
9021            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9022                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9023                if (foundPs != null) {
9024                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9025                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9026                }
9027            }
9028
9029            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9030            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9031                PackageManagerService.reportSettingsProblem(Log.WARN,
9032                        "Package " + pkg.packageName + " shared user changed from "
9033                                + (pkgSetting.sharedUser != null
9034                                        ? pkgSetting.sharedUser.name : "<nothing>")
9035                                + " to "
9036                                + (suid != null ? suid.name : "<nothing>")
9037                                + "; replacing with new");
9038                pkgSetting = null;
9039            }
9040            final PackageSetting oldPkgSetting =
9041                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9042            final PackageSetting disabledPkgSetting =
9043                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9044
9045            String[] usesStaticLibraries = null;
9046            if (pkg.usesStaticLibraries != null) {
9047                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9048                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9049            }
9050
9051            if (pkgSetting == null) {
9052                final String parentPackageName = (pkg.parentPackage != null)
9053                        ? pkg.parentPackage.packageName : null;
9054
9055                // REMOVE SharedUserSetting from method; update in a separate call
9056                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9057                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9058                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9059                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9060                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9061                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
9062                        UserManagerService.getInstance(), usesStaticLibraries,
9063                        pkg.usesStaticLibrariesVersions);
9064                // SIDE EFFECTS; updates system state; move elsewhere
9065                if (origPackage != null) {
9066                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9067                }
9068                mSettings.addUserToSettingLPw(pkgSetting);
9069            } else {
9070                // REMOVE SharedUserSetting from method; update in a separate call.
9071                //
9072                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9073                // secondaryCpuAbi are not known at this point so we always update them
9074                // to null here, only to reset them at a later point.
9075                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9076                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9077                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9078                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9079                        UserManagerService.getInstance(), usesStaticLibraries,
9080                        pkg.usesStaticLibrariesVersions);
9081            }
9082            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9083            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9084
9085            // SIDE EFFECTS; modifies system state; move elsewhere
9086            if (pkgSetting.origPackage != null) {
9087                // If we are first transitioning from an original package,
9088                // fix up the new package's name now.  We need to do this after
9089                // looking up the package under its new name, so getPackageLP
9090                // can take care of fiddling things correctly.
9091                pkg.setPackageName(origPackage.name);
9092
9093                // File a report about this.
9094                String msg = "New package " + pkgSetting.realName
9095                        + " renamed to replace old package " + pkgSetting.name;
9096                reportSettingsProblem(Log.WARN, msg);
9097
9098                // Make a note of it.
9099                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9100                    mTransferedPackages.add(origPackage.name);
9101                }
9102
9103                // No longer need to retain this.
9104                pkgSetting.origPackage = null;
9105            }
9106
9107            // SIDE EFFECTS; modifies system state; move elsewhere
9108            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9109                // Make a note of it.
9110                mTransferedPackages.add(pkg.packageName);
9111            }
9112
9113            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9114                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9115            }
9116
9117            if ((scanFlags & SCAN_BOOTING) == 0
9118                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9119                // Check all shared libraries and map to their actual file path.
9120                // We only do this here for apps not on a system dir, because those
9121                // are the only ones that can fail an install due to this.  We
9122                // will take care of the system apps by updating all of their
9123                // library paths after the scan is done. Also during the initial
9124                // scan don't update any libs as we do this wholesale after all
9125                // apps are scanned to avoid dependency based scanning.
9126                updateSharedLibrariesLPr(pkg, null);
9127            }
9128
9129            if (mFoundPolicyFile) {
9130                SELinuxMMAC.assignSeinfoValue(pkg);
9131            }
9132
9133            pkg.applicationInfo.uid = pkgSetting.appId;
9134            pkg.mExtras = pkgSetting;
9135
9136
9137            // Static shared libs have same package with different versions where
9138            // we internally use a synthetic package name to allow multiple versions
9139            // of the same package, therefore we need to compare signatures against
9140            // the package setting for the latest library version.
9141            PackageSetting signatureCheckPs = pkgSetting;
9142            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9143                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9144                if (libraryEntry != null) {
9145                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9146                }
9147            }
9148
9149            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9150                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9151                    // We just determined the app is signed correctly, so bring
9152                    // over the latest parsed certs.
9153                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9154                } else {
9155                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9156                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9157                                "Package " + pkg.packageName + " upgrade keys do not match the "
9158                                + "previously installed version");
9159                    } else {
9160                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9161                        String msg = "System package " + pkg.packageName
9162                                + " signature changed; retaining data.";
9163                        reportSettingsProblem(Log.WARN, msg);
9164                    }
9165                }
9166            } else {
9167                try {
9168                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9169                    verifySignaturesLP(signatureCheckPs, pkg);
9170                    // We just determined the app is signed correctly, so bring
9171                    // over the latest parsed certs.
9172                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9173                } catch (PackageManagerException e) {
9174                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9175                        throw e;
9176                    }
9177                    // The signature has changed, but this package is in the system
9178                    // image...  let's recover!
9179                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9180                    // However...  if this package is part of a shared user, but it
9181                    // doesn't match the signature of the shared user, let's fail.
9182                    // What this means is that you can't change the signatures
9183                    // associated with an overall shared user, which doesn't seem all
9184                    // that unreasonable.
9185                    if (signatureCheckPs.sharedUser != null) {
9186                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9187                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9188                            throw new PackageManagerException(
9189                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9190                                    "Signature mismatch for shared user: "
9191                                            + pkgSetting.sharedUser);
9192                        }
9193                    }
9194                    // File a report about this.
9195                    String msg = "System package " + pkg.packageName
9196                            + " signature changed; retaining data.";
9197                    reportSettingsProblem(Log.WARN, msg);
9198                }
9199            }
9200
9201            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9202                // This package wants to adopt ownership of permissions from
9203                // another package.
9204                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9205                    final String origName = pkg.mAdoptPermissions.get(i);
9206                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9207                    if (orig != null) {
9208                        if (verifyPackageUpdateLPr(orig, pkg)) {
9209                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9210                                    + pkg.packageName);
9211                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9212                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9213                        }
9214                    }
9215                }
9216            }
9217        }
9218
9219        pkg.applicationInfo.processName = fixProcessName(
9220                pkg.applicationInfo.packageName,
9221                pkg.applicationInfo.processName);
9222
9223        if (pkg != mPlatformPackage) {
9224            // Get all of our default paths setup
9225            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9226        }
9227
9228        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9229
9230        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9231            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9232                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9233                derivePackageAbi(
9234                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9235                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9236
9237                // Some system apps still use directory structure for native libraries
9238                // in which case we might end up not detecting abi solely based on apk
9239                // structure. Try to detect abi based on directory structure.
9240                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9241                        pkg.applicationInfo.primaryCpuAbi == null) {
9242                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9243                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9244                }
9245            } else {
9246                // This is not a first boot or an upgrade, don't bother deriving the
9247                // ABI during the scan. Instead, trust the value that was stored in the
9248                // package setting.
9249                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9250                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9251
9252                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9253
9254                if (DEBUG_ABI_SELECTION) {
9255                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9256                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9257                        pkg.applicationInfo.secondaryCpuAbi);
9258                }
9259            }
9260        } else {
9261            if ((scanFlags & SCAN_MOVE) != 0) {
9262                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9263                // but we already have this packages package info in the PackageSetting. We just
9264                // use that and derive the native library path based on the new codepath.
9265                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9266                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9267            }
9268
9269            // Set native library paths again. For moves, the path will be updated based on the
9270            // ABIs we've determined above. For non-moves, the path will be updated based on the
9271            // ABIs we determined during compilation, but the path will depend on the final
9272            // package path (after the rename away from the stage path).
9273            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9274        }
9275
9276        // This is a special case for the "system" package, where the ABI is
9277        // dictated by the zygote configuration (and init.rc). We should keep track
9278        // of this ABI so that we can deal with "normal" applications that run under
9279        // the same UID correctly.
9280        if (mPlatformPackage == pkg) {
9281            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9282                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9283        }
9284
9285        // If there's a mismatch between the abi-override in the package setting
9286        // and the abiOverride specified for the install. Warn about this because we
9287        // would've already compiled the app without taking the package setting into
9288        // account.
9289        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9290            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9291                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9292                        " for package " + pkg.packageName);
9293            }
9294        }
9295
9296        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9297        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9298        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9299
9300        // Copy the derived override back to the parsed package, so that we can
9301        // update the package settings accordingly.
9302        pkg.cpuAbiOverride = cpuAbiOverride;
9303
9304        if (DEBUG_ABI_SELECTION) {
9305            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9306                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9307                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9308        }
9309
9310        // Push the derived path down into PackageSettings so we know what to
9311        // clean up at uninstall time.
9312        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9313
9314        if (DEBUG_ABI_SELECTION) {
9315            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9316                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9317                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9318        }
9319
9320        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9321        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9322            // We don't do this here during boot because we can do it all
9323            // at once after scanning all existing packages.
9324            //
9325            // We also do this *before* we perform dexopt on this package, so that
9326            // we can avoid redundant dexopts, and also to make sure we've got the
9327            // code and package path correct.
9328            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9329        }
9330
9331        if (mFactoryTest && pkg.requestedPermissions.contains(
9332                android.Manifest.permission.FACTORY_TEST)) {
9333            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9334        }
9335
9336        if (isSystemApp(pkg)) {
9337            pkgSetting.isOrphaned = true;
9338        }
9339
9340        // Take care of first install / last update times.
9341        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9342        if (currentTime != 0) {
9343            if (pkgSetting.firstInstallTime == 0) {
9344                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9345            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9346                pkgSetting.lastUpdateTime = currentTime;
9347            }
9348        } else if (pkgSetting.firstInstallTime == 0) {
9349            // We need *something*.  Take time time stamp of the file.
9350            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9351        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9352            if (scanFileTime != pkgSetting.timeStamp) {
9353                // A package on the system image has changed; consider this
9354                // to be an update.
9355                pkgSetting.lastUpdateTime = scanFileTime;
9356            }
9357        }
9358        pkgSetting.setTimeStamp(scanFileTime);
9359
9360        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9361            if (nonMutatedPs != null) {
9362                synchronized (mPackages) {
9363                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9364                }
9365            }
9366        } else {
9367            // Modify state for the given package setting
9368            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9369                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9370            if (isEphemeral(pkg)) {
9371                final int userId = user == null ? 0 : user.getIdentifier();
9372                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9373            }
9374        }
9375        return pkg;
9376    }
9377
9378    /**
9379     * Applies policy to the parsed package based upon the given policy flags.
9380     * Ensures the package is in a good state.
9381     * <p>
9382     * Implementation detail: This method must NOT have any side effect. It would
9383     * ideally be static, but, it requires locks to read system state.
9384     */
9385    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9386        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9387            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9388            if (pkg.applicationInfo.isDirectBootAware()) {
9389                // we're direct boot aware; set for all components
9390                for (PackageParser.Service s : pkg.services) {
9391                    s.info.encryptionAware = s.info.directBootAware = true;
9392                }
9393                for (PackageParser.Provider p : pkg.providers) {
9394                    p.info.encryptionAware = p.info.directBootAware = true;
9395                }
9396                for (PackageParser.Activity a : pkg.activities) {
9397                    a.info.encryptionAware = a.info.directBootAware = true;
9398                }
9399                for (PackageParser.Activity r : pkg.receivers) {
9400                    r.info.encryptionAware = r.info.directBootAware = true;
9401                }
9402            }
9403        } else {
9404            // Only allow system apps to be flagged as core apps.
9405            pkg.coreApp = false;
9406            // clear flags not applicable to regular apps
9407            pkg.applicationInfo.privateFlags &=
9408                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9409            pkg.applicationInfo.privateFlags &=
9410                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9411        }
9412        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9413
9414        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9415            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9416        }
9417
9418        if (!isSystemApp(pkg)) {
9419            // Only system apps can use these features.
9420            pkg.mOriginalPackages = null;
9421            pkg.mRealPackage = null;
9422            pkg.mAdoptPermissions = null;
9423        }
9424    }
9425
9426    /**
9427     * Asserts the parsed package is valid according to the given policy. If the
9428     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9429     * <p>
9430     * Implementation detail: This method must NOT have any side effects. It would
9431     * ideally be static, but, it requires locks to read system state.
9432     *
9433     * @throws PackageManagerException If the package fails any of the validation checks
9434     */
9435    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9436            throws PackageManagerException {
9437        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9438            assertCodePolicy(pkg);
9439        }
9440
9441        if (pkg.applicationInfo.getCodePath() == null ||
9442                pkg.applicationInfo.getResourcePath() == null) {
9443            // Bail out. The resource and code paths haven't been set.
9444            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9445                    "Code and resource paths haven't been set correctly");
9446        }
9447
9448        // Make sure we're not adding any bogus keyset info
9449        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9450        ksms.assertScannedPackageValid(pkg);
9451
9452        synchronized (mPackages) {
9453            // The special "android" package can only be defined once
9454            if (pkg.packageName.equals("android")) {
9455                if (mAndroidApplication != null) {
9456                    Slog.w(TAG, "*************************************************");
9457                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9458                    Slog.w(TAG, " codePath=" + pkg.codePath);
9459                    Slog.w(TAG, "*************************************************");
9460                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9461                            "Core android package being redefined.  Skipping.");
9462                }
9463            }
9464
9465            // A package name must be unique; don't allow duplicates
9466            if (mPackages.containsKey(pkg.packageName)) {
9467                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9468                        "Application package " + pkg.packageName
9469                        + " already installed.  Skipping duplicate.");
9470            }
9471
9472            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9473                // Static libs have a synthetic package name containing the version
9474                // but we still want the base name to be unique.
9475                if (mPackages.containsKey(pkg.manifestPackageName)) {
9476                    throw new PackageManagerException(
9477                            "Duplicate static shared lib provider package");
9478                }
9479
9480                // Static shared libraries should have at least O target SDK
9481                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9482                    throw new PackageManagerException(
9483                            "Packages declaring static-shared libs must target O SDK or higher");
9484                }
9485
9486                // Package declaring static a shared lib cannot be ephemeral
9487                if (pkg.applicationInfo.isInstantApp()) {
9488                    throw new PackageManagerException(
9489                            "Packages declaring static-shared libs cannot be ephemeral");
9490                }
9491
9492                // Package declaring static a shared lib cannot be renamed since the package
9493                // name is synthetic and apps can't code around package manager internals.
9494                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9495                    throw new PackageManagerException(
9496                            "Packages declaring static-shared libs cannot be renamed");
9497                }
9498
9499                // Package declaring static a shared lib cannot declare child packages
9500                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9501                    throw new PackageManagerException(
9502                            "Packages declaring static-shared libs cannot have child packages");
9503                }
9504
9505                // Package declaring static a shared lib cannot declare dynamic libs
9506                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9507                    throw new PackageManagerException(
9508                            "Packages declaring static-shared libs cannot declare dynamic libs");
9509                }
9510
9511                // Package declaring static a shared lib cannot declare shared users
9512                if (pkg.mSharedUserId != null) {
9513                    throw new PackageManagerException(
9514                            "Packages declaring static-shared libs cannot declare shared users");
9515                }
9516
9517                // Static shared libs cannot declare activities
9518                if (!pkg.activities.isEmpty()) {
9519                    throw new PackageManagerException(
9520                            "Static shared libs cannot declare activities");
9521                }
9522
9523                // Static shared libs cannot declare services
9524                if (!pkg.services.isEmpty()) {
9525                    throw new PackageManagerException(
9526                            "Static shared libs cannot declare services");
9527                }
9528
9529                // Static shared libs cannot declare providers
9530                if (!pkg.providers.isEmpty()) {
9531                    throw new PackageManagerException(
9532                            "Static shared libs cannot declare content providers");
9533                }
9534
9535                // Static shared libs cannot declare receivers
9536                if (!pkg.receivers.isEmpty()) {
9537                    throw new PackageManagerException(
9538                            "Static shared libs cannot declare broadcast receivers");
9539                }
9540
9541                // Static shared libs cannot declare permission groups
9542                if (!pkg.permissionGroups.isEmpty()) {
9543                    throw new PackageManagerException(
9544                            "Static shared libs cannot declare permission groups");
9545                }
9546
9547                // Static shared libs cannot declare permissions
9548                if (!pkg.permissions.isEmpty()) {
9549                    throw new PackageManagerException(
9550                            "Static shared libs cannot declare permissions");
9551                }
9552
9553                // Static shared libs cannot declare protected broadcasts
9554                if (pkg.protectedBroadcasts != null) {
9555                    throw new PackageManagerException(
9556                            "Static shared libs cannot declare protected broadcasts");
9557                }
9558
9559                // Static shared libs cannot be overlay targets
9560                if (pkg.mOverlayTarget != null) {
9561                    throw new PackageManagerException(
9562                            "Static shared libs cannot be overlay targets");
9563                }
9564
9565                // The version codes must be ordered as lib versions
9566                int minVersionCode = Integer.MIN_VALUE;
9567                int maxVersionCode = Integer.MAX_VALUE;
9568
9569                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9570                        pkg.staticSharedLibName);
9571                if (versionedLib != null) {
9572                    final int versionCount = versionedLib.size();
9573                    for (int i = 0; i < versionCount; i++) {
9574                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9575                        // TODO: We will change version code to long, so in the new API it is long
9576                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9577                                .getVersionCode();
9578                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9579                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9580                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9581                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9582                        } else {
9583                            minVersionCode = maxVersionCode = libVersionCode;
9584                            break;
9585                        }
9586                    }
9587                }
9588                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9589                    throw new PackageManagerException("Static shared"
9590                            + " lib version codes must be ordered as lib versions");
9591                }
9592            }
9593
9594            // Only privileged apps and updated privileged apps can add child packages.
9595            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9596                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9597                    throw new PackageManagerException("Only privileged apps can add child "
9598                            + "packages. Ignoring package " + pkg.packageName);
9599                }
9600                final int childCount = pkg.childPackages.size();
9601                for (int i = 0; i < childCount; i++) {
9602                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9603                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9604                            childPkg.packageName)) {
9605                        throw new PackageManagerException("Can't override child of "
9606                                + "another disabled app. Ignoring package " + pkg.packageName);
9607                    }
9608                }
9609            }
9610
9611            // If we're only installing presumed-existing packages, require that the
9612            // scanned APK is both already known and at the path previously established
9613            // for it.  Previously unknown packages we pick up normally, but if we have an
9614            // a priori expectation about this package's install presence, enforce it.
9615            // With a singular exception for new system packages. When an OTA contains
9616            // a new system package, we allow the codepath to change from a system location
9617            // to the user-installed location. If we don't allow this change, any newer,
9618            // user-installed version of the application will be ignored.
9619            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9620                if (mExpectingBetter.containsKey(pkg.packageName)) {
9621                    logCriticalInfo(Log.WARN,
9622                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9623                } else {
9624                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9625                    if (known != null) {
9626                        if (DEBUG_PACKAGE_SCANNING) {
9627                            Log.d(TAG, "Examining " + pkg.codePath
9628                                    + " and requiring known paths " + known.codePathString
9629                                    + " & " + known.resourcePathString);
9630                        }
9631                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9632                                || !pkg.applicationInfo.getResourcePath().equals(
9633                                        known.resourcePathString)) {
9634                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9635                                    "Application package " + pkg.packageName
9636                                    + " found at " + pkg.applicationInfo.getCodePath()
9637                                    + " but expected at " + known.codePathString
9638                                    + "; ignoring.");
9639                        }
9640                    }
9641                }
9642            }
9643
9644            // Verify that this new package doesn't have any content providers
9645            // that conflict with existing packages.  Only do this if the
9646            // package isn't already installed, since we don't want to break
9647            // things that are installed.
9648            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9649                final int N = pkg.providers.size();
9650                int i;
9651                for (i=0; i<N; i++) {
9652                    PackageParser.Provider p = pkg.providers.get(i);
9653                    if (p.info.authority != null) {
9654                        String names[] = p.info.authority.split(";");
9655                        for (int j = 0; j < names.length; j++) {
9656                            if (mProvidersByAuthority.containsKey(names[j])) {
9657                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9658                                final String otherPackageName =
9659                                        ((other != null && other.getComponentName() != null) ?
9660                                                other.getComponentName().getPackageName() : "?");
9661                                throw new PackageManagerException(
9662                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9663                                        "Can't install because provider name " + names[j]
9664                                                + " (in package " + pkg.applicationInfo.packageName
9665                                                + ") is already used by " + otherPackageName);
9666                            }
9667                        }
9668                    }
9669                }
9670            }
9671        }
9672    }
9673
9674    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9675            int type, String declaringPackageName, int declaringVersionCode) {
9676        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9677        if (versionedLib == null) {
9678            versionedLib = new SparseArray<>();
9679            mSharedLibraries.put(name, versionedLib);
9680            if (type == SharedLibraryInfo.TYPE_STATIC) {
9681                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9682            }
9683        } else if (versionedLib.indexOfKey(version) >= 0) {
9684            return false;
9685        }
9686        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9687                version, type, declaringPackageName, declaringVersionCode);
9688        versionedLib.put(version, libEntry);
9689        return true;
9690    }
9691
9692    private boolean removeSharedLibraryLPw(String name, int version) {
9693        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9694        if (versionedLib == null) {
9695            return false;
9696        }
9697        final int libIdx = versionedLib.indexOfKey(version);
9698        if (libIdx < 0) {
9699            return false;
9700        }
9701        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9702        versionedLib.remove(version);
9703        if (versionedLib.size() <= 0) {
9704            mSharedLibraries.remove(name);
9705            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9706                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9707                        .getPackageName());
9708            }
9709        }
9710        return true;
9711    }
9712
9713    /**
9714     * Adds a scanned package to the system. When this method is finished, the package will
9715     * be available for query, resolution, etc...
9716     */
9717    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9718            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9719        final String pkgName = pkg.packageName;
9720        if (mCustomResolverComponentName != null &&
9721                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9722            setUpCustomResolverActivity(pkg);
9723        }
9724
9725        if (pkg.packageName.equals("android")) {
9726            synchronized (mPackages) {
9727                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9728                    // Set up information for our fall-back user intent resolution activity.
9729                    mPlatformPackage = pkg;
9730                    pkg.mVersionCode = mSdkVersion;
9731                    mAndroidApplication = pkg.applicationInfo;
9732
9733                    if (!mResolverReplaced) {
9734                        mResolveActivity.applicationInfo = mAndroidApplication;
9735                        mResolveActivity.name = ResolverActivity.class.getName();
9736                        mResolveActivity.packageName = mAndroidApplication.packageName;
9737                        mResolveActivity.processName = "system:ui";
9738                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9739                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9740                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9741                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9742                        mResolveActivity.exported = true;
9743                        mResolveActivity.enabled = true;
9744                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9745                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9746                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9747                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9748                                | ActivityInfo.CONFIG_ORIENTATION
9749                                | ActivityInfo.CONFIG_KEYBOARD
9750                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9751                        mResolveInfo.activityInfo = mResolveActivity;
9752                        mResolveInfo.priority = 0;
9753                        mResolveInfo.preferredOrder = 0;
9754                        mResolveInfo.match = 0;
9755                        mResolveComponentName = new ComponentName(
9756                                mAndroidApplication.packageName, mResolveActivity.name);
9757                    }
9758                }
9759            }
9760        }
9761
9762        ArrayList<PackageParser.Package> clientLibPkgs = null;
9763        // writer
9764        synchronized (mPackages) {
9765            boolean hasStaticSharedLibs = false;
9766
9767            // Any app can add new static shared libraries
9768            if (pkg.staticSharedLibName != null) {
9769                // Static shared libs don't allow renaming as they have synthetic package
9770                // names to allow install of multiple versions, so use name from manifest.
9771                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9772                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9773                        pkg.manifestPackageName, pkg.mVersionCode)) {
9774                    hasStaticSharedLibs = true;
9775                } else {
9776                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9777                                + pkg.staticSharedLibName + " already exists; skipping");
9778                }
9779                // Static shared libs cannot be updated once installed since they
9780                // use synthetic package name which includes the version code, so
9781                // not need to update other packages's shared lib dependencies.
9782            }
9783
9784            if (!hasStaticSharedLibs
9785                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9786                // Only system apps can add new dynamic shared libraries.
9787                if (pkg.libraryNames != null) {
9788                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9789                        String name = pkg.libraryNames.get(i);
9790                        boolean allowed = false;
9791                        if (pkg.isUpdatedSystemApp()) {
9792                            // New library entries can only be added through the
9793                            // system image.  This is important to get rid of a lot
9794                            // of nasty edge cases: for example if we allowed a non-
9795                            // system update of the app to add a library, then uninstalling
9796                            // the update would make the library go away, and assumptions
9797                            // we made such as through app install filtering would now
9798                            // have allowed apps on the device which aren't compatible
9799                            // with it.  Better to just have the restriction here, be
9800                            // conservative, and create many fewer cases that can negatively
9801                            // impact the user experience.
9802                            final PackageSetting sysPs = mSettings
9803                                    .getDisabledSystemPkgLPr(pkg.packageName);
9804                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9805                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9806                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9807                                        allowed = true;
9808                                        break;
9809                                    }
9810                                }
9811                            }
9812                        } else {
9813                            allowed = true;
9814                        }
9815                        if (allowed) {
9816                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9817                                    SharedLibraryInfo.VERSION_UNDEFINED,
9818                                    SharedLibraryInfo.TYPE_DYNAMIC,
9819                                    pkg.packageName, pkg.mVersionCode)) {
9820                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9821                                        + name + " already exists; skipping");
9822                            }
9823                        } else {
9824                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9825                                    + name + " that is not declared on system image; skipping");
9826                        }
9827                    }
9828
9829                    if ((scanFlags & SCAN_BOOTING) == 0) {
9830                        // If we are not booting, we need to update any applications
9831                        // that are clients of our shared library.  If we are booting,
9832                        // this will all be done once the scan is complete.
9833                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9834                    }
9835                }
9836            }
9837        }
9838
9839        if ((scanFlags & SCAN_BOOTING) != 0) {
9840            // No apps can run during boot scan, so they don't need to be frozen
9841        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9842            // Caller asked to not kill app, so it's probably not frozen
9843        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9844            // Caller asked us to ignore frozen check for some reason; they
9845            // probably didn't know the package name
9846        } else {
9847            // We're doing major surgery on this package, so it better be frozen
9848            // right now to keep it from launching
9849            checkPackageFrozen(pkgName);
9850        }
9851
9852        // Also need to kill any apps that are dependent on the library.
9853        if (clientLibPkgs != null) {
9854            for (int i=0; i<clientLibPkgs.size(); i++) {
9855                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9856                killApplication(clientPkg.applicationInfo.packageName,
9857                        clientPkg.applicationInfo.uid, "update lib");
9858            }
9859        }
9860
9861        // writer
9862        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9863
9864        boolean createIdmapFailed = false;
9865        synchronized (mPackages) {
9866            // We don't expect installation to fail beyond this point
9867
9868            if (pkgSetting.pkg != null) {
9869                // Note that |user| might be null during the initial boot scan. If a codePath
9870                // for an app has changed during a boot scan, it's due to an app update that's
9871                // part of the system partition and marker changes must be applied to all users.
9872                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9873                final int[] userIds = resolveUserIds(userId);
9874                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9875            }
9876
9877            // Add the new setting to mSettings
9878            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9879            // Add the new setting to mPackages
9880            mPackages.put(pkg.applicationInfo.packageName, pkg);
9881            // Make sure we don't accidentally delete its data.
9882            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9883            while (iter.hasNext()) {
9884                PackageCleanItem item = iter.next();
9885                if (pkgName.equals(item.packageName)) {
9886                    iter.remove();
9887                }
9888            }
9889
9890            // Add the package's KeySets to the global KeySetManagerService
9891            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9892            ksms.addScannedPackageLPw(pkg);
9893
9894            int N = pkg.providers.size();
9895            StringBuilder r = null;
9896            int i;
9897            for (i=0; i<N; i++) {
9898                PackageParser.Provider p = pkg.providers.get(i);
9899                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9900                        p.info.processName);
9901                mProviders.addProvider(p);
9902                p.syncable = p.info.isSyncable;
9903                if (p.info.authority != null) {
9904                    String names[] = p.info.authority.split(";");
9905                    p.info.authority = null;
9906                    for (int j = 0; j < names.length; j++) {
9907                        if (j == 1 && p.syncable) {
9908                            // We only want the first authority for a provider to possibly be
9909                            // syncable, so if we already added this provider using a different
9910                            // authority clear the syncable flag. We copy the provider before
9911                            // changing it because the mProviders object contains a reference
9912                            // to a provider that we don't want to change.
9913                            // Only do this for the second authority since the resulting provider
9914                            // object can be the same for all future authorities for this provider.
9915                            p = new PackageParser.Provider(p);
9916                            p.syncable = false;
9917                        }
9918                        if (!mProvidersByAuthority.containsKey(names[j])) {
9919                            mProvidersByAuthority.put(names[j], p);
9920                            if (p.info.authority == null) {
9921                                p.info.authority = names[j];
9922                            } else {
9923                                p.info.authority = p.info.authority + ";" + names[j];
9924                            }
9925                            if (DEBUG_PACKAGE_SCANNING) {
9926                                if (chatty)
9927                                    Log.d(TAG, "Registered content provider: " + names[j]
9928                                            + ", className = " + p.info.name + ", isSyncable = "
9929                                            + p.info.isSyncable);
9930                            }
9931                        } else {
9932                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9933                            Slog.w(TAG, "Skipping provider name " + names[j] +
9934                                    " (in package " + pkg.applicationInfo.packageName +
9935                                    "): name already used by "
9936                                    + ((other != null && other.getComponentName() != null)
9937                                            ? other.getComponentName().getPackageName() : "?"));
9938                        }
9939                    }
9940                }
9941                if (chatty) {
9942                    if (r == null) {
9943                        r = new StringBuilder(256);
9944                    } else {
9945                        r.append(' ');
9946                    }
9947                    r.append(p.info.name);
9948                }
9949            }
9950            if (r != null) {
9951                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9952            }
9953
9954            N = pkg.services.size();
9955            r = null;
9956            for (i=0; i<N; i++) {
9957                PackageParser.Service s = pkg.services.get(i);
9958                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9959                        s.info.processName);
9960                mServices.addService(s);
9961                if (chatty) {
9962                    if (r == null) {
9963                        r = new StringBuilder(256);
9964                    } else {
9965                        r.append(' ');
9966                    }
9967                    r.append(s.info.name);
9968                }
9969            }
9970            if (r != null) {
9971                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9972            }
9973
9974            N = pkg.receivers.size();
9975            r = null;
9976            for (i=0; i<N; i++) {
9977                PackageParser.Activity a = pkg.receivers.get(i);
9978                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9979                        a.info.processName);
9980                mReceivers.addActivity(a, "receiver");
9981                if (chatty) {
9982                    if (r == null) {
9983                        r = new StringBuilder(256);
9984                    } else {
9985                        r.append(' ');
9986                    }
9987                    r.append(a.info.name);
9988                }
9989            }
9990            if (r != null) {
9991                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9992            }
9993
9994            N = pkg.activities.size();
9995            r = null;
9996            for (i=0; i<N; i++) {
9997                PackageParser.Activity a = pkg.activities.get(i);
9998                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9999                        a.info.processName);
10000                mActivities.addActivity(a, "activity");
10001                if (chatty) {
10002                    if (r == null) {
10003                        r = new StringBuilder(256);
10004                    } else {
10005                        r.append(' ');
10006                    }
10007                    r.append(a.info.name);
10008                }
10009            }
10010            if (r != null) {
10011                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10012            }
10013
10014            N = pkg.permissionGroups.size();
10015            r = null;
10016            for (i=0; i<N; i++) {
10017                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10018                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10019                final String curPackageName = cur == null ? null : cur.info.packageName;
10020                // Dont allow ephemeral apps to define new permission groups.
10021                if (pkg.applicationInfo.isInstantApp()) {
10022                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10023                            + pg.info.packageName
10024                            + " ignored: ephemeral apps cannot define new permission groups.");
10025                    continue;
10026                }
10027                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10028                if (cur == null || isPackageUpdate) {
10029                    mPermissionGroups.put(pg.info.name, pg);
10030                    if (chatty) {
10031                        if (r == null) {
10032                            r = new StringBuilder(256);
10033                        } else {
10034                            r.append(' ');
10035                        }
10036                        if (isPackageUpdate) {
10037                            r.append("UPD:");
10038                        }
10039                        r.append(pg.info.name);
10040                    }
10041                } else {
10042                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10043                            + pg.info.packageName + " ignored: original from "
10044                            + cur.info.packageName);
10045                    if (chatty) {
10046                        if (r == null) {
10047                            r = new StringBuilder(256);
10048                        } else {
10049                            r.append(' ');
10050                        }
10051                        r.append("DUP:");
10052                        r.append(pg.info.name);
10053                    }
10054                }
10055            }
10056            if (r != null) {
10057                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10058            }
10059
10060            N = pkg.permissions.size();
10061            r = null;
10062            for (i=0; i<N; i++) {
10063                PackageParser.Permission p = pkg.permissions.get(i);
10064
10065                // Dont allow ephemeral apps to define new permissions.
10066                if (pkg.applicationInfo.isInstantApp()) {
10067                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10068                            + p.info.packageName
10069                            + " ignored: ephemeral apps cannot define new permissions.");
10070                    continue;
10071                }
10072
10073                // Assume by default that we did not install this permission into the system.
10074                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10075
10076                // Now that permission groups have a special meaning, we ignore permission
10077                // groups for legacy apps to prevent unexpected behavior. In particular,
10078                // permissions for one app being granted to someone just becase they happen
10079                // to be in a group defined by another app (before this had no implications).
10080                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10081                    p.group = mPermissionGroups.get(p.info.group);
10082                    // Warn for a permission in an unknown group.
10083                    if (p.info.group != null && p.group == null) {
10084                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10085                                + p.info.packageName + " in an unknown group " + p.info.group);
10086                    }
10087                }
10088
10089                ArrayMap<String, BasePermission> permissionMap =
10090                        p.tree ? mSettings.mPermissionTrees
10091                                : mSettings.mPermissions;
10092                BasePermission bp = permissionMap.get(p.info.name);
10093
10094                // Allow system apps to redefine non-system permissions
10095                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10096                    final boolean currentOwnerIsSystem = (bp.perm != null
10097                            && isSystemApp(bp.perm.owner));
10098                    if (isSystemApp(p.owner)) {
10099                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10100                            // It's a built-in permission and no owner, take ownership now
10101                            bp.packageSetting = pkgSetting;
10102                            bp.perm = p;
10103                            bp.uid = pkg.applicationInfo.uid;
10104                            bp.sourcePackage = p.info.packageName;
10105                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10106                        } else if (!currentOwnerIsSystem) {
10107                            String msg = "New decl " + p.owner + " of permission  "
10108                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10109                            reportSettingsProblem(Log.WARN, msg);
10110                            bp = null;
10111                        }
10112                    }
10113                }
10114
10115                if (bp == null) {
10116                    bp = new BasePermission(p.info.name, p.info.packageName,
10117                            BasePermission.TYPE_NORMAL);
10118                    permissionMap.put(p.info.name, bp);
10119                }
10120
10121                if (bp.perm == null) {
10122                    if (bp.sourcePackage == null
10123                            || bp.sourcePackage.equals(p.info.packageName)) {
10124                        BasePermission tree = findPermissionTreeLP(p.info.name);
10125                        if (tree == null
10126                                || tree.sourcePackage.equals(p.info.packageName)) {
10127                            bp.packageSetting = pkgSetting;
10128                            bp.perm = p;
10129                            bp.uid = pkg.applicationInfo.uid;
10130                            bp.sourcePackage = p.info.packageName;
10131                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10132                            if (chatty) {
10133                                if (r == null) {
10134                                    r = new StringBuilder(256);
10135                                } else {
10136                                    r.append(' ');
10137                                }
10138                                r.append(p.info.name);
10139                            }
10140                        } else {
10141                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10142                                    + p.info.packageName + " ignored: base tree "
10143                                    + tree.name + " is from package "
10144                                    + tree.sourcePackage);
10145                        }
10146                    } else {
10147                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10148                                + p.info.packageName + " ignored: original from "
10149                                + bp.sourcePackage);
10150                    }
10151                } else if (chatty) {
10152                    if (r == null) {
10153                        r = new StringBuilder(256);
10154                    } else {
10155                        r.append(' ');
10156                    }
10157                    r.append("DUP:");
10158                    r.append(p.info.name);
10159                }
10160                if (bp.perm == p) {
10161                    bp.protectionLevel = p.info.protectionLevel;
10162                }
10163            }
10164
10165            if (r != null) {
10166                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10167            }
10168
10169            N = pkg.instrumentation.size();
10170            r = null;
10171            for (i=0; i<N; i++) {
10172                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10173                a.info.packageName = pkg.applicationInfo.packageName;
10174                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10175                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10176                a.info.splitNames = pkg.splitNames;
10177                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10178                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10179                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10180                a.info.dataDir = pkg.applicationInfo.dataDir;
10181                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10182                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10183                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10184                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10185                mInstrumentation.put(a.getComponentName(), a);
10186                if (chatty) {
10187                    if (r == null) {
10188                        r = new StringBuilder(256);
10189                    } else {
10190                        r.append(' ');
10191                    }
10192                    r.append(a.info.name);
10193                }
10194            }
10195            if (r != null) {
10196                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10197            }
10198
10199            if (pkg.protectedBroadcasts != null) {
10200                N = pkg.protectedBroadcasts.size();
10201                for (i=0; i<N; i++) {
10202                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10203                }
10204            }
10205
10206            // Create idmap files for pairs of (packages, overlay packages).
10207            // Note: "android", ie framework-res.apk, is handled by native layers.
10208            if (pkg.mOverlayTarget != null) {
10209                // This is an overlay package.
10210                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10211                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10212                        mOverlays.put(pkg.mOverlayTarget,
10213                                new ArrayMap<String, PackageParser.Package>());
10214                    }
10215                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10216                    map.put(pkg.packageName, pkg);
10217                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10218                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10219                        createIdmapFailed = true;
10220                    }
10221                }
10222            } else if (mOverlays.containsKey(pkg.packageName) &&
10223                    !pkg.packageName.equals("android")) {
10224                // This is a regular package, with one or more known overlay packages.
10225                createIdmapsForPackageLI(pkg);
10226            }
10227        }
10228
10229        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10230
10231        if (createIdmapFailed) {
10232            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10233                    "scanPackageLI failed to createIdmap");
10234        }
10235    }
10236
10237    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10238            PackageParser.Package update, int[] userIds) {
10239        if (existing.applicationInfo == null || update.applicationInfo == null) {
10240            // This isn't due to an app installation.
10241            return;
10242        }
10243
10244        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10245        final File newCodePath = new File(update.applicationInfo.getCodePath());
10246
10247        // The codePath hasn't changed, so there's nothing for us to do.
10248        if (Objects.equals(oldCodePath, newCodePath)) {
10249            return;
10250        }
10251
10252        File canonicalNewCodePath;
10253        try {
10254            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10255        } catch (IOException e) {
10256            Slog.w(TAG, "Failed to get canonical path.", e);
10257            return;
10258        }
10259
10260        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10261        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10262        // that the last component of the path (i.e, the name) doesn't need canonicalization
10263        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10264        // but may change in the future. Hopefully this function won't exist at that point.
10265        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10266                oldCodePath.getName());
10267
10268        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10269        // with "@".
10270        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10271        if (!oldMarkerPrefix.endsWith("@")) {
10272            oldMarkerPrefix += "@";
10273        }
10274        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10275        if (!newMarkerPrefix.endsWith("@")) {
10276            newMarkerPrefix += "@";
10277        }
10278
10279        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10280        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10281        for (String updatedPath : updatedPaths) {
10282            String updatedPathName = new File(updatedPath).getName();
10283            markerSuffixes.add(updatedPathName.replace('/', '@'));
10284        }
10285
10286        for (int userId : userIds) {
10287            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10288
10289            for (String markerSuffix : markerSuffixes) {
10290                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10291                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10292                if (oldForeignUseMark.exists()) {
10293                    try {
10294                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10295                                newForeignUseMark.getAbsolutePath());
10296                    } catch (ErrnoException e) {
10297                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10298                        oldForeignUseMark.delete();
10299                    }
10300                }
10301            }
10302        }
10303    }
10304
10305    /**
10306     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10307     * is derived purely on the basis of the contents of {@code scanFile} and
10308     * {@code cpuAbiOverride}.
10309     *
10310     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10311     */
10312    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10313                                 String cpuAbiOverride, boolean extractLibs,
10314                                 File appLib32InstallDir)
10315            throws PackageManagerException {
10316        // Give ourselves some initial paths; we'll come back for another
10317        // pass once we've determined ABI below.
10318        setNativeLibraryPaths(pkg, appLib32InstallDir);
10319
10320        // We would never need to extract libs for forward-locked and external packages,
10321        // since the container service will do it for us. We shouldn't attempt to
10322        // extract libs from system app when it was not updated.
10323        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10324                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10325            extractLibs = false;
10326        }
10327
10328        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10329        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10330
10331        NativeLibraryHelper.Handle handle = null;
10332        try {
10333            handle = NativeLibraryHelper.Handle.create(pkg);
10334            // TODO(multiArch): This can be null for apps that didn't go through the
10335            // usual installation process. We can calculate it again, like we
10336            // do during install time.
10337            //
10338            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10339            // unnecessary.
10340            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10341
10342            // Null out the abis so that they can be recalculated.
10343            pkg.applicationInfo.primaryCpuAbi = null;
10344            pkg.applicationInfo.secondaryCpuAbi = null;
10345            if (isMultiArch(pkg.applicationInfo)) {
10346                // Warn if we've set an abiOverride for multi-lib packages..
10347                // By definition, we need to copy both 32 and 64 bit libraries for
10348                // such packages.
10349                if (pkg.cpuAbiOverride != null
10350                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10351                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10352                }
10353
10354                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10355                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10356                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10357                    if (extractLibs) {
10358                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10359                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10360                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10361                                useIsaSpecificSubdirs);
10362                    } else {
10363                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10364                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10365                    }
10366                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10367                }
10368
10369                maybeThrowExceptionForMultiArchCopy(
10370                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10371
10372                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10373                    if (extractLibs) {
10374                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10375                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10376                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10377                                useIsaSpecificSubdirs);
10378                    } else {
10379                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10380                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10381                    }
10382                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10383                }
10384
10385                maybeThrowExceptionForMultiArchCopy(
10386                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10387
10388                if (abi64 >= 0) {
10389                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10390                }
10391
10392                if (abi32 >= 0) {
10393                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10394                    if (abi64 >= 0) {
10395                        if (pkg.use32bitAbi) {
10396                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10397                            pkg.applicationInfo.primaryCpuAbi = abi;
10398                        } else {
10399                            pkg.applicationInfo.secondaryCpuAbi = abi;
10400                        }
10401                    } else {
10402                        pkg.applicationInfo.primaryCpuAbi = abi;
10403                    }
10404                }
10405
10406            } else {
10407                String[] abiList = (cpuAbiOverride != null) ?
10408                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10409
10410                // Enable gross and lame hacks for apps that are built with old
10411                // SDK tools. We must scan their APKs for renderscript bitcode and
10412                // not launch them if it's present. Don't bother checking on devices
10413                // that don't have 64 bit support.
10414                boolean needsRenderScriptOverride = false;
10415                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10416                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10417                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10418                    needsRenderScriptOverride = true;
10419                }
10420
10421                final int copyRet;
10422                if (extractLibs) {
10423                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10424                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10425                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10426                } else {
10427                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10428                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10429                }
10430                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10431
10432                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10433                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10434                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10435                }
10436
10437                if (copyRet >= 0) {
10438                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10439                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10440                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10441                } else if (needsRenderScriptOverride) {
10442                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10443                }
10444            }
10445        } catch (IOException ioe) {
10446            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10447        } finally {
10448            IoUtils.closeQuietly(handle);
10449        }
10450
10451        // Now that we've calculated the ABIs and determined if it's an internal app,
10452        // we will go ahead and populate the nativeLibraryPath.
10453        setNativeLibraryPaths(pkg, appLib32InstallDir);
10454    }
10455
10456    /**
10457     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10458     * i.e, so that all packages can be run inside a single process if required.
10459     *
10460     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10461     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10462     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10463     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10464     * updating a package that belongs to a shared user.
10465     *
10466     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10467     * adds unnecessary complexity.
10468     */
10469    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10470            PackageParser.Package scannedPackage) {
10471        String requiredInstructionSet = null;
10472        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10473            requiredInstructionSet = VMRuntime.getInstructionSet(
10474                     scannedPackage.applicationInfo.primaryCpuAbi);
10475        }
10476
10477        PackageSetting requirer = null;
10478        for (PackageSetting ps : packagesForUser) {
10479            // If packagesForUser contains scannedPackage, we skip it. This will happen
10480            // when scannedPackage is an update of an existing package. Without this check,
10481            // we will never be able to change the ABI of any package belonging to a shared
10482            // user, even if it's compatible with other packages.
10483            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10484                if (ps.primaryCpuAbiString == null) {
10485                    continue;
10486                }
10487
10488                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10489                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10490                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10491                    // this but there's not much we can do.
10492                    String errorMessage = "Instruction set mismatch, "
10493                            + ((requirer == null) ? "[caller]" : requirer)
10494                            + " requires " + requiredInstructionSet + " whereas " + ps
10495                            + " requires " + instructionSet;
10496                    Slog.w(TAG, errorMessage);
10497                }
10498
10499                if (requiredInstructionSet == null) {
10500                    requiredInstructionSet = instructionSet;
10501                    requirer = ps;
10502                }
10503            }
10504        }
10505
10506        if (requiredInstructionSet != null) {
10507            String adjustedAbi;
10508            if (requirer != null) {
10509                // requirer != null implies that either scannedPackage was null or that scannedPackage
10510                // did not require an ABI, in which case we have to adjust scannedPackage to match
10511                // the ABI of the set (which is the same as requirer's ABI)
10512                adjustedAbi = requirer.primaryCpuAbiString;
10513                if (scannedPackage != null) {
10514                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10515                }
10516            } else {
10517                // requirer == null implies that we're updating all ABIs in the set to
10518                // match scannedPackage.
10519                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10520            }
10521
10522            for (PackageSetting ps : packagesForUser) {
10523                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10524                    if (ps.primaryCpuAbiString != null) {
10525                        continue;
10526                    }
10527
10528                    ps.primaryCpuAbiString = adjustedAbi;
10529                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10530                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10531                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10532                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10533                                + " (requirer="
10534                                + (requirer == null ? "null" : requirer.pkg.packageName)
10535                                + ", scannedPackage="
10536                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10537                                + ")");
10538                        try {
10539                            mInstaller.rmdex(ps.codePathString,
10540                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10541                        } catch (InstallerException ignored) {
10542                        }
10543                    }
10544                }
10545            }
10546        }
10547    }
10548
10549    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10550        synchronized (mPackages) {
10551            mResolverReplaced = true;
10552            // Set up information for custom user intent resolution activity.
10553            mResolveActivity.applicationInfo = pkg.applicationInfo;
10554            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10555            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10556            mResolveActivity.processName = pkg.applicationInfo.packageName;
10557            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10558            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10559                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10560            mResolveActivity.theme = 0;
10561            mResolveActivity.exported = true;
10562            mResolveActivity.enabled = true;
10563            mResolveInfo.activityInfo = mResolveActivity;
10564            mResolveInfo.priority = 0;
10565            mResolveInfo.preferredOrder = 0;
10566            mResolveInfo.match = 0;
10567            mResolveComponentName = mCustomResolverComponentName;
10568            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10569                    mResolveComponentName);
10570        }
10571    }
10572
10573    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10574        if (installerComponent == null) {
10575            if (DEBUG_EPHEMERAL) {
10576                Slog.d(TAG, "Clear ephemeral installer activity");
10577            }
10578            mEphemeralInstallerActivity.applicationInfo = null;
10579            return;
10580        }
10581
10582        if (DEBUG_EPHEMERAL) {
10583            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10584        }
10585        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10586        // Set up information for ephemeral installer activity
10587        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10588        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10589        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10590        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10591        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10592        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10593                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10594        mEphemeralInstallerActivity.theme = 0;
10595        mEphemeralInstallerActivity.exported = true;
10596        mEphemeralInstallerActivity.enabled = true;
10597        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10598        mEphemeralInstallerInfo.priority = 0;
10599        mEphemeralInstallerInfo.preferredOrder = 1;
10600        mEphemeralInstallerInfo.isDefault = true;
10601        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10602                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10603    }
10604
10605    private static String calculateBundledApkRoot(final String codePathString) {
10606        final File codePath = new File(codePathString);
10607        final File codeRoot;
10608        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10609            codeRoot = Environment.getRootDirectory();
10610        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10611            codeRoot = Environment.getOemDirectory();
10612        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10613            codeRoot = Environment.getVendorDirectory();
10614        } else {
10615            // Unrecognized code path; take its top real segment as the apk root:
10616            // e.g. /something/app/blah.apk => /something
10617            try {
10618                File f = codePath.getCanonicalFile();
10619                File parent = f.getParentFile();    // non-null because codePath is a file
10620                File tmp;
10621                while ((tmp = parent.getParentFile()) != null) {
10622                    f = parent;
10623                    parent = tmp;
10624                }
10625                codeRoot = f;
10626                Slog.w(TAG, "Unrecognized code path "
10627                        + codePath + " - using " + codeRoot);
10628            } catch (IOException e) {
10629                // Can't canonicalize the code path -- shenanigans?
10630                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10631                return Environment.getRootDirectory().getPath();
10632            }
10633        }
10634        return codeRoot.getPath();
10635    }
10636
10637    /**
10638     * Derive and set the location of native libraries for the given package,
10639     * which varies depending on where and how the package was installed.
10640     */
10641    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10642        final ApplicationInfo info = pkg.applicationInfo;
10643        final String codePath = pkg.codePath;
10644        final File codeFile = new File(codePath);
10645        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10646        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10647
10648        info.nativeLibraryRootDir = null;
10649        info.nativeLibraryRootRequiresIsa = false;
10650        info.nativeLibraryDir = null;
10651        info.secondaryNativeLibraryDir = null;
10652
10653        if (isApkFile(codeFile)) {
10654            // Monolithic install
10655            if (bundledApp) {
10656                // If "/system/lib64/apkname" exists, assume that is the per-package
10657                // native library directory to use; otherwise use "/system/lib/apkname".
10658                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10659                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10660                        getPrimaryInstructionSet(info));
10661
10662                // This is a bundled system app so choose the path based on the ABI.
10663                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10664                // is just the default path.
10665                final String apkName = deriveCodePathName(codePath);
10666                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10667                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10668                        apkName).getAbsolutePath();
10669
10670                if (info.secondaryCpuAbi != null) {
10671                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10672                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10673                            secondaryLibDir, apkName).getAbsolutePath();
10674                }
10675            } else if (asecApp) {
10676                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10677                        .getAbsolutePath();
10678            } else {
10679                final String apkName = deriveCodePathName(codePath);
10680                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10681                        .getAbsolutePath();
10682            }
10683
10684            info.nativeLibraryRootRequiresIsa = false;
10685            info.nativeLibraryDir = info.nativeLibraryRootDir;
10686        } else {
10687            // Cluster install
10688            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10689            info.nativeLibraryRootRequiresIsa = true;
10690
10691            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10692                    getPrimaryInstructionSet(info)).getAbsolutePath();
10693
10694            if (info.secondaryCpuAbi != null) {
10695                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10696                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10697            }
10698        }
10699    }
10700
10701    /**
10702     * Calculate the abis and roots for a bundled app. These can uniquely
10703     * be determined from the contents of the system partition, i.e whether
10704     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10705     * of this information, and instead assume that the system was built
10706     * sensibly.
10707     */
10708    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10709                                           PackageSetting pkgSetting) {
10710        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10711
10712        // If "/system/lib64/apkname" exists, assume that is the per-package
10713        // native library directory to use; otherwise use "/system/lib/apkname".
10714        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10715        setBundledAppAbi(pkg, apkRoot, apkName);
10716        // pkgSetting might be null during rescan following uninstall of updates
10717        // to a bundled app, so accommodate that possibility.  The settings in
10718        // that case will be established later from the parsed package.
10719        //
10720        // If the settings aren't null, sync them up with what we've just derived.
10721        // note that apkRoot isn't stored in the package settings.
10722        if (pkgSetting != null) {
10723            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10724            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10725        }
10726    }
10727
10728    /**
10729     * Deduces the ABI of a bundled app and sets the relevant fields on the
10730     * parsed pkg object.
10731     *
10732     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10733     *        under which system libraries are installed.
10734     * @param apkName the name of the installed package.
10735     */
10736    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10737        final File codeFile = new File(pkg.codePath);
10738
10739        final boolean has64BitLibs;
10740        final boolean has32BitLibs;
10741        if (isApkFile(codeFile)) {
10742            // Monolithic install
10743            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10744            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10745        } else {
10746            // Cluster install
10747            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10748            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10749                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10750                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10751                has64BitLibs = (new File(rootDir, isa)).exists();
10752            } else {
10753                has64BitLibs = false;
10754            }
10755            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10756                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10757                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10758                has32BitLibs = (new File(rootDir, isa)).exists();
10759            } else {
10760                has32BitLibs = false;
10761            }
10762        }
10763
10764        if (has64BitLibs && !has32BitLibs) {
10765            // The package has 64 bit libs, but not 32 bit libs. Its primary
10766            // ABI should be 64 bit. We can safely assume here that the bundled
10767            // native libraries correspond to the most preferred ABI in the list.
10768
10769            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10770            pkg.applicationInfo.secondaryCpuAbi = null;
10771        } else if (has32BitLibs && !has64BitLibs) {
10772            // The package has 32 bit libs but not 64 bit libs. Its primary
10773            // ABI should be 32 bit.
10774
10775            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10776            pkg.applicationInfo.secondaryCpuAbi = null;
10777        } else if (has32BitLibs && has64BitLibs) {
10778            // The application has both 64 and 32 bit bundled libraries. We check
10779            // here that the app declares multiArch support, and warn if it doesn't.
10780            //
10781            // We will be lenient here and record both ABIs. The primary will be the
10782            // ABI that's higher on the list, i.e, a device that's configured to prefer
10783            // 64 bit apps will see a 64 bit primary ABI,
10784
10785            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10786                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10787            }
10788
10789            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10790                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10791                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10792            } else {
10793                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10794                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10795            }
10796        } else {
10797            pkg.applicationInfo.primaryCpuAbi = null;
10798            pkg.applicationInfo.secondaryCpuAbi = null;
10799        }
10800    }
10801
10802    private void killApplication(String pkgName, int appId, String reason) {
10803        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10804    }
10805
10806    private void killApplication(String pkgName, int appId, int userId, String reason) {
10807        // Request the ActivityManager to kill the process(only for existing packages)
10808        // so that we do not end up in a confused state while the user is still using the older
10809        // version of the application while the new one gets installed.
10810        final long token = Binder.clearCallingIdentity();
10811        try {
10812            IActivityManager am = ActivityManager.getService();
10813            if (am != null) {
10814                try {
10815                    am.killApplication(pkgName, appId, userId, reason);
10816                } catch (RemoteException e) {
10817                }
10818            }
10819        } finally {
10820            Binder.restoreCallingIdentity(token);
10821        }
10822    }
10823
10824    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10825        // Remove the parent package setting
10826        PackageSetting ps = (PackageSetting) pkg.mExtras;
10827        if (ps != null) {
10828            removePackageLI(ps, chatty);
10829        }
10830        // Remove the child package setting
10831        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10832        for (int i = 0; i < childCount; i++) {
10833            PackageParser.Package childPkg = pkg.childPackages.get(i);
10834            ps = (PackageSetting) childPkg.mExtras;
10835            if (ps != null) {
10836                removePackageLI(ps, chatty);
10837            }
10838        }
10839    }
10840
10841    void removePackageLI(PackageSetting ps, boolean chatty) {
10842        if (DEBUG_INSTALL) {
10843            if (chatty)
10844                Log.d(TAG, "Removing package " + ps.name);
10845        }
10846
10847        // writer
10848        synchronized (mPackages) {
10849            mPackages.remove(ps.name);
10850            final PackageParser.Package pkg = ps.pkg;
10851            if (pkg != null) {
10852                cleanPackageDataStructuresLILPw(pkg, chatty);
10853            }
10854        }
10855    }
10856
10857    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10858        if (DEBUG_INSTALL) {
10859            if (chatty)
10860                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10861        }
10862
10863        // writer
10864        synchronized (mPackages) {
10865            // Remove the parent package
10866            mPackages.remove(pkg.applicationInfo.packageName);
10867            cleanPackageDataStructuresLILPw(pkg, chatty);
10868
10869            // Remove the child packages
10870            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10871            for (int i = 0; i < childCount; i++) {
10872                PackageParser.Package childPkg = pkg.childPackages.get(i);
10873                mPackages.remove(childPkg.applicationInfo.packageName);
10874                cleanPackageDataStructuresLILPw(childPkg, chatty);
10875            }
10876        }
10877    }
10878
10879    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10880        int N = pkg.providers.size();
10881        StringBuilder r = null;
10882        int i;
10883        for (i=0; i<N; i++) {
10884            PackageParser.Provider p = pkg.providers.get(i);
10885            mProviders.removeProvider(p);
10886            if (p.info.authority == null) {
10887
10888                /* There was another ContentProvider with this authority when
10889                 * this app was installed so this authority is null,
10890                 * Ignore it as we don't have to unregister the provider.
10891                 */
10892                continue;
10893            }
10894            String names[] = p.info.authority.split(";");
10895            for (int j = 0; j < names.length; j++) {
10896                if (mProvidersByAuthority.get(names[j]) == p) {
10897                    mProvidersByAuthority.remove(names[j]);
10898                    if (DEBUG_REMOVE) {
10899                        if (chatty)
10900                            Log.d(TAG, "Unregistered content provider: " + names[j]
10901                                    + ", className = " + p.info.name + ", isSyncable = "
10902                                    + p.info.isSyncable);
10903                    }
10904                }
10905            }
10906            if (DEBUG_REMOVE && chatty) {
10907                if (r == null) {
10908                    r = new StringBuilder(256);
10909                } else {
10910                    r.append(' ');
10911                }
10912                r.append(p.info.name);
10913            }
10914        }
10915        if (r != null) {
10916            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10917        }
10918
10919        N = pkg.services.size();
10920        r = null;
10921        for (i=0; i<N; i++) {
10922            PackageParser.Service s = pkg.services.get(i);
10923            mServices.removeService(s);
10924            if (chatty) {
10925                if (r == null) {
10926                    r = new StringBuilder(256);
10927                } else {
10928                    r.append(' ');
10929                }
10930                r.append(s.info.name);
10931            }
10932        }
10933        if (r != null) {
10934            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10935        }
10936
10937        N = pkg.receivers.size();
10938        r = null;
10939        for (i=0; i<N; i++) {
10940            PackageParser.Activity a = pkg.receivers.get(i);
10941            mReceivers.removeActivity(a, "receiver");
10942            if (DEBUG_REMOVE && chatty) {
10943                if (r == null) {
10944                    r = new StringBuilder(256);
10945                } else {
10946                    r.append(' ');
10947                }
10948                r.append(a.info.name);
10949            }
10950        }
10951        if (r != null) {
10952            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10953        }
10954
10955        N = pkg.activities.size();
10956        r = null;
10957        for (i=0; i<N; i++) {
10958            PackageParser.Activity a = pkg.activities.get(i);
10959            mActivities.removeActivity(a, "activity");
10960            if (DEBUG_REMOVE && chatty) {
10961                if (r == null) {
10962                    r = new StringBuilder(256);
10963                } else {
10964                    r.append(' ');
10965                }
10966                r.append(a.info.name);
10967            }
10968        }
10969        if (r != null) {
10970            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10971        }
10972
10973        N = pkg.permissions.size();
10974        r = null;
10975        for (i=0; i<N; i++) {
10976            PackageParser.Permission p = pkg.permissions.get(i);
10977            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10978            if (bp == null) {
10979                bp = mSettings.mPermissionTrees.get(p.info.name);
10980            }
10981            if (bp != null && bp.perm == p) {
10982                bp.perm = null;
10983                if (DEBUG_REMOVE && chatty) {
10984                    if (r == null) {
10985                        r = new StringBuilder(256);
10986                    } else {
10987                        r.append(' ');
10988                    }
10989                    r.append(p.info.name);
10990                }
10991            }
10992            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10993                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10994                if (appOpPkgs != null) {
10995                    appOpPkgs.remove(pkg.packageName);
10996                }
10997            }
10998        }
10999        if (r != null) {
11000            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11001        }
11002
11003        N = pkg.requestedPermissions.size();
11004        r = null;
11005        for (i=0; i<N; i++) {
11006            String perm = pkg.requestedPermissions.get(i);
11007            BasePermission bp = mSettings.mPermissions.get(perm);
11008            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11009                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11010                if (appOpPkgs != null) {
11011                    appOpPkgs.remove(pkg.packageName);
11012                    if (appOpPkgs.isEmpty()) {
11013                        mAppOpPermissionPackages.remove(perm);
11014                    }
11015                }
11016            }
11017        }
11018        if (r != null) {
11019            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11020        }
11021
11022        N = pkg.instrumentation.size();
11023        r = null;
11024        for (i=0; i<N; i++) {
11025            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11026            mInstrumentation.remove(a.getComponentName());
11027            if (DEBUG_REMOVE && chatty) {
11028                if (r == null) {
11029                    r = new StringBuilder(256);
11030                } else {
11031                    r.append(' ');
11032                }
11033                r.append(a.info.name);
11034            }
11035        }
11036        if (r != null) {
11037            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11038        }
11039
11040        r = null;
11041        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11042            // Only system apps can hold shared libraries.
11043            if (pkg.libraryNames != null) {
11044                for (i = 0; i < pkg.libraryNames.size(); i++) {
11045                    String name = pkg.libraryNames.get(i);
11046                    if (removeSharedLibraryLPw(name, 0)) {
11047                        if (DEBUG_REMOVE && chatty) {
11048                            if (r == null) {
11049                                r = new StringBuilder(256);
11050                            } else {
11051                                r.append(' ');
11052                            }
11053                            r.append(name);
11054                        }
11055                    }
11056                }
11057            }
11058        }
11059
11060        r = null;
11061
11062        // Any package can hold static shared libraries.
11063        if (pkg.staticSharedLibName != null) {
11064            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11065                if (DEBUG_REMOVE && chatty) {
11066                    if (r == null) {
11067                        r = new StringBuilder(256);
11068                    } else {
11069                        r.append(' ');
11070                    }
11071                    r.append(pkg.staticSharedLibName);
11072                }
11073            }
11074        }
11075
11076        if (r != null) {
11077            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11078        }
11079    }
11080
11081    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11082        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11083            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11084                return true;
11085            }
11086        }
11087        return false;
11088    }
11089
11090    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11091    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11092    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11093
11094    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11095        // Update the parent permissions
11096        updatePermissionsLPw(pkg.packageName, pkg, flags);
11097        // Update the child permissions
11098        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11099        for (int i = 0; i < childCount; i++) {
11100            PackageParser.Package childPkg = pkg.childPackages.get(i);
11101            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11102        }
11103    }
11104
11105    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11106            int flags) {
11107        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11108        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11109    }
11110
11111    private void updatePermissionsLPw(String changingPkg,
11112            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11113        // Make sure there are no dangling permission trees.
11114        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11115        while (it.hasNext()) {
11116            final BasePermission bp = it.next();
11117            if (bp.packageSetting == null) {
11118                // We may not yet have parsed the package, so just see if
11119                // we still know about its settings.
11120                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11121            }
11122            if (bp.packageSetting == null) {
11123                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11124                        + " from package " + bp.sourcePackage);
11125                it.remove();
11126            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11127                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11128                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11129                            + " from package " + bp.sourcePackage);
11130                    flags |= UPDATE_PERMISSIONS_ALL;
11131                    it.remove();
11132                }
11133            }
11134        }
11135
11136        // Make sure all dynamic permissions have been assigned to a package,
11137        // and make sure there are no dangling permissions.
11138        it = mSettings.mPermissions.values().iterator();
11139        while (it.hasNext()) {
11140            final BasePermission bp = it.next();
11141            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11142                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11143                        + bp.name + " pkg=" + bp.sourcePackage
11144                        + " info=" + bp.pendingInfo);
11145                if (bp.packageSetting == null && bp.pendingInfo != null) {
11146                    final BasePermission tree = findPermissionTreeLP(bp.name);
11147                    if (tree != null && tree.perm != null) {
11148                        bp.packageSetting = tree.packageSetting;
11149                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11150                                new PermissionInfo(bp.pendingInfo));
11151                        bp.perm.info.packageName = tree.perm.info.packageName;
11152                        bp.perm.info.name = bp.name;
11153                        bp.uid = tree.uid;
11154                    }
11155                }
11156            }
11157            if (bp.packageSetting == null) {
11158                // We may not yet have parsed the package, so just see if
11159                // we still know about its settings.
11160                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11161            }
11162            if (bp.packageSetting == null) {
11163                Slog.w(TAG, "Removing dangling permission: " + bp.name
11164                        + " from package " + bp.sourcePackage);
11165                it.remove();
11166            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11167                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11168                    Slog.i(TAG, "Removing old permission: " + bp.name
11169                            + " from package " + bp.sourcePackage);
11170                    flags |= UPDATE_PERMISSIONS_ALL;
11171                    it.remove();
11172                }
11173            }
11174        }
11175
11176        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11177        // Now update the permissions for all packages, in particular
11178        // replace the granted permissions of the system packages.
11179        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11180            for (PackageParser.Package pkg : mPackages.values()) {
11181                if (pkg != pkgInfo) {
11182                    // Only replace for packages on requested volume
11183                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11184                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11185                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11186                    grantPermissionsLPw(pkg, replace, changingPkg);
11187                }
11188            }
11189        }
11190
11191        if (pkgInfo != null) {
11192            // Only replace for packages on requested volume
11193            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11194            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11195                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11196            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11197        }
11198        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11199    }
11200
11201    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11202            String packageOfInterest) {
11203        // IMPORTANT: There are two types of permissions: install and runtime.
11204        // Install time permissions are granted when the app is installed to
11205        // all device users and users added in the future. Runtime permissions
11206        // are granted at runtime explicitly to specific users. Normal and signature
11207        // protected permissions are install time permissions. Dangerous permissions
11208        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11209        // otherwise they are runtime permissions. This function does not manage
11210        // runtime permissions except for the case an app targeting Lollipop MR1
11211        // being upgraded to target a newer SDK, in which case dangerous permissions
11212        // are transformed from install time to runtime ones.
11213
11214        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11215        if (ps == null) {
11216            return;
11217        }
11218
11219        PermissionsState permissionsState = ps.getPermissionsState();
11220        PermissionsState origPermissions = permissionsState;
11221
11222        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11223
11224        boolean runtimePermissionsRevoked = false;
11225        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11226
11227        boolean changedInstallPermission = false;
11228
11229        if (replace) {
11230            ps.installPermissionsFixed = false;
11231            if (!ps.isSharedUser()) {
11232                origPermissions = new PermissionsState(permissionsState);
11233                permissionsState.reset();
11234            } else {
11235                // We need to know only about runtime permission changes since the
11236                // calling code always writes the install permissions state but
11237                // the runtime ones are written only if changed. The only cases of
11238                // changed runtime permissions here are promotion of an install to
11239                // runtime and revocation of a runtime from a shared user.
11240                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11241                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11242                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11243                    runtimePermissionsRevoked = true;
11244                }
11245            }
11246        }
11247
11248        permissionsState.setGlobalGids(mGlobalGids);
11249
11250        final int N = pkg.requestedPermissions.size();
11251        for (int i=0; i<N; i++) {
11252            final String name = pkg.requestedPermissions.get(i);
11253            final BasePermission bp = mSettings.mPermissions.get(name);
11254
11255            if (DEBUG_INSTALL) {
11256                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11257            }
11258
11259            if (bp == null || bp.packageSetting == null) {
11260                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11261                    Slog.w(TAG, "Unknown permission " + name
11262                            + " in package " + pkg.packageName);
11263                }
11264                continue;
11265            }
11266
11267
11268            // Limit ephemeral apps to ephemeral allowed permissions.
11269            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11270                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11271                        + pkg.packageName);
11272                continue;
11273            }
11274
11275            final String perm = bp.name;
11276            boolean allowedSig = false;
11277            int grant = GRANT_DENIED;
11278
11279            // Keep track of app op permissions.
11280            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11281                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11282                if (pkgs == null) {
11283                    pkgs = new ArraySet<>();
11284                    mAppOpPermissionPackages.put(bp.name, pkgs);
11285                }
11286                pkgs.add(pkg.packageName);
11287            }
11288
11289            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11290            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11291                    >= Build.VERSION_CODES.M;
11292            switch (level) {
11293                case PermissionInfo.PROTECTION_NORMAL: {
11294                    // For all apps normal permissions are install time ones.
11295                    grant = GRANT_INSTALL;
11296                } break;
11297
11298                case PermissionInfo.PROTECTION_DANGEROUS: {
11299                    // If a permission review is required for legacy apps we represent
11300                    // their permissions as always granted runtime ones since we need
11301                    // to keep the review required permission flag per user while an
11302                    // install permission's state is shared across all users.
11303                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11304                        // For legacy apps dangerous permissions are install time ones.
11305                        grant = GRANT_INSTALL;
11306                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11307                        // For legacy apps that became modern, install becomes runtime.
11308                        grant = GRANT_UPGRADE;
11309                    } else if (mPromoteSystemApps
11310                            && isSystemApp(ps)
11311                            && mExistingSystemPackages.contains(ps.name)) {
11312                        // For legacy system apps, install becomes runtime.
11313                        // We cannot check hasInstallPermission() for system apps since those
11314                        // permissions were granted implicitly and not persisted pre-M.
11315                        grant = GRANT_UPGRADE;
11316                    } else {
11317                        // For modern apps keep runtime permissions unchanged.
11318                        grant = GRANT_RUNTIME;
11319                    }
11320                } break;
11321
11322                case PermissionInfo.PROTECTION_SIGNATURE: {
11323                    // For all apps signature permissions are install time ones.
11324                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11325                    if (allowedSig) {
11326                        grant = GRANT_INSTALL;
11327                    }
11328                } break;
11329            }
11330
11331            if (DEBUG_INSTALL) {
11332                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11333            }
11334
11335            if (grant != GRANT_DENIED) {
11336                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11337                    // If this is an existing, non-system package, then
11338                    // we can't add any new permissions to it.
11339                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11340                        // Except...  if this is a permission that was added
11341                        // to the platform (note: need to only do this when
11342                        // updating the platform).
11343                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11344                            grant = GRANT_DENIED;
11345                        }
11346                    }
11347                }
11348
11349                switch (grant) {
11350                    case GRANT_INSTALL: {
11351                        // Revoke this as runtime permission to handle the case of
11352                        // a runtime permission being downgraded to an install one.
11353                        // Also in permission review mode we keep dangerous permissions
11354                        // for legacy apps
11355                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11356                            if (origPermissions.getRuntimePermissionState(
11357                                    bp.name, userId) != null) {
11358                                // Revoke the runtime permission and clear the flags.
11359                                origPermissions.revokeRuntimePermission(bp, userId);
11360                                origPermissions.updatePermissionFlags(bp, userId,
11361                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11362                                // If we revoked a permission permission, we have to write.
11363                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11364                                        changedRuntimePermissionUserIds, userId);
11365                            }
11366                        }
11367                        // Grant an install permission.
11368                        if (permissionsState.grantInstallPermission(bp) !=
11369                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11370                            changedInstallPermission = true;
11371                        }
11372                    } break;
11373
11374                    case GRANT_RUNTIME: {
11375                        // Grant previously granted runtime permissions.
11376                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11377                            PermissionState permissionState = origPermissions
11378                                    .getRuntimePermissionState(bp.name, userId);
11379                            int flags = permissionState != null
11380                                    ? permissionState.getFlags() : 0;
11381                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11382                                // Don't propagate the permission in a permission review mode if
11383                                // the former was revoked, i.e. marked to not propagate on upgrade.
11384                                // Note that in a permission review mode install permissions are
11385                                // represented as constantly granted runtime ones since we need to
11386                                // keep a per user state associated with the permission. Also the
11387                                // revoke on upgrade flag is no longer applicable and is reset.
11388                                final boolean revokeOnUpgrade = (flags & PackageManager
11389                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11390                                if (revokeOnUpgrade) {
11391                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11392                                    // Since we changed the flags, we have to write.
11393                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11394                                            changedRuntimePermissionUserIds, userId);
11395                                }
11396                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11397                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11398                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11399                                        // If we cannot put the permission as it was,
11400                                        // we have to write.
11401                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11402                                                changedRuntimePermissionUserIds, userId);
11403                                    }
11404                                }
11405
11406                                // If the app supports runtime permissions no need for a review.
11407                                if (mPermissionReviewRequired
11408                                        && appSupportsRuntimePermissions
11409                                        && (flags & PackageManager
11410                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11411                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11412                                    // Since we changed the flags, we have to write.
11413                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11414                                            changedRuntimePermissionUserIds, userId);
11415                                }
11416                            } else if (mPermissionReviewRequired
11417                                    && !appSupportsRuntimePermissions) {
11418                                // For legacy apps that need a permission review, every new
11419                                // runtime permission is granted but it is pending a review.
11420                                // We also need to review only platform defined runtime
11421                                // permissions as these are the only ones the platform knows
11422                                // how to disable the API to simulate revocation as legacy
11423                                // apps don't expect to run with revoked permissions.
11424                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11425                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11426                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11427                                        // We changed the flags, hence have to write.
11428                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11429                                                changedRuntimePermissionUserIds, userId);
11430                                    }
11431                                }
11432                                if (permissionsState.grantRuntimePermission(bp, userId)
11433                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11434                                    // We changed the permission, hence have to write.
11435                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11436                                            changedRuntimePermissionUserIds, userId);
11437                                }
11438                            }
11439                            // Propagate the permission flags.
11440                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11441                        }
11442                    } break;
11443
11444                    case GRANT_UPGRADE: {
11445                        // Grant runtime permissions for a previously held install permission.
11446                        PermissionState permissionState = origPermissions
11447                                .getInstallPermissionState(bp.name);
11448                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11449
11450                        if (origPermissions.revokeInstallPermission(bp)
11451                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11452                            // We will be transferring the permission flags, so clear them.
11453                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11454                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11455                            changedInstallPermission = true;
11456                        }
11457
11458                        // If the permission is not to be promoted to runtime we ignore it and
11459                        // also its other flags as they are not applicable to install permissions.
11460                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11461                            for (int userId : currentUserIds) {
11462                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11463                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11464                                    // Transfer the permission flags.
11465                                    permissionsState.updatePermissionFlags(bp, userId,
11466                                            flags, flags);
11467                                    // If we granted the permission, we have to write.
11468                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11469                                            changedRuntimePermissionUserIds, userId);
11470                                }
11471                            }
11472                        }
11473                    } break;
11474
11475                    default: {
11476                        if (packageOfInterest == null
11477                                || packageOfInterest.equals(pkg.packageName)) {
11478                            Slog.w(TAG, "Not granting permission " + perm
11479                                    + " to package " + pkg.packageName
11480                                    + " because it was previously installed without");
11481                        }
11482                    } break;
11483                }
11484            } else {
11485                if (permissionsState.revokeInstallPermission(bp) !=
11486                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11487                    // Also drop the permission flags.
11488                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11489                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11490                    changedInstallPermission = true;
11491                    Slog.i(TAG, "Un-granting permission " + perm
11492                            + " from package " + pkg.packageName
11493                            + " (protectionLevel=" + bp.protectionLevel
11494                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11495                            + ")");
11496                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11497                    // Don't print warning for app op permissions, since it is fine for them
11498                    // not to be granted, there is a UI for the user to decide.
11499                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11500                        Slog.w(TAG, "Not granting permission " + perm
11501                                + " to package " + pkg.packageName
11502                                + " (protectionLevel=" + bp.protectionLevel
11503                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11504                                + ")");
11505                    }
11506                }
11507            }
11508        }
11509
11510        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11511                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11512            // This is the first that we have heard about this package, so the
11513            // permissions we have now selected are fixed until explicitly
11514            // changed.
11515            ps.installPermissionsFixed = true;
11516        }
11517
11518        // Persist the runtime permissions state for users with changes. If permissions
11519        // were revoked because no app in the shared user declares them we have to
11520        // write synchronously to avoid losing runtime permissions state.
11521        for (int userId : changedRuntimePermissionUserIds) {
11522            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11523        }
11524    }
11525
11526    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11527        boolean allowed = false;
11528        final int NP = PackageParser.NEW_PERMISSIONS.length;
11529        for (int ip=0; ip<NP; ip++) {
11530            final PackageParser.NewPermissionInfo npi
11531                    = PackageParser.NEW_PERMISSIONS[ip];
11532            if (npi.name.equals(perm)
11533                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11534                allowed = true;
11535                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11536                        + pkg.packageName);
11537                break;
11538            }
11539        }
11540        return allowed;
11541    }
11542
11543    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11544            BasePermission bp, PermissionsState origPermissions) {
11545        boolean privilegedPermission = (bp.protectionLevel
11546                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11547        boolean privappPermissionsDisable =
11548                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11549        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11550        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11551        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11552                && !platformPackage && platformPermission) {
11553            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11554                    .getPrivAppPermissions(pkg.packageName);
11555            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11556            if (!whitelisted) {
11557                Slog.w(TAG, "Privileged permission " + perm + " for package "
11558                        + pkg.packageName + " - not in privapp-permissions whitelist");
11559                if (!mSystemReady) {
11560                    if (mPrivappPermissionsViolations == null) {
11561                        mPrivappPermissionsViolations = new ArraySet<>();
11562                    }
11563                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11564                }
11565                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11566                    return false;
11567                }
11568            }
11569        }
11570        boolean allowed = (compareSignatures(
11571                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11572                        == PackageManager.SIGNATURE_MATCH)
11573                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11574                        == PackageManager.SIGNATURE_MATCH);
11575        if (!allowed && privilegedPermission) {
11576            if (isSystemApp(pkg)) {
11577                // For updated system applications, a system permission
11578                // is granted only if it had been defined by the original application.
11579                if (pkg.isUpdatedSystemApp()) {
11580                    final PackageSetting sysPs = mSettings
11581                            .getDisabledSystemPkgLPr(pkg.packageName);
11582                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11583                        // If the original was granted this permission, we take
11584                        // that grant decision as read and propagate it to the
11585                        // update.
11586                        if (sysPs.isPrivileged()) {
11587                            allowed = true;
11588                        }
11589                    } else {
11590                        // The system apk may have been updated with an older
11591                        // version of the one on the data partition, but which
11592                        // granted a new system permission that it didn't have
11593                        // before.  In this case we do want to allow the app to
11594                        // now get the new permission if the ancestral apk is
11595                        // privileged to get it.
11596                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11597                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11598                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11599                                    allowed = true;
11600                                    break;
11601                                }
11602                            }
11603                        }
11604                        // Also if a privileged parent package on the system image or any of
11605                        // its children requested a privileged permission, the updated child
11606                        // packages can also get the permission.
11607                        if (pkg.parentPackage != null) {
11608                            final PackageSetting disabledSysParentPs = mSettings
11609                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11610                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11611                                    && disabledSysParentPs.isPrivileged()) {
11612                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11613                                    allowed = true;
11614                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11615                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11616                                    for (int i = 0; i < count; i++) {
11617                                        PackageParser.Package disabledSysChildPkg =
11618                                                disabledSysParentPs.pkg.childPackages.get(i);
11619                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11620                                                perm)) {
11621                                            allowed = true;
11622                                            break;
11623                                        }
11624                                    }
11625                                }
11626                            }
11627                        }
11628                    }
11629                } else {
11630                    allowed = isPrivilegedApp(pkg);
11631                }
11632            }
11633        }
11634        if (!allowed) {
11635            if (!allowed && (bp.protectionLevel
11636                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11637                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11638                // If this was a previously normal/dangerous permission that got moved
11639                // to a system permission as part of the runtime permission redesign, then
11640                // we still want to blindly grant it to old apps.
11641                allowed = true;
11642            }
11643            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11644                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11645                // If this permission is to be granted to the system installer and
11646                // this app is an installer, then it gets the permission.
11647                allowed = true;
11648            }
11649            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11650                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11651                // If this permission is to be granted to the system verifier and
11652                // this app is a verifier, then it gets the permission.
11653                allowed = true;
11654            }
11655            if (!allowed && (bp.protectionLevel
11656                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11657                    && isSystemApp(pkg)) {
11658                // Any pre-installed system app is allowed to get this permission.
11659                allowed = true;
11660            }
11661            if (!allowed && (bp.protectionLevel
11662                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11663                // For development permissions, a development permission
11664                // is granted only if it was already granted.
11665                allowed = origPermissions.hasInstallPermission(perm);
11666            }
11667            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11668                    && pkg.packageName.equals(mSetupWizardPackage)) {
11669                // If this permission is to be granted to the system setup wizard and
11670                // this app is a setup wizard, then it gets the permission.
11671                allowed = true;
11672            }
11673        }
11674        return allowed;
11675    }
11676
11677    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11678        final int permCount = pkg.requestedPermissions.size();
11679        for (int j = 0; j < permCount; j++) {
11680            String requestedPermission = pkg.requestedPermissions.get(j);
11681            if (permission.equals(requestedPermission)) {
11682                return true;
11683            }
11684        }
11685        return false;
11686    }
11687
11688    final class ActivityIntentResolver
11689            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11690        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11691                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11692            if (!sUserManager.exists(userId)) return null;
11693            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11694                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11695                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11696            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11697                    isEphemeral, userId);
11698        }
11699
11700        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11701                int userId) {
11702            if (!sUserManager.exists(userId)) return null;
11703            mFlags = flags;
11704            return super.queryIntent(intent, resolvedType,
11705                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11706                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11707                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11708        }
11709
11710        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11711                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11712            if (!sUserManager.exists(userId)) return null;
11713            if (packageActivities == null) {
11714                return null;
11715            }
11716            mFlags = flags;
11717            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11718            final boolean vislbleToEphemeral =
11719                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11720            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11721            final int N = packageActivities.size();
11722            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11723                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11724
11725            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11726            for (int i = 0; i < N; ++i) {
11727                intentFilters = packageActivities.get(i).intents;
11728                if (intentFilters != null && intentFilters.size() > 0) {
11729                    PackageParser.ActivityIntentInfo[] array =
11730                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11731                    intentFilters.toArray(array);
11732                    listCut.add(array);
11733                }
11734            }
11735            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11736                    vislbleToEphemeral, isEphemeral, listCut, userId);
11737        }
11738
11739        /**
11740         * Finds a privileged activity that matches the specified activity names.
11741         */
11742        private PackageParser.Activity findMatchingActivity(
11743                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11744            for (PackageParser.Activity sysActivity : activityList) {
11745                if (sysActivity.info.name.equals(activityInfo.name)) {
11746                    return sysActivity;
11747                }
11748                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11749                    return sysActivity;
11750                }
11751                if (sysActivity.info.targetActivity != null) {
11752                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11753                        return sysActivity;
11754                    }
11755                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11756                        return sysActivity;
11757                    }
11758                }
11759            }
11760            return null;
11761        }
11762
11763        public class IterGenerator<E> {
11764            public Iterator<E> generate(ActivityIntentInfo info) {
11765                return null;
11766            }
11767        }
11768
11769        public class ActionIterGenerator extends IterGenerator<String> {
11770            @Override
11771            public Iterator<String> generate(ActivityIntentInfo info) {
11772                return info.actionsIterator();
11773            }
11774        }
11775
11776        public class CategoriesIterGenerator extends IterGenerator<String> {
11777            @Override
11778            public Iterator<String> generate(ActivityIntentInfo info) {
11779                return info.categoriesIterator();
11780            }
11781        }
11782
11783        public class SchemesIterGenerator extends IterGenerator<String> {
11784            @Override
11785            public Iterator<String> generate(ActivityIntentInfo info) {
11786                return info.schemesIterator();
11787            }
11788        }
11789
11790        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11791            @Override
11792            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11793                return info.authoritiesIterator();
11794            }
11795        }
11796
11797        /**
11798         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11799         * MODIFIED. Do not pass in a list that should not be changed.
11800         */
11801        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11802                IterGenerator<T> generator, Iterator<T> searchIterator) {
11803            // loop through the set of actions; every one must be found in the intent filter
11804            while (searchIterator.hasNext()) {
11805                // we must have at least one filter in the list to consider a match
11806                if (intentList.size() == 0) {
11807                    break;
11808                }
11809
11810                final T searchAction = searchIterator.next();
11811
11812                // loop through the set of intent filters
11813                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11814                while (intentIter.hasNext()) {
11815                    final ActivityIntentInfo intentInfo = intentIter.next();
11816                    boolean selectionFound = false;
11817
11818                    // loop through the intent filter's selection criteria; at least one
11819                    // of them must match the searched criteria
11820                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11821                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11822                        final T intentSelection = intentSelectionIter.next();
11823                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11824                            selectionFound = true;
11825                            break;
11826                        }
11827                    }
11828
11829                    // the selection criteria wasn't found in this filter's set; this filter
11830                    // is not a potential match
11831                    if (!selectionFound) {
11832                        intentIter.remove();
11833                    }
11834                }
11835            }
11836        }
11837
11838        private boolean isProtectedAction(ActivityIntentInfo filter) {
11839            final Iterator<String> actionsIter = filter.actionsIterator();
11840            while (actionsIter != null && actionsIter.hasNext()) {
11841                final String filterAction = actionsIter.next();
11842                if (PROTECTED_ACTIONS.contains(filterAction)) {
11843                    return true;
11844                }
11845            }
11846            return false;
11847        }
11848
11849        /**
11850         * Adjusts the priority of the given intent filter according to policy.
11851         * <p>
11852         * <ul>
11853         * <li>The priority for non privileged applications is capped to '0'</li>
11854         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11855         * <li>The priority for unbundled updates to privileged applications is capped to the
11856         *      priority defined on the system partition</li>
11857         * </ul>
11858         * <p>
11859         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11860         * allowed to obtain any priority on any action.
11861         */
11862        private void adjustPriority(
11863                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11864            // nothing to do; priority is fine as-is
11865            if (intent.getPriority() <= 0) {
11866                return;
11867            }
11868
11869            final ActivityInfo activityInfo = intent.activity.info;
11870            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11871
11872            final boolean privilegedApp =
11873                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11874            if (!privilegedApp) {
11875                // non-privileged applications can never define a priority >0
11876                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11877                        + " package: " + applicationInfo.packageName
11878                        + " activity: " + intent.activity.className
11879                        + " origPrio: " + intent.getPriority());
11880                intent.setPriority(0);
11881                return;
11882            }
11883
11884            if (systemActivities == null) {
11885                // the system package is not disabled; we're parsing the system partition
11886                if (isProtectedAction(intent)) {
11887                    if (mDeferProtectedFilters) {
11888                        // We can't deal with these just yet. No component should ever obtain a
11889                        // >0 priority for a protected actions, with ONE exception -- the setup
11890                        // wizard. The setup wizard, however, cannot be known until we're able to
11891                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11892                        // until all intent filters have been processed. Chicken, meet egg.
11893                        // Let the filter temporarily have a high priority and rectify the
11894                        // priorities after all system packages have been scanned.
11895                        mProtectedFilters.add(intent);
11896                        if (DEBUG_FILTERS) {
11897                            Slog.i(TAG, "Protected action; save for later;"
11898                                    + " package: " + applicationInfo.packageName
11899                                    + " activity: " + intent.activity.className
11900                                    + " origPrio: " + intent.getPriority());
11901                        }
11902                        return;
11903                    } else {
11904                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11905                            Slog.i(TAG, "No setup wizard;"
11906                                + " All protected intents capped to priority 0");
11907                        }
11908                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11909                            if (DEBUG_FILTERS) {
11910                                Slog.i(TAG, "Found setup wizard;"
11911                                    + " allow priority " + intent.getPriority() + ";"
11912                                    + " package: " + intent.activity.info.packageName
11913                                    + " activity: " + intent.activity.className
11914                                    + " priority: " + intent.getPriority());
11915                            }
11916                            // setup wizard gets whatever it wants
11917                            return;
11918                        }
11919                        Slog.w(TAG, "Protected action; cap priority to 0;"
11920                                + " package: " + intent.activity.info.packageName
11921                                + " activity: " + intent.activity.className
11922                                + " origPrio: " + intent.getPriority());
11923                        intent.setPriority(0);
11924                        return;
11925                    }
11926                }
11927                // privileged apps on the system image get whatever priority they request
11928                return;
11929            }
11930
11931            // privileged app unbundled update ... try to find the same activity
11932            final PackageParser.Activity foundActivity =
11933                    findMatchingActivity(systemActivities, activityInfo);
11934            if (foundActivity == null) {
11935                // this is a new activity; it cannot obtain >0 priority
11936                if (DEBUG_FILTERS) {
11937                    Slog.i(TAG, "New activity; cap priority to 0;"
11938                            + " package: " + applicationInfo.packageName
11939                            + " activity: " + intent.activity.className
11940                            + " origPrio: " + intent.getPriority());
11941                }
11942                intent.setPriority(0);
11943                return;
11944            }
11945
11946            // found activity, now check for filter equivalence
11947
11948            // a shallow copy is enough; we modify the list, not its contents
11949            final List<ActivityIntentInfo> intentListCopy =
11950                    new ArrayList<>(foundActivity.intents);
11951            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11952
11953            // find matching action subsets
11954            final Iterator<String> actionsIterator = intent.actionsIterator();
11955            if (actionsIterator != null) {
11956                getIntentListSubset(
11957                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11958                if (intentListCopy.size() == 0) {
11959                    // no more intents to match; we're not equivalent
11960                    if (DEBUG_FILTERS) {
11961                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11962                                + " package: " + applicationInfo.packageName
11963                                + " activity: " + intent.activity.className
11964                                + " origPrio: " + intent.getPriority());
11965                    }
11966                    intent.setPriority(0);
11967                    return;
11968                }
11969            }
11970
11971            // find matching category subsets
11972            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11973            if (categoriesIterator != null) {
11974                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11975                        categoriesIterator);
11976                if (intentListCopy.size() == 0) {
11977                    // no more intents to match; we're not equivalent
11978                    if (DEBUG_FILTERS) {
11979                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11980                                + " package: " + applicationInfo.packageName
11981                                + " activity: " + intent.activity.className
11982                                + " origPrio: " + intent.getPriority());
11983                    }
11984                    intent.setPriority(0);
11985                    return;
11986                }
11987            }
11988
11989            // find matching schemes subsets
11990            final Iterator<String> schemesIterator = intent.schemesIterator();
11991            if (schemesIterator != null) {
11992                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11993                        schemesIterator);
11994                if (intentListCopy.size() == 0) {
11995                    // no more intents to match; we're not equivalent
11996                    if (DEBUG_FILTERS) {
11997                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11998                                + " package: " + applicationInfo.packageName
11999                                + " activity: " + intent.activity.className
12000                                + " origPrio: " + intent.getPriority());
12001                    }
12002                    intent.setPriority(0);
12003                    return;
12004                }
12005            }
12006
12007            // find matching authorities subsets
12008            final Iterator<IntentFilter.AuthorityEntry>
12009                    authoritiesIterator = intent.authoritiesIterator();
12010            if (authoritiesIterator != null) {
12011                getIntentListSubset(intentListCopy,
12012                        new AuthoritiesIterGenerator(),
12013                        authoritiesIterator);
12014                if (intentListCopy.size() == 0) {
12015                    // no more intents to match; we're not equivalent
12016                    if (DEBUG_FILTERS) {
12017                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12018                                + " package: " + applicationInfo.packageName
12019                                + " activity: " + intent.activity.className
12020                                + " origPrio: " + intent.getPriority());
12021                    }
12022                    intent.setPriority(0);
12023                    return;
12024                }
12025            }
12026
12027            // we found matching filter(s); app gets the max priority of all intents
12028            int cappedPriority = 0;
12029            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12030                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12031            }
12032            if (intent.getPriority() > cappedPriority) {
12033                if (DEBUG_FILTERS) {
12034                    Slog.i(TAG, "Found matching filter(s);"
12035                            + " cap priority to " + cappedPriority + ";"
12036                            + " package: " + applicationInfo.packageName
12037                            + " activity: " + intent.activity.className
12038                            + " origPrio: " + intent.getPriority());
12039                }
12040                intent.setPriority(cappedPriority);
12041                return;
12042            }
12043            // all this for nothing; the requested priority was <= what was on the system
12044        }
12045
12046        public final void addActivity(PackageParser.Activity a, String type) {
12047            mActivities.put(a.getComponentName(), a);
12048            if (DEBUG_SHOW_INFO)
12049                Log.v(
12050                TAG, "  " + type + " " +
12051                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12052            if (DEBUG_SHOW_INFO)
12053                Log.v(TAG, "    Class=" + a.info.name);
12054            final int NI = a.intents.size();
12055            for (int j=0; j<NI; j++) {
12056                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12057                if ("activity".equals(type)) {
12058                    final PackageSetting ps =
12059                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12060                    final List<PackageParser.Activity> systemActivities =
12061                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12062                    adjustPriority(systemActivities, intent);
12063                }
12064                if (DEBUG_SHOW_INFO) {
12065                    Log.v(TAG, "    IntentFilter:");
12066                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12067                }
12068                if (!intent.debugCheck()) {
12069                    Log.w(TAG, "==> For Activity " + a.info.name);
12070                }
12071                addFilter(intent);
12072            }
12073        }
12074
12075        public final void removeActivity(PackageParser.Activity a, String type) {
12076            mActivities.remove(a.getComponentName());
12077            if (DEBUG_SHOW_INFO) {
12078                Log.v(TAG, "  " + type + " "
12079                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12080                                : a.info.name) + ":");
12081                Log.v(TAG, "    Class=" + a.info.name);
12082            }
12083            final int NI = a.intents.size();
12084            for (int j=0; j<NI; j++) {
12085                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12086                if (DEBUG_SHOW_INFO) {
12087                    Log.v(TAG, "    IntentFilter:");
12088                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12089                }
12090                removeFilter(intent);
12091            }
12092        }
12093
12094        @Override
12095        protected boolean allowFilterResult(
12096                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12097            ActivityInfo filterAi = filter.activity.info;
12098            for (int i=dest.size()-1; i>=0; i--) {
12099                ActivityInfo destAi = dest.get(i).activityInfo;
12100                if (destAi.name == filterAi.name
12101                        && destAi.packageName == filterAi.packageName) {
12102                    return false;
12103                }
12104            }
12105            return true;
12106        }
12107
12108        @Override
12109        protected ActivityIntentInfo[] newArray(int size) {
12110            return new ActivityIntentInfo[size];
12111        }
12112
12113        @Override
12114        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12115            if (!sUserManager.exists(userId)) return true;
12116            PackageParser.Package p = filter.activity.owner;
12117            if (p != null) {
12118                PackageSetting ps = (PackageSetting)p.mExtras;
12119                if (ps != null) {
12120                    // System apps are never considered stopped for purposes of
12121                    // filtering, because there may be no way for the user to
12122                    // actually re-launch them.
12123                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12124                            && ps.getStopped(userId);
12125                }
12126            }
12127            return false;
12128        }
12129
12130        @Override
12131        protected boolean isPackageForFilter(String packageName,
12132                PackageParser.ActivityIntentInfo info) {
12133            return packageName.equals(info.activity.owner.packageName);
12134        }
12135
12136        @Override
12137        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12138                int match, int userId) {
12139            if (!sUserManager.exists(userId)) return null;
12140            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12141                return null;
12142            }
12143            final PackageParser.Activity activity = info.activity;
12144            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12145            if (ps == null) {
12146                return null;
12147            }
12148            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12149                    ps.readUserState(userId), userId);
12150            if (ai == null) {
12151                return null;
12152            }
12153            final ResolveInfo res = new ResolveInfo();
12154            res.activityInfo = ai;
12155            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12156                res.filter = info;
12157            }
12158            if (info != null) {
12159                res.handleAllWebDataURI = info.handleAllWebDataURI();
12160            }
12161            res.priority = info.getPriority();
12162            res.preferredOrder = activity.owner.mPreferredOrder;
12163            //System.out.println("Result: " + res.activityInfo.className +
12164            //                   " = " + res.priority);
12165            res.match = match;
12166            res.isDefault = info.hasDefault;
12167            res.labelRes = info.labelRes;
12168            res.nonLocalizedLabel = info.nonLocalizedLabel;
12169            if (userNeedsBadging(userId)) {
12170                res.noResourceId = true;
12171            } else {
12172                res.icon = info.icon;
12173            }
12174            res.iconResourceId = info.icon;
12175            res.system = res.activityInfo.applicationInfo.isSystemApp();
12176            return res;
12177        }
12178
12179        @Override
12180        protected void sortResults(List<ResolveInfo> results) {
12181            Collections.sort(results, mResolvePrioritySorter);
12182        }
12183
12184        @Override
12185        protected void dumpFilter(PrintWriter out, String prefix,
12186                PackageParser.ActivityIntentInfo filter) {
12187            out.print(prefix); out.print(
12188                    Integer.toHexString(System.identityHashCode(filter.activity)));
12189                    out.print(' ');
12190                    filter.activity.printComponentShortName(out);
12191                    out.print(" filter ");
12192                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12193        }
12194
12195        @Override
12196        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12197            return filter.activity;
12198        }
12199
12200        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12201            PackageParser.Activity activity = (PackageParser.Activity)label;
12202            out.print(prefix); out.print(
12203                    Integer.toHexString(System.identityHashCode(activity)));
12204                    out.print(' ');
12205                    activity.printComponentShortName(out);
12206            if (count > 1) {
12207                out.print(" ("); out.print(count); out.print(" filters)");
12208            }
12209            out.println();
12210        }
12211
12212        // Keys are String (activity class name), values are Activity.
12213        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12214                = new ArrayMap<ComponentName, PackageParser.Activity>();
12215        private int mFlags;
12216    }
12217
12218    private final class ServiceIntentResolver
12219            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12220        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12221                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12222            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12223            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12224                    isEphemeral, userId);
12225        }
12226
12227        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12228                int userId) {
12229            if (!sUserManager.exists(userId)) return null;
12230            mFlags = flags;
12231            return super.queryIntent(intent, resolvedType,
12232                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12233                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12234                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12235        }
12236
12237        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12238                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12239            if (!sUserManager.exists(userId)) return null;
12240            if (packageServices == null) {
12241                return null;
12242            }
12243            mFlags = flags;
12244            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12245            final boolean vislbleToEphemeral =
12246                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12247            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12248            final int N = packageServices.size();
12249            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12250                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12251
12252            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12253            for (int i = 0; i < N; ++i) {
12254                intentFilters = packageServices.get(i).intents;
12255                if (intentFilters != null && intentFilters.size() > 0) {
12256                    PackageParser.ServiceIntentInfo[] array =
12257                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12258                    intentFilters.toArray(array);
12259                    listCut.add(array);
12260                }
12261            }
12262            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12263                    vislbleToEphemeral, isEphemeral, listCut, userId);
12264        }
12265
12266        public final void addService(PackageParser.Service s) {
12267            mServices.put(s.getComponentName(), s);
12268            if (DEBUG_SHOW_INFO) {
12269                Log.v(TAG, "  "
12270                        + (s.info.nonLocalizedLabel != null
12271                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12272                Log.v(TAG, "    Class=" + s.info.name);
12273            }
12274            final int NI = s.intents.size();
12275            int j;
12276            for (j=0; j<NI; j++) {
12277                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12278                if (DEBUG_SHOW_INFO) {
12279                    Log.v(TAG, "    IntentFilter:");
12280                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12281                }
12282                if (!intent.debugCheck()) {
12283                    Log.w(TAG, "==> For Service " + s.info.name);
12284                }
12285                addFilter(intent);
12286            }
12287        }
12288
12289        public final void removeService(PackageParser.Service s) {
12290            mServices.remove(s.getComponentName());
12291            if (DEBUG_SHOW_INFO) {
12292                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12293                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12294                Log.v(TAG, "    Class=" + s.info.name);
12295            }
12296            final int NI = s.intents.size();
12297            int j;
12298            for (j=0; j<NI; j++) {
12299                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12300                if (DEBUG_SHOW_INFO) {
12301                    Log.v(TAG, "    IntentFilter:");
12302                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12303                }
12304                removeFilter(intent);
12305            }
12306        }
12307
12308        @Override
12309        protected boolean allowFilterResult(
12310                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12311            ServiceInfo filterSi = filter.service.info;
12312            for (int i=dest.size()-1; i>=0; i--) {
12313                ServiceInfo destAi = dest.get(i).serviceInfo;
12314                if (destAi.name == filterSi.name
12315                        && destAi.packageName == filterSi.packageName) {
12316                    return false;
12317                }
12318            }
12319            return true;
12320        }
12321
12322        @Override
12323        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12324            return new PackageParser.ServiceIntentInfo[size];
12325        }
12326
12327        @Override
12328        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12329            if (!sUserManager.exists(userId)) return true;
12330            PackageParser.Package p = filter.service.owner;
12331            if (p != null) {
12332                PackageSetting ps = (PackageSetting)p.mExtras;
12333                if (ps != null) {
12334                    // System apps are never considered stopped for purposes of
12335                    // filtering, because there may be no way for the user to
12336                    // actually re-launch them.
12337                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12338                            && ps.getStopped(userId);
12339                }
12340            }
12341            return false;
12342        }
12343
12344        @Override
12345        protected boolean isPackageForFilter(String packageName,
12346                PackageParser.ServiceIntentInfo info) {
12347            return packageName.equals(info.service.owner.packageName);
12348        }
12349
12350        @Override
12351        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12352                int match, int userId) {
12353            if (!sUserManager.exists(userId)) return null;
12354            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12355            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12356                return null;
12357            }
12358            final PackageParser.Service service = info.service;
12359            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12360            if (ps == null) {
12361                return null;
12362            }
12363            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12364                    ps.readUserState(userId), userId);
12365            if (si == null) {
12366                return null;
12367            }
12368            final ResolveInfo res = new ResolveInfo();
12369            res.serviceInfo = si;
12370            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12371                res.filter = filter;
12372            }
12373            res.priority = info.getPriority();
12374            res.preferredOrder = service.owner.mPreferredOrder;
12375            res.match = match;
12376            res.isDefault = info.hasDefault;
12377            res.labelRes = info.labelRes;
12378            res.nonLocalizedLabel = info.nonLocalizedLabel;
12379            res.icon = info.icon;
12380            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12381            return res;
12382        }
12383
12384        @Override
12385        protected void sortResults(List<ResolveInfo> results) {
12386            Collections.sort(results, mResolvePrioritySorter);
12387        }
12388
12389        @Override
12390        protected void dumpFilter(PrintWriter out, String prefix,
12391                PackageParser.ServiceIntentInfo filter) {
12392            out.print(prefix); out.print(
12393                    Integer.toHexString(System.identityHashCode(filter.service)));
12394                    out.print(' ');
12395                    filter.service.printComponentShortName(out);
12396                    out.print(" filter ");
12397                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12398        }
12399
12400        @Override
12401        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12402            return filter.service;
12403        }
12404
12405        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12406            PackageParser.Service service = (PackageParser.Service)label;
12407            out.print(prefix); out.print(
12408                    Integer.toHexString(System.identityHashCode(service)));
12409                    out.print(' ');
12410                    service.printComponentShortName(out);
12411            if (count > 1) {
12412                out.print(" ("); out.print(count); out.print(" filters)");
12413            }
12414            out.println();
12415        }
12416
12417//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12418//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12419//            final List<ResolveInfo> retList = Lists.newArrayList();
12420//            while (i.hasNext()) {
12421//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12422//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12423//                    retList.add(resolveInfo);
12424//                }
12425//            }
12426//            return retList;
12427//        }
12428
12429        // Keys are String (activity class name), values are Activity.
12430        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12431                = new ArrayMap<ComponentName, PackageParser.Service>();
12432        private int mFlags;
12433    }
12434
12435    private final class ProviderIntentResolver
12436            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12437        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12438                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12439            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12440            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12441                    isEphemeral, userId);
12442        }
12443
12444        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12445                int userId) {
12446            if (!sUserManager.exists(userId))
12447                return null;
12448            mFlags = flags;
12449            return super.queryIntent(intent, resolvedType,
12450                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12451                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12452                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12453        }
12454
12455        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12456                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12457            if (!sUserManager.exists(userId))
12458                return null;
12459            if (packageProviders == null) {
12460                return null;
12461            }
12462            mFlags = flags;
12463            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12464            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12465            final boolean vislbleToEphemeral =
12466                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12467            final int N = packageProviders.size();
12468            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12469                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12470
12471            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12472            for (int i = 0; i < N; ++i) {
12473                intentFilters = packageProviders.get(i).intents;
12474                if (intentFilters != null && intentFilters.size() > 0) {
12475                    PackageParser.ProviderIntentInfo[] array =
12476                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12477                    intentFilters.toArray(array);
12478                    listCut.add(array);
12479                }
12480            }
12481            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12482                    vislbleToEphemeral, isEphemeral, listCut, userId);
12483        }
12484
12485        public final void addProvider(PackageParser.Provider p) {
12486            if (mProviders.containsKey(p.getComponentName())) {
12487                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12488                return;
12489            }
12490
12491            mProviders.put(p.getComponentName(), p);
12492            if (DEBUG_SHOW_INFO) {
12493                Log.v(TAG, "  "
12494                        + (p.info.nonLocalizedLabel != null
12495                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12496                Log.v(TAG, "    Class=" + p.info.name);
12497            }
12498            final int NI = p.intents.size();
12499            int j;
12500            for (j = 0; j < NI; j++) {
12501                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12502                if (DEBUG_SHOW_INFO) {
12503                    Log.v(TAG, "    IntentFilter:");
12504                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12505                }
12506                if (!intent.debugCheck()) {
12507                    Log.w(TAG, "==> For Provider " + p.info.name);
12508                }
12509                addFilter(intent);
12510            }
12511        }
12512
12513        public final void removeProvider(PackageParser.Provider p) {
12514            mProviders.remove(p.getComponentName());
12515            if (DEBUG_SHOW_INFO) {
12516                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12517                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12518                Log.v(TAG, "    Class=" + p.info.name);
12519            }
12520            final int NI = p.intents.size();
12521            int j;
12522            for (j = 0; j < NI; j++) {
12523                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12524                if (DEBUG_SHOW_INFO) {
12525                    Log.v(TAG, "    IntentFilter:");
12526                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12527                }
12528                removeFilter(intent);
12529            }
12530        }
12531
12532        @Override
12533        protected boolean allowFilterResult(
12534                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12535            ProviderInfo filterPi = filter.provider.info;
12536            for (int i = dest.size() - 1; i >= 0; i--) {
12537                ProviderInfo destPi = dest.get(i).providerInfo;
12538                if (destPi.name == filterPi.name
12539                        && destPi.packageName == filterPi.packageName) {
12540                    return false;
12541                }
12542            }
12543            return true;
12544        }
12545
12546        @Override
12547        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12548            return new PackageParser.ProviderIntentInfo[size];
12549        }
12550
12551        @Override
12552        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12553            if (!sUserManager.exists(userId))
12554                return true;
12555            PackageParser.Package p = filter.provider.owner;
12556            if (p != null) {
12557                PackageSetting ps = (PackageSetting) p.mExtras;
12558                if (ps != null) {
12559                    // System apps are never considered stopped for purposes of
12560                    // filtering, because there may be no way for the user to
12561                    // actually re-launch them.
12562                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12563                            && ps.getStopped(userId);
12564                }
12565            }
12566            return false;
12567        }
12568
12569        @Override
12570        protected boolean isPackageForFilter(String packageName,
12571                PackageParser.ProviderIntentInfo info) {
12572            return packageName.equals(info.provider.owner.packageName);
12573        }
12574
12575        @Override
12576        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12577                int match, int userId) {
12578            if (!sUserManager.exists(userId))
12579                return null;
12580            final PackageParser.ProviderIntentInfo info = filter;
12581            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12582                return null;
12583            }
12584            final PackageParser.Provider provider = info.provider;
12585            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12586            if (ps == null) {
12587                return null;
12588            }
12589            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12590                    ps.readUserState(userId), userId);
12591            if (pi == null) {
12592                return null;
12593            }
12594            final ResolveInfo res = new ResolveInfo();
12595            res.providerInfo = pi;
12596            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12597                res.filter = filter;
12598            }
12599            res.priority = info.getPriority();
12600            res.preferredOrder = provider.owner.mPreferredOrder;
12601            res.match = match;
12602            res.isDefault = info.hasDefault;
12603            res.labelRes = info.labelRes;
12604            res.nonLocalizedLabel = info.nonLocalizedLabel;
12605            res.icon = info.icon;
12606            res.system = res.providerInfo.applicationInfo.isSystemApp();
12607            return res;
12608        }
12609
12610        @Override
12611        protected void sortResults(List<ResolveInfo> results) {
12612            Collections.sort(results, mResolvePrioritySorter);
12613        }
12614
12615        @Override
12616        protected void dumpFilter(PrintWriter out, String prefix,
12617                PackageParser.ProviderIntentInfo filter) {
12618            out.print(prefix);
12619            out.print(
12620                    Integer.toHexString(System.identityHashCode(filter.provider)));
12621            out.print(' ');
12622            filter.provider.printComponentShortName(out);
12623            out.print(" filter ");
12624            out.println(Integer.toHexString(System.identityHashCode(filter)));
12625        }
12626
12627        @Override
12628        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12629            return filter.provider;
12630        }
12631
12632        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12633            PackageParser.Provider provider = (PackageParser.Provider)label;
12634            out.print(prefix); out.print(
12635                    Integer.toHexString(System.identityHashCode(provider)));
12636                    out.print(' ');
12637                    provider.printComponentShortName(out);
12638            if (count > 1) {
12639                out.print(" ("); out.print(count); out.print(" filters)");
12640            }
12641            out.println();
12642        }
12643
12644        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12645                = new ArrayMap<ComponentName, PackageParser.Provider>();
12646        private int mFlags;
12647    }
12648
12649    static final class EphemeralIntentResolver
12650            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12651        /**
12652         * The result that has the highest defined order. Ordering applies on a
12653         * per-package basis. Mapping is from package name to Pair of order and
12654         * EphemeralResolveInfo.
12655         * <p>
12656         * NOTE: This is implemented as a field variable for convenience and efficiency.
12657         * By having a field variable, we're able to track filter ordering as soon as
12658         * a non-zero order is defined. Otherwise, multiple loops across the result set
12659         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12660         * this needs to be contained entirely within {@link #filterResults()}.
12661         */
12662        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12663
12664        @Override
12665        protected EphemeralResponse[] newArray(int size) {
12666            return new EphemeralResponse[size];
12667        }
12668
12669        @Override
12670        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12671            return true;
12672        }
12673
12674        @Override
12675        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12676                int userId) {
12677            if (!sUserManager.exists(userId)) {
12678                return null;
12679            }
12680            final String packageName = responseObj.resolveInfo.getPackageName();
12681            final Integer order = responseObj.getOrder();
12682            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12683                    mOrderResult.get(packageName);
12684            // ordering is enabled and this item's order isn't high enough
12685            if (lastOrderResult != null && lastOrderResult.first >= order) {
12686                return null;
12687            }
12688            final EphemeralResolveInfo res = responseObj.resolveInfo;
12689            if (order > 0) {
12690                // non-zero order, enable ordering
12691                mOrderResult.put(packageName, new Pair<>(order, res));
12692            }
12693            return responseObj;
12694        }
12695
12696        @Override
12697        protected void filterResults(List<EphemeralResponse> results) {
12698            // only do work if ordering is enabled [most of the time it won't be]
12699            if (mOrderResult.size() == 0) {
12700                return;
12701            }
12702            int resultSize = results.size();
12703            for (int i = 0; i < resultSize; i++) {
12704                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12705                final String packageName = info.getPackageName();
12706                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12707                if (savedInfo == null) {
12708                    // package doesn't having ordering
12709                    continue;
12710                }
12711                if (savedInfo.second == info) {
12712                    // circled back to the highest ordered item; remove from order list
12713                    mOrderResult.remove(savedInfo);
12714                    if (mOrderResult.size() == 0) {
12715                        // no more ordered items
12716                        break;
12717                    }
12718                    continue;
12719                }
12720                // item has a worse order, remove it from the result list
12721                results.remove(i);
12722                resultSize--;
12723                i--;
12724            }
12725        }
12726    }
12727
12728    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12729            new Comparator<ResolveInfo>() {
12730        public int compare(ResolveInfo r1, ResolveInfo r2) {
12731            int v1 = r1.priority;
12732            int v2 = r2.priority;
12733            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12734            if (v1 != v2) {
12735                return (v1 > v2) ? -1 : 1;
12736            }
12737            v1 = r1.preferredOrder;
12738            v2 = r2.preferredOrder;
12739            if (v1 != v2) {
12740                return (v1 > v2) ? -1 : 1;
12741            }
12742            if (r1.isDefault != r2.isDefault) {
12743                return r1.isDefault ? -1 : 1;
12744            }
12745            v1 = r1.match;
12746            v2 = r2.match;
12747            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12748            if (v1 != v2) {
12749                return (v1 > v2) ? -1 : 1;
12750            }
12751            if (r1.system != r2.system) {
12752                return r1.system ? -1 : 1;
12753            }
12754            if (r1.activityInfo != null) {
12755                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12756            }
12757            if (r1.serviceInfo != null) {
12758                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12759            }
12760            if (r1.providerInfo != null) {
12761                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12762            }
12763            return 0;
12764        }
12765    };
12766
12767    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12768            new Comparator<ProviderInfo>() {
12769        public int compare(ProviderInfo p1, ProviderInfo p2) {
12770            final int v1 = p1.initOrder;
12771            final int v2 = p2.initOrder;
12772            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12773        }
12774    };
12775
12776    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12777            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12778            final int[] userIds) {
12779        mHandler.post(new Runnable() {
12780            @Override
12781            public void run() {
12782                try {
12783                    final IActivityManager am = ActivityManager.getService();
12784                    if (am == null) return;
12785                    final int[] resolvedUserIds;
12786                    if (userIds == null) {
12787                        resolvedUserIds = am.getRunningUserIds();
12788                    } else {
12789                        resolvedUserIds = userIds;
12790                    }
12791                    for (int id : resolvedUserIds) {
12792                        final Intent intent = new Intent(action,
12793                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12794                        if (extras != null) {
12795                            intent.putExtras(extras);
12796                        }
12797                        if (targetPkg != null) {
12798                            intent.setPackage(targetPkg);
12799                        }
12800                        // Modify the UID when posting to other users
12801                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12802                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12803                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12804                            intent.putExtra(Intent.EXTRA_UID, uid);
12805                        }
12806                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12807                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12808                        if (DEBUG_BROADCASTS) {
12809                            RuntimeException here = new RuntimeException("here");
12810                            here.fillInStackTrace();
12811                            Slog.d(TAG, "Sending to user " + id + ": "
12812                                    + intent.toShortString(false, true, false, false)
12813                                    + " " + intent.getExtras(), here);
12814                        }
12815                        am.broadcastIntent(null, intent, null, finishedReceiver,
12816                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12817                                null, finishedReceiver != null, false, id);
12818                    }
12819                } catch (RemoteException ex) {
12820                }
12821            }
12822        });
12823    }
12824
12825    /**
12826     * Check if the external storage media is available. This is true if there
12827     * is a mounted external storage medium or if the external storage is
12828     * emulated.
12829     */
12830    private boolean isExternalMediaAvailable() {
12831        return mMediaMounted || Environment.isExternalStorageEmulated();
12832    }
12833
12834    @Override
12835    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12836        // writer
12837        synchronized (mPackages) {
12838            if (!isExternalMediaAvailable()) {
12839                // If the external storage is no longer mounted at this point,
12840                // the caller may not have been able to delete all of this
12841                // packages files and can not delete any more.  Bail.
12842                return null;
12843            }
12844            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12845            if (lastPackage != null) {
12846                pkgs.remove(lastPackage);
12847            }
12848            if (pkgs.size() > 0) {
12849                return pkgs.get(0);
12850            }
12851        }
12852        return null;
12853    }
12854
12855    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12856        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12857                userId, andCode ? 1 : 0, packageName);
12858        if (mSystemReady) {
12859            msg.sendToTarget();
12860        } else {
12861            if (mPostSystemReadyMessages == null) {
12862                mPostSystemReadyMessages = new ArrayList<>();
12863            }
12864            mPostSystemReadyMessages.add(msg);
12865        }
12866    }
12867
12868    void startCleaningPackages() {
12869        // reader
12870        if (!isExternalMediaAvailable()) {
12871            return;
12872        }
12873        synchronized (mPackages) {
12874            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12875                return;
12876            }
12877        }
12878        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12879        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12880        IActivityManager am = ActivityManager.getService();
12881        if (am != null) {
12882            try {
12883                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12884                        UserHandle.USER_SYSTEM);
12885            } catch (RemoteException e) {
12886            }
12887        }
12888    }
12889
12890    @Override
12891    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12892            int installFlags, String installerPackageName, int userId) {
12893        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12894
12895        final int callingUid = Binder.getCallingUid();
12896        enforceCrossUserPermission(callingUid, userId,
12897                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12898
12899        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12900            try {
12901                if (observer != null) {
12902                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12903                }
12904            } catch (RemoteException re) {
12905            }
12906            return;
12907        }
12908
12909        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12910            installFlags |= PackageManager.INSTALL_FROM_ADB;
12911
12912        } else {
12913            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12914            // about installerPackageName.
12915
12916            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12917            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12918        }
12919
12920        UserHandle user;
12921        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12922            user = UserHandle.ALL;
12923        } else {
12924            user = new UserHandle(userId);
12925        }
12926
12927        // Only system components can circumvent runtime permissions when installing.
12928        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12929                && mContext.checkCallingOrSelfPermission(Manifest.permission
12930                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12931            throw new SecurityException("You need the "
12932                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12933                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12934        }
12935
12936        final File originFile = new File(originPath);
12937        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12938
12939        final Message msg = mHandler.obtainMessage(INIT_COPY);
12940        final VerificationInfo verificationInfo = new VerificationInfo(
12941                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12942        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12943                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12944                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12945                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12946        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12947        msg.obj = params;
12948
12949        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12950                System.identityHashCode(msg.obj));
12951        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12952                System.identityHashCode(msg.obj));
12953
12954        mHandler.sendMessage(msg);
12955    }
12956
12957
12958    /**
12959     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12960     * it is acting on behalf on an enterprise or the user).
12961     *
12962     * Note that the ordering of the conditionals in this method is important. The checks we perform
12963     * are as follows, in this order:
12964     *
12965     * 1) If the install is being performed by a system app, we can trust the app to have set the
12966     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12967     *    what it is.
12968     * 2) If the install is being performed by a device or profile owner app, the install reason
12969     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12970     *    set the install reason correctly. If the app targets an older SDK version where install
12971     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12972     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12973     * 3) In all other cases, the install is being performed by a regular app that is neither part
12974     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12975     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12976     *    set to enterprise policy and if so, change it to unknown instead.
12977     */
12978    private int fixUpInstallReason(String installerPackageName, int installerUid,
12979            int installReason) {
12980        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12981                == PERMISSION_GRANTED) {
12982            // If the install is being performed by a system app, we trust that app to have set the
12983            // install reason correctly.
12984            return installReason;
12985        }
12986
12987        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12988            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12989        if (dpm != null) {
12990            ComponentName owner = null;
12991            try {
12992                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12993                if (owner == null) {
12994                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12995                }
12996            } catch (RemoteException e) {
12997            }
12998            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12999                // If the install is being performed by a device or profile owner, the install
13000                // reason should be enterprise policy.
13001                return PackageManager.INSTALL_REASON_POLICY;
13002            }
13003        }
13004
13005        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13006            // If the install is being performed by a regular app (i.e. neither system app nor
13007            // device or profile owner), we have no reason to believe that the app is acting on
13008            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13009            // change it to unknown instead.
13010            return PackageManager.INSTALL_REASON_UNKNOWN;
13011        }
13012
13013        // If the install is being performed by a regular app and the install reason was set to any
13014        // value but enterprise policy, leave the install reason unchanged.
13015        return installReason;
13016    }
13017
13018    void installStage(String packageName, File stagedDir, String stagedCid,
13019            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13020            String installerPackageName, int installerUid, UserHandle user,
13021            Certificate[][] certificates) {
13022        if (DEBUG_EPHEMERAL) {
13023            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13024                Slog.d(TAG, "Ephemeral install of " + packageName);
13025            }
13026        }
13027        final VerificationInfo verificationInfo = new VerificationInfo(
13028                sessionParams.originatingUri, sessionParams.referrerUri,
13029                sessionParams.originatingUid, installerUid);
13030
13031        final OriginInfo origin;
13032        if (stagedDir != null) {
13033            origin = OriginInfo.fromStagedFile(stagedDir);
13034        } else {
13035            origin = OriginInfo.fromStagedContainer(stagedCid);
13036        }
13037
13038        final Message msg = mHandler.obtainMessage(INIT_COPY);
13039        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13040                sessionParams.installReason);
13041        final InstallParams params = new InstallParams(origin, null, observer,
13042                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13043                verificationInfo, user, sessionParams.abiOverride,
13044                sessionParams.grantedRuntimePermissions, certificates, installReason);
13045        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13046        msg.obj = params;
13047
13048        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13049                System.identityHashCode(msg.obj));
13050        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13051                System.identityHashCode(msg.obj));
13052
13053        mHandler.sendMessage(msg);
13054    }
13055
13056    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13057            int userId) {
13058        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13059        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13060    }
13061
13062    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13063            int appId, int... userIds) {
13064        if (ArrayUtils.isEmpty(userIds)) {
13065            return;
13066        }
13067        Bundle extras = new Bundle(1);
13068        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13069        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13070
13071        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13072                packageName, extras, 0, null, null, userIds);
13073        if (isSystem) {
13074            mHandler.post(() -> {
13075                        for (int userId : userIds) {
13076                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13077                        }
13078                    }
13079            );
13080        }
13081    }
13082
13083    /**
13084     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13085     * automatically without needing an explicit launch.
13086     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13087     */
13088    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13089        // If user is not running, the app didn't miss any broadcast
13090        if (!mUserManagerInternal.isUserRunning(userId)) {
13091            return;
13092        }
13093        final IActivityManager am = ActivityManager.getService();
13094        try {
13095            // Deliver LOCKED_BOOT_COMPLETED first
13096            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13097                    .setPackage(packageName);
13098            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13099            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13100                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13101
13102            // Deliver BOOT_COMPLETED only if user is unlocked
13103            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13104                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13105                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13106                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13107            }
13108        } catch (RemoteException e) {
13109            throw e.rethrowFromSystemServer();
13110        }
13111    }
13112
13113    @Override
13114    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13115            int userId) {
13116        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13117        PackageSetting pkgSetting;
13118        final int uid = Binder.getCallingUid();
13119        enforceCrossUserPermission(uid, userId,
13120                true /* requireFullPermission */, true /* checkShell */,
13121                "setApplicationHiddenSetting for user " + userId);
13122
13123        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13124            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13125            return false;
13126        }
13127
13128        long callingId = Binder.clearCallingIdentity();
13129        try {
13130            boolean sendAdded = false;
13131            boolean sendRemoved = false;
13132            // writer
13133            synchronized (mPackages) {
13134                pkgSetting = mSettings.mPackages.get(packageName);
13135                if (pkgSetting == null) {
13136                    return false;
13137                }
13138                // Do not allow "android" is being disabled
13139                if ("android".equals(packageName)) {
13140                    Slog.w(TAG, "Cannot hide package: android");
13141                    return false;
13142                }
13143                // Cannot hide static shared libs as they are considered
13144                // a part of the using app (emulating static linking). Also
13145                // static libs are installed always on internal storage.
13146                PackageParser.Package pkg = mPackages.get(packageName);
13147                if (pkg != null && pkg.staticSharedLibName != null) {
13148                    Slog.w(TAG, "Cannot hide package: " + packageName
13149                            + " providing static shared library: "
13150                            + pkg.staticSharedLibName);
13151                    return false;
13152                }
13153                // Only allow protected packages to hide themselves.
13154                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13155                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13156                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13157                    return false;
13158                }
13159
13160                if (pkgSetting.getHidden(userId) != hidden) {
13161                    pkgSetting.setHidden(hidden, userId);
13162                    mSettings.writePackageRestrictionsLPr(userId);
13163                    if (hidden) {
13164                        sendRemoved = true;
13165                    } else {
13166                        sendAdded = true;
13167                    }
13168                }
13169            }
13170            if (sendAdded) {
13171                sendPackageAddedForUser(packageName, pkgSetting, userId);
13172                return true;
13173            }
13174            if (sendRemoved) {
13175                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13176                        "hiding pkg");
13177                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13178                return true;
13179            }
13180        } finally {
13181            Binder.restoreCallingIdentity(callingId);
13182        }
13183        return false;
13184    }
13185
13186    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13187            int userId) {
13188        final PackageRemovedInfo info = new PackageRemovedInfo();
13189        info.removedPackage = packageName;
13190        info.removedUsers = new int[] {userId};
13191        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13192        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13193    }
13194
13195    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13196        if (pkgList.length > 0) {
13197            Bundle extras = new Bundle(1);
13198            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13199
13200            sendPackageBroadcast(
13201                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13202                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13203                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13204                    new int[] {userId});
13205        }
13206    }
13207
13208    /**
13209     * Returns true if application is not found or there was an error. Otherwise it returns
13210     * the hidden state of the package for the given user.
13211     */
13212    @Override
13213    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13214        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13215        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13216                true /* requireFullPermission */, false /* checkShell */,
13217                "getApplicationHidden for user " + userId);
13218        PackageSetting pkgSetting;
13219        long callingId = Binder.clearCallingIdentity();
13220        try {
13221            // writer
13222            synchronized (mPackages) {
13223                pkgSetting = mSettings.mPackages.get(packageName);
13224                if (pkgSetting == null) {
13225                    return true;
13226                }
13227                return pkgSetting.getHidden(userId);
13228            }
13229        } finally {
13230            Binder.restoreCallingIdentity(callingId);
13231        }
13232    }
13233
13234    /**
13235     * @hide
13236     */
13237    @Override
13238    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13239        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13240                null);
13241        PackageSetting pkgSetting;
13242        final int uid = Binder.getCallingUid();
13243        enforceCrossUserPermission(uid, userId,
13244                true /* requireFullPermission */, true /* checkShell */,
13245                "installExistingPackage for user " + userId);
13246        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13247            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13248        }
13249
13250        long callingId = Binder.clearCallingIdentity();
13251        try {
13252            boolean installed = false;
13253
13254            // writer
13255            synchronized (mPackages) {
13256                pkgSetting = mSettings.mPackages.get(packageName);
13257                if (pkgSetting == null) {
13258                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13259                }
13260                if (!pkgSetting.getInstalled(userId)) {
13261                    pkgSetting.setInstalled(true, userId);
13262                    pkgSetting.setHidden(false, userId);
13263                    pkgSetting.setInstallReason(installReason, userId);
13264                    mSettings.writePackageRestrictionsLPr(userId);
13265                    installed = true;
13266                }
13267            }
13268
13269            if (installed) {
13270                if (pkgSetting.pkg != null) {
13271                    synchronized (mInstallLock) {
13272                        // We don't need to freeze for a brand new install
13273                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13274                    }
13275                }
13276                sendPackageAddedForUser(packageName, pkgSetting, userId);
13277            }
13278        } finally {
13279            Binder.restoreCallingIdentity(callingId);
13280        }
13281
13282        return PackageManager.INSTALL_SUCCEEDED;
13283    }
13284
13285    boolean isUserRestricted(int userId, String restrictionKey) {
13286        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13287        if (restrictions.getBoolean(restrictionKey, false)) {
13288            Log.w(TAG, "User is restricted: " + restrictionKey);
13289            return true;
13290        }
13291        return false;
13292    }
13293
13294    @Override
13295    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13296            int userId) {
13297        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13298        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13299                true /* requireFullPermission */, true /* checkShell */,
13300                "setPackagesSuspended for user " + userId);
13301
13302        if (ArrayUtils.isEmpty(packageNames)) {
13303            return packageNames;
13304        }
13305
13306        // List of package names for whom the suspended state has changed.
13307        List<String> changedPackages = new ArrayList<>(packageNames.length);
13308        // List of package names for whom the suspended state is not set as requested in this
13309        // method.
13310        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13311        long callingId = Binder.clearCallingIdentity();
13312        try {
13313            for (int i = 0; i < packageNames.length; i++) {
13314                String packageName = packageNames[i];
13315                boolean changed = false;
13316                final int appId;
13317                synchronized (mPackages) {
13318                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13319                    if (pkgSetting == null) {
13320                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13321                                + "\". Skipping suspending/un-suspending.");
13322                        unactionedPackages.add(packageName);
13323                        continue;
13324                    }
13325                    appId = pkgSetting.appId;
13326                    if (pkgSetting.getSuspended(userId) != suspended) {
13327                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13328                            unactionedPackages.add(packageName);
13329                            continue;
13330                        }
13331                        pkgSetting.setSuspended(suspended, userId);
13332                        mSettings.writePackageRestrictionsLPr(userId);
13333                        changed = true;
13334                        changedPackages.add(packageName);
13335                    }
13336                }
13337
13338                if (changed && suspended) {
13339                    killApplication(packageName, UserHandle.getUid(userId, appId),
13340                            "suspending package");
13341                }
13342            }
13343        } finally {
13344            Binder.restoreCallingIdentity(callingId);
13345        }
13346
13347        if (!changedPackages.isEmpty()) {
13348            sendPackagesSuspendedForUser(changedPackages.toArray(
13349                    new String[changedPackages.size()]), userId, suspended);
13350        }
13351
13352        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13353    }
13354
13355    @Override
13356    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13357        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13358                true /* requireFullPermission */, false /* checkShell */,
13359                "isPackageSuspendedForUser for user " + userId);
13360        synchronized (mPackages) {
13361            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13362            if (pkgSetting == null) {
13363                throw new IllegalArgumentException("Unknown target package: " + packageName);
13364            }
13365            return pkgSetting.getSuspended(userId);
13366        }
13367    }
13368
13369    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13370        if (isPackageDeviceAdmin(packageName, userId)) {
13371            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13372                    + "\": has an active device admin");
13373            return false;
13374        }
13375
13376        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13377        if (packageName.equals(activeLauncherPackageName)) {
13378            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13379                    + "\": contains the active launcher");
13380            return false;
13381        }
13382
13383        if (packageName.equals(mRequiredInstallerPackage)) {
13384            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13385                    + "\": required for package installation");
13386            return false;
13387        }
13388
13389        if (packageName.equals(mRequiredUninstallerPackage)) {
13390            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13391                    + "\": required for package uninstallation");
13392            return false;
13393        }
13394
13395        if (packageName.equals(mRequiredVerifierPackage)) {
13396            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13397                    + "\": required for package verification");
13398            return false;
13399        }
13400
13401        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13402            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13403                    + "\": is the default dialer");
13404            return false;
13405        }
13406
13407        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13408            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13409                    + "\": protected package");
13410            return false;
13411        }
13412
13413        // Cannot suspend static shared libs as they are considered
13414        // a part of the using app (emulating static linking). Also
13415        // static libs are installed always on internal storage.
13416        PackageParser.Package pkg = mPackages.get(packageName);
13417        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13418            Slog.w(TAG, "Cannot suspend package: " + packageName
13419                    + " providing static shared library: "
13420                    + pkg.staticSharedLibName);
13421            return false;
13422        }
13423
13424        return true;
13425    }
13426
13427    private String getActiveLauncherPackageName(int userId) {
13428        Intent intent = new Intent(Intent.ACTION_MAIN);
13429        intent.addCategory(Intent.CATEGORY_HOME);
13430        ResolveInfo resolveInfo = resolveIntent(
13431                intent,
13432                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13433                PackageManager.MATCH_DEFAULT_ONLY,
13434                userId);
13435
13436        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13437    }
13438
13439    private String getDefaultDialerPackageName(int userId) {
13440        synchronized (mPackages) {
13441            return mSettings.getDefaultDialerPackageNameLPw(userId);
13442        }
13443    }
13444
13445    @Override
13446    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13447        mContext.enforceCallingOrSelfPermission(
13448                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13449                "Only package verification agents can verify applications");
13450
13451        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13452        final PackageVerificationResponse response = new PackageVerificationResponse(
13453                verificationCode, Binder.getCallingUid());
13454        msg.arg1 = id;
13455        msg.obj = response;
13456        mHandler.sendMessage(msg);
13457    }
13458
13459    @Override
13460    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13461            long millisecondsToDelay) {
13462        mContext.enforceCallingOrSelfPermission(
13463                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13464                "Only package verification agents can extend verification timeouts");
13465
13466        final PackageVerificationState state = mPendingVerification.get(id);
13467        final PackageVerificationResponse response = new PackageVerificationResponse(
13468                verificationCodeAtTimeout, Binder.getCallingUid());
13469
13470        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13471            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13472        }
13473        if (millisecondsToDelay < 0) {
13474            millisecondsToDelay = 0;
13475        }
13476        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13477                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13478            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13479        }
13480
13481        if ((state != null) && !state.timeoutExtended()) {
13482            state.extendTimeout();
13483
13484            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13485            msg.arg1 = id;
13486            msg.obj = response;
13487            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13488        }
13489    }
13490
13491    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13492            int verificationCode, UserHandle user) {
13493        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13494        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13495        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13496        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13497        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13498
13499        mContext.sendBroadcastAsUser(intent, user,
13500                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13501    }
13502
13503    private ComponentName matchComponentForVerifier(String packageName,
13504            List<ResolveInfo> receivers) {
13505        ActivityInfo targetReceiver = null;
13506
13507        final int NR = receivers.size();
13508        for (int i = 0; i < NR; i++) {
13509            final ResolveInfo info = receivers.get(i);
13510            if (info.activityInfo == null) {
13511                continue;
13512            }
13513
13514            if (packageName.equals(info.activityInfo.packageName)) {
13515                targetReceiver = info.activityInfo;
13516                break;
13517            }
13518        }
13519
13520        if (targetReceiver == null) {
13521            return null;
13522        }
13523
13524        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13525    }
13526
13527    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13528            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13529        if (pkgInfo.verifiers.length == 0) {
13530            return null;
13531        }
13532
13533        final int N = pkgInfo.verifiers.length;
13534        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13535        for (int i = 0; i < N; i++) {
13536            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13537
13538            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13539                    receivers);
13540            if (comp == null) {
13541                continue;
13542            }
13543
13544            final int verifierUid = getUidForVerifier(verifierInfo);
13545            if (verifierUid == -1) {
13546                continue;
13547            }
13548
13549            if (DEBUG_VERIFY) {
13550                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13551                        + " with the correct signature");
13552            }
13553            sufficientVerifiers.add(comp);
13554            verificationState.addSufficientVerifier(verifierUid);
13555        }
13556
13557        return sufficientVerifiers;
13558    }
13559
13560    private int getUidForVerifier(VerifierInfo verifierInfo) {
13561        synchronized (mPackages) {
13562            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13563            if (pkg == null) {
13564                return -1;
13565            } else if (pkg.mSignatures.length != 1) {
13566                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13567                        + " has more than one signature; ignoring");
13568                return -1;
13569            }
13570
13571            /*
13572             * If the public key of the package's signature does not match
13573             * our expected public key, then this is a different package and
13574             * we should skip.
13575             */
13576
13577            final byte[] expectedPublicKey;
13578            try {
13579                final Signature verifierSig = pkg.mSignatures[0];
13580                final PublicKey publicKey = verifierSig.getPublicKey();
13581                expectedPublicKey = publicKey.getEncoded();
13582            } catch (CertificateException e) {
13583                return -1;
13584            }
13585
13586            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13587
13588            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13589                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13590                        + " does not have the expected public key; ignoring");
13591                return -1;
13592            }
13593
13594            return pkg.applicationInfo.uid;
13595        }
13596    }
13597
13598    @Override
13599    public void finishPackageInstall(int token, boolean didLaunch) {
13600        enforceSystemOrRoot("Only the system is allowed to finish installs");
13601
13602        if (DEBUG_INSTALL) {
13603            Slog.v(TAG, "BM finishing package install for " + token);
13604        }
13605        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13606
13607        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13608        mHandler.sendMessage(msg);
13609    }
13610
13611    /**
13612     * Get the verification agent timeout.
13613     *
13614     * @return verification timeout in milliseconds
13615     */
13616    private long getVerificationTimeout() {
13617        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13618                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13619                DEFAULT_VERIFICATION_TIMEOUT);
13620    }
13621
13622    /**
13623     * Get the default verification agent response code.
13624     *
13625     * @return default verification response code
13626     */
13627    private int getDefaultVerificationResponse() {
13628        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13629                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13630                DEFAULT_VERIFICATION_RESPONSE);
13631    }
13632
13633    /**
13634     * Check whether or not package verification has been enabled.
13635     *
13636     * @return true if verification should be performed
13637     */
13638    private boolean isVerificationEnabled(int userId, int installFlags) {
13639        if (!DEFAULT_VERIFY_ENABLE) {
13640            return false;
13641        }
13642        // Ephemeral apps don't get the full verification treatment
13643        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13644            if (DEBUG_EPHEMERAL) {
13645                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13646            }
13647            return false;
13648        }
13649
13650        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13651
13652        // Check if installing from ADB
13653        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13654            // Do not run verification in a test harness environment
13655            if (ActivityManager.isRunningInTestHarness()) {
13656                return false;
13657            }
13658            if (ensureVerifyAppsEnabled) {
13659                return true;
13660            }
13661            // Check if the developer does not want package verification for ADB installs
13662            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13663                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13664                return false;
13665            }
13666        }
13667
13668        if (ensureVerifyAppsEnabled) {
13669            return true;
13670        }
13671
13672        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13673                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13674    }
13675
13676    @Override
13677    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13678            throws RemoteException {
13679        mContext.enforceCallingOrSelfPermission(
13680                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13681                "Only intentfilter verification agents can verify applications");
13682
13683        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13684        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13685                Binder.getCallingUid(), verificationCode, failedDomains);
13686        msg.arg1 = id;
13687        msg.obj = response;
13688        mHandler.sendMessage(msg);
13689    }
13690
13691    @Override
13692    public int getIntentVerificationStatus(String packageName, int userId) {
13693        synchronized (mPackages) {
13694            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13695        }
13696    }
13697
13698    @Override
13699    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13700        mContext.enforceCallingOrSelfPermission(
13701                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13702
13703        boolean result = false;
13704        synchronized (mPackages) {
13705            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13706        }
13707        if (result) {
13708            scheduleWritePackageRestrictionsLocked(userId);
13709        }
13710        return result;
13711    }
13712
13713    @Override
13714    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13715            String packageName) {
13716        synchronized (mPackages) {
13717            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13718        }
13719    }
13720
13721    @Override
13722    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13723        if (TextUtils.isEmpty(packageName)) {
13724            return ParceledListSlice.emptyList();
13725        }
13726        synchronized (mPackages) {
13727            PackageParser.Package pkg = mPackages.get(packageName);
13728            if (pkg == null || pkg.activities == null) {
13729                return ParceledListSlice.emptyList();
13730            }
13731            final int count = pkg.activities.size();
13732            ArrayList<IntentFilter> result = new ArrayList<>();
13733            for (int n=0; n<count; n++) {
13734                PackageParser.Activity activity = pkg.activities.get(n);
13735                if (activity.intents != null && activity.intents.size() > 0) {
13736                    result.addAll(activity.intents);
13737                }
13738            }
13739            return new ParceledListSlice<>(result);
13740        }
13741    }
13742
13743    @Override
13744    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13745        mContext.enforceCallingOrSelfPermission(
13746                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13747
13748        synchronized (mPackages) {
13749            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13750            if (packageName != null) {
13751                result |= updateIntentVerificationStatus(packageName,
13752                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13753                        userId);
13754                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13755                        packageName, userId);
13756            }
13757            return result;
13758        }
13759    }
13760
13761    @Override
13762    public String getDefaultBrowserPackageName(int userId) {
13763        synchronized (mPackages) {
13764            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13765        }
13766    }
13767
13768    /**
13769     * Get the "allow unknown sources" setting.
13770     *
13771     * @return the current "allow unknown sources" setting
13772     */
13773    private int getUnknownSourcesSettings() {
13774        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13775                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13776                -1);
13777    }
13778
13779    @Override
13780    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13781        final int uid = Binder.getCallingUid();
13782        // writer
13783        synchronized (mPackages) {
13784            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13785            if (targetPackageSetting == null) {
13786                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13787            }
13788
13789            PackageSetting installerPackageSetting;
13790            if (installerPackageName != null) {
13791                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13792                if (installerPackageSetting == null) {
13793                    throw new IllegalArgumentException("Unknown installer package: "
13794                            + installerPackageName);
13795                }
13796            } else {
13797                installerPackageSetting = null;
13798            }
13799
13800            Signature[] callerSignature;
13801            Object obj = mSettings.getUserIdLPr(uid);
13802            if (obj != null) {
13803                if (obj instanceof SharedUserSetting) {
13804                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13805                } else if (obj instanceof PackageSetting) {
13806                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13807                } else {
13808                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13809                }
13810            } else {
13811                throw new SecurityException("Unknown calling UID: " + uid);
13812            }
13813
13814            // Verify: can't set installerPackageName to a package that is
13815            // not signed with the same cert as the caller.
13816            if (installerPackageSetting != null) {
13817                if (compareSignatures(callerSignature,
13818                        installerPackageSetting.signatures.mSignatures)
13819                        != PackageManager.SIGNATURE_MATCH) {
13820                    throw new SecurityException(
13821                            "Caller does not have same cert as new installer package "
13822                            + installerPackageName);
13823                }
13824            }
13825
13826            // Verify: if target already has an installer package, it must
13827            // be signed with the same cert as the caller.
13828            if (targetPackageSetting.installerPackageName != null) {
13829                PackageSetting setting = mSettings.mPackages.get(
13830                        targetPackageSetting.installerPackageName);
13831                // If the currently set package isn't valid, then it's always
13832                // okay to change it.
13833                if (setting != null) {
13834                    if (compareSignatures(callerSignature,
13835                            setting.signatures.mSignatures)
13836                            != PackageManager.SIGNATURE_MATCH) {
13837                        throw new SecurityException(
13838                                "Caller does not have same cert as old installer package "
13839                                + targetPackageSetting.installerPackageName);
13840                    }
13841                }
13842            }
13843
13844            // Okay!
13845            targetPackageSetting.installerPackageName = installerPackageName;
13846            if (installerPackageName != null) {
13847                mSettings.mInstallerPackages.add(installerPackageName);
13848            }
13849            scheduleWriteSettingsLocked();
13850        }
13851    }
13852
13853    @Override
13854    public void setApplicationCategoryHint(String packageName, int categoryHint,
13855            String callerPackageName) {
13856        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13857                callerPackageName);
13858        synchronized (mPackages) {
13859            PackageSetting ps = mSettings.mPackages.get(packageName);
13860            if (ps == null) {
13861                throw new IllegalArgumentException("Unknown target package " + packageName);
13862            }
13863
13864            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13865                throw new IllegalArgumentException("Calling package " + callerPackageName
13866                        + " is not installer for " + packageName);
13867            }
13868
13869            if (ps.categoryHint != categoryHint) {
13870                ps.categoryHint = categoryHint;
13871                scheduleWriteSettingsLocked();
13872            }
13873        }
13874    }
13875
13876    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13877        // Queue up an async operation since the package installation may take a little while.
13878        mHandler.post(new Runnable() {
13879            public void run() {
13880                mHandler.removeCallbacks(this);
13881                 // Result object to be returned
13882                PackageInstalledInfo res = new PackageInstalledInfo();
13883                res.setReturnCode(currentStatus);
13884                res.uid = -1;
13885                res.pkg = null;
13886                res.removedInfo = null;
13887                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13888                    args.doPreInstall(res.returnCode);
13889                    synchronized (mInstallLock) {
13890                        installPackageTracedLI(args, res);
13891                    }
13892                    args.doPostInstall(res.returnCode, res.uid);
13893                }
13894
13895                // A restore should be performed at this point if (a) the install
13896                // succeeded, (b) the operation is not an update, and (c) the new
13897                // package has not opted out of backup participation.
13898                final boolean update = res.removedInfo != null
13899                        && res.removedInfo.removedPackage != null;
13900                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13901                boolean doRestore = !update
13902                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13903
13904                // Set up the post-install work request bookkeeping.  This will be used
13905                // and cleaned up by the post-install event handling regardless of whether
13906                // there's a restore pass performed.  Token values are >= 1.
13907                int token;
13908                if (mNextInstallToken < 0) mNextInstallToken = 1;
13909                token = mNextInstallToken++;
13910
13911                PostInstallData data = new PostInstallData(args, res);
13912                mRunningInstalls.put(token, data);
13913                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13914
13915                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13916                    // Pass responsibility to the Backup Manager.  It will perform a
13917                    // restore if appropriate, then pass responsibility back to the
13918                    // Package Manager to run the post-install observer callbacks
13919                    // and broadcasts.
13920                    IBackupManager bm = IBackupManager.Stub.asInterface(
13921                            ServiceManager.getService(Context.BACKUP_SERVICE));
13922                    if (bm != null) {
13923                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13924                                + " to BM for possible restore");
13925                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13926                        try {
13927                            // TODO: http://b/22388012
13928                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13929                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13930                            } else {
13931                                doRestore = false;
13932                            }
13933                        } catch (RemoteException e) {
13934                            // can't happen; the backup manager is local
13935                        } catch (Exception e) {
13936                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13937                            doRestore = false;
13938                        }
13939                    } else {
13940                        Slog.e(TAG, "Backup Manager not found!");
13941                        doRestore = false;
13942                    }
13943                }
13944
13945                if (!doRestore) {
13946                    // No restore possible, or the Backup Manager was mysteriously not
13947                    // available -- just fire the post-install work request directly.
13948                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13949
13950                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13951
13952                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13953                    mHandler.sendMessage(msg);
13954                }
13955            }
13956        });
13957    }
13958
13959    /**
13960     * Callback from PackageSettings whenever an app is first transitioned out of the
13961     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13962     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13963     * here whether the app is the target of an ongoing install, and only send the
13964     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13965     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13966     * handling.
13967     */
13968    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13969        // Serialize this with the rest of the install-process message chain.  In the
13970        // restore-at-install case, this Runnable will necessarily run before the
13971        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13972        // are coherent.  In the non-restore case, the app has already completed install
13973        // and been launched through some other means, so it is not in a problematic
13974        // state for observers to see the FIRST_LAUNCH signal.
13975        mHandler.post(new Runnable() {
13976            @Override
13977            public void run() {
13978                for (int i = 0; i < mRunningInstalls.size(); i++) {
13979                    final PostInstallData data = mRunningInstalls.valueAt(i);
13980                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13981                        continue;
13982                    }
13983                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13984                        // right package; but is it for the right user?
13985                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13986                            if (userId == data.res.newUsers[uIndex]) {
13987                                if (DEBUG_BACKUP) {
13988                                    Slog.i(TAG, "Package " + pkgName
13989                                            + " being restored so deferring FIRST_LAUNCH");
13990                                }
13991                                return;
13992                            }
13993                        }
13994                    }
13995                }
13996                // didn't find it, so not being restored
13997                if (DEBUG_BACKUP) {
13998                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13999                }
14000                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14001            }
14002        });
14003    }
14004
14005    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14006        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14007                installerPkg, null, userIds);
14008    }
14009
14010    private abstract class HandlerParams {
14011        private static final int MAX_RETRIES = 4;
14012
14013        /**
14014         * Number of times startCopy() has been attempted and had a non-fatal
14015         * error.
14016         */
14017        private int mRetries = 0;
14018
14019        /** User handle for the user requesting the information or installation. */
14020        private final UserHandle mUser;
14021        String traceMethod;
14022        int traceCookie;
14023
14024        HandlerParams(UserHandle user) {
14025            mUser = user;
14026        }
14027
14028        UserHandle getUser() {
14029            return mUser;
14030        }
14031
14032        HandlerParams setTraceMethod(String traceMethod) {
14033            this.traceMethod = traceMethod;
14034            return this;
14035        }
14036
14037        HandlerParams setTraceCookie(int traceCookie) {
14038            this.traceCookie = traceCookie;
14039            return this;
14040        }
14041
14042        final boolean startCopy() {
14043            boolean res;
14044            try {
14045                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14046
14047                if (++mRetries > MAX_RETRIES) {
14048                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14049                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14050                    handleServiceError();
14051                    return false;
14052                } else {
14053                    handleStartCopy();
14054                    res = true;
14055                }
14056            } catch (RemoteException e) {
14057                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14058                mHandler.sendEmptyMessage(MCS_RECONNECT);
14059                res = false;
14060            }
14061            handleReturnCode();
14062            return res;
14063        }
14064
14065        final void serviceError() {
14066            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14067            handleServiceError();
14068            handleReturnCode();
14069        }
14070
14071        abstract void handleStartCopy() throws RemoteException;
14072        abstract void handleServiceError();
14073        abstract void handleReturnCode();
14074    }
14075
14076    class MeasureParams extends HandlerParams {
14077        private final PackageStats mStats;
14078        private boolean mSuccess;
14079
14080        private final IPackageStatsObserver mObserver;
14081
14082        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14083            super(new UserHandle(stats.userHandle));
14084            mObserver = observer;
14085            mStats = stats;
14086        }
14087
14088        @Override
14089        public String toString() {
14090            return "MeasureParams{"
14091                + Integer.toHexString(System.identityHashCode(this))
14092                + " " + mStats.packageName + "}";
14093        }
14094
14095        @Override
14096        void handleStartCopy() throws RemoteException {
14097            synchronized (mInstallLock) {
14098                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14099            }
14100
14101            if (mSuccess) {
14102                boolean mounted = false;
14103                try {
14104                    final String status = Environment.getExternalStorageState();
14105                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14106                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14107                } catch (Exception e) {
14108                }
14109
14110                if (mounted) {
14111                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14112
14113                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14114                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14115
14116                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14117                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14118
14119                    // Always subtract cache size, since it's a subdirectory
14120                    mStats.externalDataSize -= mStats.externalCacheSize;
14121
14122                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14123                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14124
14125                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14126                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14127                }
14128            }
14129        }
14130
14131        @Override
14132        void handleReturnCode() {
14133            if (mObserver != null) {
14134                try {
14135                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14136                } catch (RemoteException e) {
14137                    Slog.i(TAG, "Observer no longer exists.");
14138                }
14139            }
14140        }
14141
14142        @Override
14143        void handleServiceError() {
14144            Slog.e(TAG, "Could not measure application " + mStats.packageName
14145                            + " external storage");
14146        }
14147    }
14148
14149    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14150            throws RemoteException {
14151        long result = 0;
14152        for (File path : paths) {
14153            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14154        }
14155        return result;
14156    }
14157
14158    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14159        for (File path : paths) {
14160            try {
14161                mcs.clearDirectory(path.getAbsolutePath());
14162            } catch (RemoteException e) {
14163            }
14164        }
14165    }
14166
14167    static class OriginInfo {
14168        /**
14169         * Location where install is coming from, before it has been
14170         * copied/renamed into place. This could be a single monolithic APK
14171         * file, or a cluster directory. This location may be untrusted.
14172         */
14173        final File file;
14174        final String cid;
14175
14176        /**
14177         * Flag indicating that {@link #file} or {@link #cid} has already been
14178         * staged, meaning downstream users don't need to defensively copy the
14179         * contents.
14180         */
14181        final boolean staged;
14182
14183        /**
14184         * Flag indicating that {@link #file} or {@link #cid} is an already
14185         * installed app that is being moved.
14186         */
14187        final boolean existing;
14188
14189        final String resolvedPath;
14190        final File resolvedFile;
14191
14192        static OriginInfo fromNothing() {
14193            return new OriginInfo(null, null, false, false);
14194        }
14195
14196        static OriginInfo fromUntrustedFile(File file) {
14197            return new OriginInfo(file, null, false, false);
14198        }
14199
14200        static OriginInfo fromExistingFile(File file) {
14201            return new OriginInfo(file, null, false, true);
14202        }
14203
14204        static OriginInfo fromStagedFile(File file) {
14205            return new OriginInfo(file, null, true, false);
14206        }
14207
14208        static OriginInfo fromStagedContainer(String cid) {
14209            return new OriginInfo(null, cid, true, false);
14210        }
14211
14212        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14213            this.file = file;
14214            this.cid = cid;
14215            this.staged = staged;
14216            this.existing = existing;
14217
14218            if (cid != null) {
14219                resolvedPath = PackageHelper.getSdDir(cid);
14220                resolvedFile = new File(resolvedPath);
14221            } else if (file != null) {
14222                resolvedPath = file.getAbsolutePath();
14223                resolvedFile = file;
14224            } else {
14225                resolvedPath = null;
14226                resolvedFile = null;
14227            }
14228        }
14229    }
14230
14231    static class MoveInfo {
14232        final int moveId;
14233        final String fromUuid;
14234        final String toUuid;
14235        final String packageName;
14236        final String dataAppName;
14237        final int appId;
14238        final String seinfo;
14239        final int targetSdkVersion;
14240
14241        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14242                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14243            this.moveId = moveId;
14244            this.fromUuid = fromUuid;
14245            this.toUuid = toUuid;
14246            this.packageName = packageName;
14247            this.dataAppName = dataAppName;
14248            this.appId = appId;
14249            this.seinfo = seinfo;
14250            this.targetSdkVersion = targetSdkVersion;
14251        }
14252    }
14253
14254    static class VerificationInfo {
14255        /** A constant used to indicate that a uid value is not present. */
14256        public static final int NO_UID = -1;
14257
14258        /** URI referencing where the package was downloaded from. */
14259        final Uri originatingUri;
14260
14261        /** HTTP referrer URI associated with the originatingURI. */
14262        final Uri referrer;
14263
14264        /** UID of the application that the install request originated from. */
14265        final int originatingUid;
14266
14267        /** UID of application requesting the install */
14268        final int installerUid;
14269
14270        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14271            this.originatingUri = originatingUri;
14272            this.referrer = referrer;
14273            this.originatingUid = originatingUid;
14274            this.installerUid = installerUid;
14275        }
14276    }
14277
14278    class InstallParams extends HandlerParams {
14279        final OriginInfo origin;
14280        final MoveInfo move;
14281        final IPackageInstallObserver2 observer;
14282        int installFlags;
14283        final String installerPackageName;
14284        final String volumeUuid;
14285        private InstallArgs mArgs;
14286        private int mRet;
14287        final String packageAbiOverride;
14288        final String[] grantedRuntimePermissions;
14289        final VerificationInfo verificationInfo;
14290        final Certificate[][] certificates;
14291        final int installReason;
14292
14293        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14294                int installFlags, String installerPackageName, String volumeUuid,
14295                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14296                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14297            super(user);
14298            this.origin = origin;
14299            this.move = move;
14300            this.observer = observer;
14301            this.installFlags = installFlags;
14302            this.installerPackageName = installerPackageName;
14303            this.volumeUuid = volumeUuid;
14304            this.verificationInfo = verificationInfo;
14305            this.packageAbiOverride = packageAbiOverride;
14306            this.grantedRuntimePermissions = grantedPermissions;
14307            this.certificates = certificates;
14308            this.installReason = installReason;
14309        }
14310
14311        @Override
14312        public String toString() {
14313            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14314                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14315        }
14316
14317        private int installLocationPolicy(PackageInfoLite pkgLite) {
14318            String packageName = pkgLite.packageName;
14319            int installLocation = pkgLite.installLocation;
14320            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14321            // reader
14322            synchronized (mPackages) {
14323                // Currently installed package which the new package is attempting to replace or
14324                // null if no such package is installed.
14325                PackageParser.Package installedPkg = mPackages.get(packageName);
14326                // Package which currently owns the data which the new package will own if installed.
14327                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14328                // will be null whereas dataOwnerPkg will contain information about the package
14329                // which was uninstalled while keeping its data.
14330                PackageParser.Package dataOwnerPkg = installedPkg;
14331                if (dataOwnerPkg  == null) {
14332                    PackageSetting ps = mSettings.mPackages.get(packageName);
14333                    if (ps != null) {
14334                        dataOwnerPkg = ps.pkg;
14335                    }
14336                }
14337
14338                if (dataOwnerPkg != null) {
14339                    // If installed, the package will get access to data left on the device by its
14340                    // predecessor. As a security measure, this is permited only if this is not a
14341                    // version downgrade or if the predecessor package is marked as debuggable and
14342                    // a downgrade is explicitly requested.
14343                    //
14344                    // On debuggable platform builds, downgrades are permitted even for
14345                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14346                    // not offer security guarantees and thus it's OK to disable some security
14347                    // mechanisms to make debugging/testing easier on those builds. However, even on
14348                    // debuggable builds downgrades of packages are permitted only if requested via
14349                    // installFlags. This is because we aim to keep the behavior of debuggable
14350                    // platform builds as close as possible to the behavior of non-debuggable
14351                    // platform builds.
14352                    final boolean downgradeRequested =
14353                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14354                    final boolean packageDebuggable =
14355                                (dataOwnerPkg.applicationInfo.flags
14356                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14357                    final boolean downgradePermitted =
14358                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14359                    if (!downgradePermitted) {
14360                        try {
14361                            checkDowngrade(dataOwnerPkg, pkgLite);
14362                        } catch (PackageManagerException e) {
14363                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14364                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14365                        }
14366                    }
14367                }
14368
14369                if (installedPkg != null) {
14370                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14371                        // Check for updated system application.
14372                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14373                            if (onSd) {
14374                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14375                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14376                            }
14377                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14378                        } else {
14379                            if (onSd) {
14380                                // Install flag overrides everything.
14381                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14382                            }
14383                            // If current upgrade specifies particular preference
14384                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14385                                // Application explicitly specified internal.
14386                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14387                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14388                                // App explictly prefers external. Let policy decide
14389                            } else {
14390                                // Prefer previous location
14391                                if (isExternal(installedPkg)) {
14392                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14393                                }
14394                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14395                            }
14396                        }
14397                    } else {
14398                        // Invalid install. Return error code
14399                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14400                    }
14401                }
14402            }
14403            // All the special cases have been taken care of.
14404            // Return result based on recommended install location.
14405            if (onSd) {
14406                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14407            }
14408            return pkgLite.recommendedInstallLocation;
14409        }
14410
14411        /*
14412         * Invoke remote method to get package information and install
14413         * location values. Override install location based on default
14414         * policy if needed and then create install arguments based
14415         * on the install location.
14416         */
14417        public void handleStartCopy() throws RemoteException {
14418            int ret = PackageManager.INSTALL_SUCCEEDED;
14419
14420            // If we're already staged, we've firmly committed to an install location
14421            if (origin.staged) {
14422                if (origin.file != null) {
14423                    installFlags |= PackageManager.INSTALL_INTERNAL;
14424                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14425                } else if (origin.cid != null) {
14426                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14427                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14428                } else {
14429                    throw new IllegalStateException("Invalid stage location");
14430                }
14431            }
14432
14433            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14434            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14435            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14436            PackageInfoLite pkgLite = null;
14437
14438            if (onInt && onSd) {
14439                // Check if both bits are set.
14440                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14441                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14442            } else if (onSd && ephemeral) {
14443                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14444                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14445            } else {
14446                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14447                        packageAbiOverride);
14448
14449                if (DEBUG_EPHEMERAL && ephemeral) {
14450                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14451                }
14452
14453                /*
14454                 * If we have too little free space, try to free cache
14455                 * before giving up.
14456                 */
14457                if (!origin.staged && pkgLite.recommendedInstallLocation
14458                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14459                    // TODO: focus freeing disk space on the target device
14460                    final StorageManager storage = StorageManager.from(mContext);
14461                    final long lowThreshold = storage.getStorageLowBytes(
14462                            Environment.getDataDirectory());
14463
14464                    final long sizeBytes = mContainerService.calculateInstalledSize(
14465                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14466
14467                    try {
14468                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14469                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14470                                installFlags, packageAbiOverride);
14471                    } catch (InstallerException e) {
14472                        Slog.w(TAG, "Failed to free cache", e);
14473                    }
14474
14475                    /*
14476                     * The cache free must have deleted the file we
14477                     * downloaded to install.
14478                     *
14479                     * TODO: fix the "freeCache" call to not delete
14480                     *       the file we care about.
14481                     */
14482                    if (pkgLite.recommendedInstallLocation
14483                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14484                        pkgLite.recommendedInstallLocation
14485                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14486                    }
14487                }
14488            }
14489
14490            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14491                int loc = pkgLite.recommendedInstallLocation;
14492                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14493                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14494                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14495                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14496                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14497                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14498                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14499                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14500                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14501                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14502                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14503                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14504                } else {
14505                    // Override with defaults if needed.
14506                    loc = installLocationPolicy(pkgLite);
14507                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14508                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14509                    } else if (!onSd && !onInt) {
14510                        // Override install location with flags
14511                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14512                            // Set the flag to install on external media.
14513                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14514                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14515                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14516                            if (DEBUG_EPHEMERAL) {
14517                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14518                            }
14519                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14520                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14521                                    |PackageManager.INSTALL_INTERNAL);
14522                        } else {
14523                            // Make sure the flag for installing on external
14524                            // media is unset
14525                            installFlags |= PackageManager.INSTALL_INTERNAL;
14526                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14527                        }
14528                    }
14529                }
14530            }
14531
14532            final InstallArgs args = createInstallArgs(this);
14533            mArgs = args;
14534
14535            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14536                // TODO: http://b/22976637
14537                // Apps installed for "all" users use the device owner to verify the app
14538                UserHandle verifierUser = getUser();
14539                if (verifierUser == UserHandle.ALL) {
14540                    verifierUser = UserHandle.SYSTEM;
14541                }
14542
14543                /*
14544                 * Determine if we have any installed package verifiers. If we
14545                 * do, then we'll defer to them to verify the packages.
14546                 */
14547                final int requiredUid = mRequiredVerifierPackage == null ? -1
14548                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14549                                verifierUser.getIdentifier());
14550                if (!origin.existing && requiredUid != -1
14551                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14552                    final Intent verification = new Intent(
14553                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14554                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14555                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14556                            PACKAGE_MIME_TYPE);
14557                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14558
14559                    // Query all live verifiers based on current user state
14560                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14561                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14562
14563                    if (DEBUG_VERIFY) {
14564                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14565                                + verification.toString() + " with " + pkgLite.verifiers.length
14566                                + " optional verifiers");
14567                    }
14568
14569                    final int verificationId = mPendingVerificationToken++;
14570
14571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14572
14573                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14574                            installerPackageName);
14575
14576                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14577                            installFlags);
14578
14579                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14580                            pkgLite.packageName);
14581
14582                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14583                            pkgLite.versionCode);
14584
14585                    if (verificationInfo != null) {
14586                        if (verificationInfo.originatingUri != null) {
14587                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14588                                    verificationInfo.originatingUri);
14589                        }
14590                        if (verificationInfo.referrer != null) {
14591                            verification.putExtra(Intent.EXTRA_REFERRER,
14592                                    verificationInfo.referrer);
14593                        }
14594                        if (verificationInfo.originatingUid >= 0) {
14595                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14596                                    verificationInfo.originatingUid);
14597                        }
14598                        if (verificationInfo.installerUid >= 0) {
14599                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14600                                    verificationInfo.installerUid);
14601                        }
14602                    }
14603
14604                    final PackageVerificationState verificationState = new PackageVerificationState(
14605                            requiredUid, args);
14606
14607                    mPendingVerification.append(verificationId, verificationState);
14608
14609                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14610                            receivers, verificationState);
14611
14612                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14613                    final long idleDuration = getVerificationTimeout();
14614
14615                    /*
14616                     * If any sufficient verifiers were listed in the package
14617                     * manifest, attempt to ask them.
14618                     */
14619                    if (sufficientVerifiers != null) {
14620                        final int N = sufficientVerifiers.size();
14621                        if (N == 0) {
14622                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14623                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14624                        } else {
14625                            for (int i = 0; i < N; i++) {
14626                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14627                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14628                                        verifierComponent.getPackageName(), idleDuration,
14629                                        verifierUser.getIdentifier(), false, "package verifier");
14630
14631                                final Intent sufficientIntent = new Intent(verification);
14632                                sufficientIntent.setComponent(verifierComponent);
14633                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14634                            }
14635                        }
14636                    }
14637
14638                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14639                            mRequiredVerifierPackage, receivers);
14640                    if (ret == PackageManager.INSTALL_SUCCEEDED
14641                            && mRequiredVerifierPackage != null) {
14642                        Trace.asyncTraceBegin(
14643                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14644                        /*
14645                         * Send the intent to the required verification agent,
14646                         * but only start the verification timeout after the
14647                         * target BroadcastReceivers have run.
14648                         */
14649                        verification.setComponent(requiredVerifierComponent);
14650                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14651                                requiredVerifierComponent.getPackageName(), idleDuration,
14652                                verifierUser.getIdentifier(), false, "package verifier");
14653                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14654                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14655                                new BroadcastReceiver() {
14656                                    @Override
14657                                    public void onReceive(Context context, Intent intent) {
14658                                        final Message msg = mHandler
14659                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14660                                        msg.arg1 = verificationId;
14661                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14662                                    }
14663                                }, null, 0, null, null);
14664
14665                        /*
14666                         * We don't want the copy to proceed until verification
14667                         * succeeds, so null out this field.
14668                         */
14669                        mArgs = null;
14670                    }
14671                } else {
14672                    /*
14673                     * No package verification is enabled, so immediately start
14674                     * the remote call to initiate copy using temporary file.
14675                     */
14676                    ret = args.copyApk(mContainerService, true);
14677                }
14678            }
14679
14680            mRet = ret;
14681        }
14682
14683        @Override
14684        void handleReturnCode() {
14685            // If mArgs is null, then MCS couldn't be reached. When it
14686            // reconnects, it will try again to install. At that point, this
14687            // will succeed.
14688            if (mArgs != null) {
14689                processPendingInstall(mArgs, mRet);
14690            }
14691        }
14692
14693        @Override
14694        void handleServiceError() {
14695            mArgs = createInstallArgs(this);
14696            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14697        }
14698
14699        public boolean isForwardLocked() {
14700            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14701        }
14702    }
14703
14704    /**
14705     * Used during creation of InstallArgs
14706     *
14707     * @param installFlags package installation flags
14708     * @return true if should be installed on external storage
14709     */
14710    private static boolean installOnExternalAsec(int installFlags) {
14711        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14712            return false;
14713        }
14714        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14715            return true;
14716        }
14717        return false;
14718    }
14719
14720    /**
14721     * Used during creation of InstallArgs
14722     *
14723     * @param installFlags package installation flags
14724     * @return true if should be installed as forward locked
14725     */
14726    private static boolean installForwardLocked(int installFlags) {
14727        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14728    }
14729
14730    private InstallArgs createInstallArgs(InstallParams params) {
14731        if (params.move != null) {
14732            return new MoveInstallArgs(params);
14733        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14734            return new AsecInstallArgs(params);
14735        } else {
14736            return new FileInstallArgs(params);
14737        }
14738    }
14739
14740    /**
14741     * Create args that describe an existing installed package. Typically used
14742     * when cleaning up old installs, or used as a move source.
14743     */
14744    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14745            String resourcePath, String[] instructionSets) {
14746        final boolean isInAsec;
14747        if (installOnExternalAsec(installFlags)) {
14748            /* Apps on SD card are always in ASEC containers. */
14749            isInAsec = true;
14750        } else if (installForwardLocked(installFlags)
14751                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14752            /*
14753             * Forward-locked apps are only in ASEC containers if they're the
14754             * new style
14755             */
14756            isInAsec = true;
14757        } else {
14758            isInAsec = false;
14759        }
14760
14761        if (isInAsec) {
14762            return new AsecInstallArgs(codePath, instructionSets,
14763                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14764        } else {
14765            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14766        }
14767    }
14768
14769    static abstract class InstallArgs {
14770        /** @see InstallParams#origin */
14771        final OriginInfo origin;
14772        /** @see InstallParams#move */
14773        final MoveInfo move;
14774
14775        final IPackageInstallObserver2 observer;
14776        // Always refers to PackageManager flags only
14777        final int installFlags;
14778        final String installerPackageName;
14779        final String volumeUuid;
14780        final UserHandle user;
14781        final String abiOverride;
14782        final String[] installGrantPermissions;
14783        /** If non-null, drop an async trace when the install completes */
14784        final String traceMethod;
14785        final int traceCookie;
14786        final Certificate[][] certificates;
14787        final int installReason;
14788
14789        // The list of instruction sets supported by this app. This is currently
14790        // only used during the rmdex() phase to clean up resources. We can get rid of this
14791        // if we move dex files under the common app path.
14792        /* nullable */ String[] instructionSets;
14793
14794        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14795                int installFlags, String installerPackageName, String volumeUuid,
14796                UserHandle user, String[] instructionSets,
14797                String abiOverride, String[] installGrantPermissions,
14798                String traceMethod, int traceCookie, Certificate[][] certificates,
14799                int installReason) {
14800            this.origin = origin;
14801            this.move = move;
14802            this.installFlags = installFlags;
14803            this.observer = observer;
14804            this.installerPackageName = installerPackageName;
14805            this.volumeUuid = volumeUuid;
14806            this.user = user;
14807            this.instructionSets = instructionSets;
14808            this.abiOverride = abiOverride;
14809            this.installGrantPermissions = installGrantPermissions;
14810            this.traceMethod = traceMethod;
14811            this.traceCookie = traceCookie;
14812            this.certificates = certificates;
14813            this.installReason = installReason;
14814        }
14815
14816        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14817        abstract int doPreInstall(int status);
14818
14819        /**
14820         * Rename package into final resting place. All paths on the given
14821         * scanned package should be updated to reflect the rename.
14822         */
14823        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14824        abstract int doPostInstall(int status, int uid);
14825
14826        /** @see PackageSettingBase#codePathString */
14827        abstract String getCodePath();
14828        /** @see PackageSettingBase#resourcePathString */
14829        abstract String getResourcePath();
14830
14831        // Need installer lock especially for dex file removal.
14832        abstract void cleanUpResourcesLI();
14833        abstract boolean doPostDeleteLI(boolean delete);
14834
14835        /**
14836         * Called before the source arguments are copied. This is used mostly
14837         * for MoveParams when it needs to read the source file to put it in the
14838         * destination.
14839         */
14840        int doPreCopy() {
14841            return PackageManager.INSTALL_SUCCEEDED;
14842        }
14843
14844        /**
14845         * Called after the source arguments are copied. This is used mostly for
14846         * MoveParams when it needs to read the source file to put it in the
14847         * destination.
14848         */
14849        int doPostCopy(int uid) {
14850            return PackageManager.INSTALL_SUCCEEDED;
14851        }
14852
14853        protected boolean isFwdLocked() {
14854            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14855        }
14856
14857        protected boolean isExternalAsec() {
14858            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14859        }
14860
14861        protected boolean isEphemeral() {
14862            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14863        }
14864
14865        UserHandle getUser() {
14866            return user;
14867        }
14868    }
14869
14870    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14871        if (!allCodePaths.isEmpty()) {
14872            if (instructionSets == null) {
14873                throw new IllegalStateException("instructionSet == null");
14874            }
14875            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14876            for (String codePath : allCodePaths) {
14877                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14878                    try {
14879                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14880                    } catch (InstallerException ignored) {
14881                    }
14882                }
14883            }
14884        }
14885    }
14886
14887    /**
14888     * Logic to handle installation of non-ASEC applications, including copying
14889     * and renaming logic.
14890     */
14891    class FileInstallArgs extends InstallArgs {
14892        private File codeFile;
14893        private File resourceFile;
14894
14895        // Example topology:
14896        // /data/app/com.example/base.apk
14897        // /data/app/com.example/split_foo.apk
14898        // /data/app/com.example/lib/arm/libfoo.so
14899        // /data/app/com.example/lib/arm64/libfoo.so
14900        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14901
14902        /** New install */
14903        FileInstallArgs(InstallParams params) {
14904            super(params.origin, params.move, params.observer, params.installFlags,
14905                    params.installerPackageName, params.volumeUuid,
14906                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14907                    params.grantedRuntimePermissions,
14908                    params.traceMethod, params.traceCookie, params.certificates,
14909                    params.installReason);
14910            if (isFwdLocked()) {
14911                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14912            }
14913        }
14914
14915        /** Existing install */
14916        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14917            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14918                    null, null, null, 0, null /*certificates*/,
14919                    PackageManager.INSTALL_REASON_UNKNOWN);
14920            this.codeFile = (codePath != null) ? new File(codePath) : null;
14921            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14922        }
14923
14924        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14925            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14926            try {
14927                return doCopyApk(imcs, temp);
14928            } finally {
14929                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14930            }
14931        }
14932
14933        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14934            if (origin.staged) {
14935                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14936                codeFile = origin.file;
14937                resourceFile = origin.file;
14938                return PackageManager.INSTALL_SUCCEEDED;
14939            }
14940
14941            try {
14942                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14943                final File tempDir =
14944                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14945                codeFile = tempDir;
14946                resourceFile = tempDir;
14947            } catch (IOException e) {
14948                Slog.w(TAG, "Failed to create copy file: " + e);
14949                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14950            }
14951
14952            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14953                @Override
14954                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14955                    if (!FileUtils.isValidExtFilename(name)) {
14956                        throw new IllegalArgumentException("Invalid filename: " + name);
14957                    }
14958                    try {
14959                        final File file = new File(codeFile, name);
14960                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14961                                O_RDWR | O_CREAT, 0644);
14962                        Os.chmod(file.getAbsolutePath(), 0644);
14963                        return new ParcelFileDescriptor(fd);
14964                    } catch (ErrnoException e) {
14965                        throw new RemoteException("Failed to open: " + e.getMessage());
14966                    }
14967                }
14968            };
14969
14970            int ret = PackageManager.INSTALL_SUCCEEDED;
14971            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14972            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14973                Slog.e(TAG, "Failed to copy package");
14974                return ret;
14975            }
14976
14977            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14978            NativeLibraryHelper.Handle handle = null;
14979            try {
14980                handle = NativeLibraryHelper.Handle.create(codeFile);
14981                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14982                        abiOverride);
14983            } catch (IOException e) {
14984                Slog.e(TAG, "Copying native libraries failed", e);
14985                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14986            } finally {
14987                IoUtils.closeQuietly(handle);
14988            }
14989
14990            return ret;
14991        }
14992
14993        int doPreInstall(int status) {
14994            if (status != PackageManager.INSTALL_SUCCEEDED) {
14995                cleanUp();
14996            }
14997            return status;
14998        }
14999
15000        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15001            if (status != PackageManager.INSTALL_SUCCEEDED) {
15002                cleanUp();
15003                return false;
15004            }
15005
15006            final File targetDir = codeFile.getParentFile();
15007            final File beforeCodeFile = codeFile;
15008            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15009
15010            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15011            try {
15012                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15013            } catch (ErrnoException e) {
15014                Slog.w(TAG, "Failed to rename", e);
15015                return false;
15016            }
15017
15018            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15019                Slog.w(TAG, "Failed to restorecon");
15020                return false;
15021            }
15022
15023            // Reflect the rename internally
15024            codeFile = afterCodeFile;
15025            resourceFile = afterCodeFile;
15026
15027            // Reflect the rename in scanned details
15028            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15029            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15030                    afterCodeFile, pkg.baseCodePath));
15031            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15032                    afterCodeFile, pkg.splitCodePaths));
15033
15034            // Reflect the rename in app info
15035            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15036            pkg.setApplicationInfoCodePath(pkg.codePath);
15037            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15038            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15039            pkg.setApplicationInfoResourcePath(pkg.codePath);
15040            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15041            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15042
15043            return true;
15044        }
15045
15046        int doPostInstall(int status, int uid) {
15047            if (status != PackageManager.INSTALL_SUCCEEDED) {
15048                cleanUp();
15049            }
15050            return status;
15051        }
15052
15053        @Override
15054        String getCodePath() {
15055            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15056        }
15057
15058        @Override
15059        String getResourcePath() {
15060            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15061        }
15062
15063        private boolean cleanUp() {
15064            if (codeFile == null || !codeFile.exists()) {
15065                return false;
15066            }
15067
15068            removeCodePathLI(codeFile);
15069
15070            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15071                resourceFile.delete();
15072            }
15073
15074            return true;
15075        }
15076
15077        void cleanUpResourcesLI() {
15078            // Try enumerating all code paths before deleting
15079            List<String> allCodePaths = Collections.EMPTY_LIST;
15080            if (codeFile != null && codeFile.exists()) {
15081                try {
15082                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15083                    allCodePaths = pkg.getAllCodePaths();
15084                } catch (PackageParserException e) {
15085                    // Ignored; we tried our best
15086                }
15087            }
15088
15089            cleanUp();
15090            removeDexFiles(allCodePaths, instructionSets);
15091        }
15092
15093        boolean doPostDeleteLI(boolean delete) {
15094            // XXX err, shouldn't we respect the delete flag?
15095            cleanUpResourcesLI();
15096            return true;
15097        }
15098    }
15099
15100    private boolean isAsecExternal(String cid) {
15101        final String asecPath = PackageHelper.getSdFilesystem(cid);
15102        return !asecPath.startsWith(mAsecInternalPath);
15103    }
15104
15105    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15106            PackageManagerException {
15107        if (copyRet < 0) {
15108            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15109                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15110                throw new PackageManagerException(copyRet, message);
15111            }
15112        }
15113    }
15114
15115    /**
15116     * Extract the StorageManagerService "container ID" from the full code path of an
15117     * .apk.
15118     */
15119    static String cidFromCodePath(String fullCodePath) {
15120        int eidx = fullCodePath.lastIndexOf("/");
15121        String subStr1 = fullCodePath.substring(0, eidx);
15122        int sidx = subStr1.lastIndexOf("/");
15123        return subStr1.substring(sidx+1, eidx);
15124    }
15125
15126    /**
15127     * Logic to handle installation of ASEC applications, including copying and
15128     * renaming logic.
15129     */
15130    class AsecInstallArgs extends InstallArgs {
15131        static final String RES_FILE_NAME = "pkg.apk";
15132        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15133
15134        String cid;
15135        String packagePath;
15136        String resourcePath;
15137
15138        /** New install */
15139        AsecInstallArgs(InstallParams params) {
15140            super(params.origin, params.move, params.observer, params.installFlags,
15141                    params.installerPackageName, params.volumeUuid,
15142                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15143                    params.grantedRuntimePermissions,
15144                    params.traceMethod, params.traceCookie, params.certificates,
15145                    params.installReason);
15146        }
15147
15148        /** Existing install */
15149        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15150                        boolean isExternal, boolean isForwardLocked) {
15151            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15152                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15153                    instructionSets, null, null, null, 0, null /*certificates*/,
15154                    PackageManager.INSTALL_REASON_UNKNOWN);
15155            // Hackily pretend we're still looking at a full code path
15156            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15157                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15158            }
15159
15160            // Extract cid from fullCodePath
15161            int eidx = fullCodePath.lastIndexOf("/");
15162            String subStr1 = fullCodePath.substring(0, eidx);
15163            int sidx = subStr1.lastIndexOf("/");
15164            cid = subStr1.substring(sidx+1, eidx);
15165            setMountPath(subStr1);
15166        }
15167
15168        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15169            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15170                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15171                    instructionSets, null, null, null, 0, null /*certificates*/,
15172                    PackageManager.INSTALL_REASON_UNKNOWN);
15173            this.cid = cid;
15174            setMountPath(PackageHelper.getSdDir(cid));
15175        }
15176
15177        void createCopyFile() {
15178            cid = mInstallerService.allocateExternalStageCidLegacy();
15179        }
15180
15181        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15182            if (origin.staged && origin.cid != null) {
15183                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15184                cid = origin.cid;
15185                setMountPath(PackageHelper.getSdDir(cid));
15186                return PackageManager.INSTALL_SUCCEEDED;
15187            }
15188
15189            if (temp) {
15190                createCopyFile();
15191            } else {
15192                /*
15193                 * Pre-emptively destroy the container since it's destroyed if
15194                 * copying fails due to it existing anyway.
15195                 */
15196                PackageHelper.destroySdDir(cid);
15197            }
15198
15199            final String newMountPath = imcs.copyPackageToContainer(
15200                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15201                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15202
15203            if (newMountPath != null) {
15204                setMountPath(newMountPath);
15205                return PackageManager.INSTALL_SUCCEEDED;
15206            } else {
15207                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15208            }
15209        }
15210
15211        @Override
15212        String getCodePath() {
15213            return packagePath;
15214        }
15215
15216        @Override
15217        String getResourcePath() {
15218            return resourcePath;
15219        }
15220
15221        int doPreInstall(int status) {
15222            if (status != PackageManager.INSTALL_SUCCEEDED) {
15223                // Destroy container
15224                PackageHelper.destroySdDir(cid);
15225            } else {
15226                boolean mounted = PackageHelper.isContainerMounted(cid);
15227                if (!mounted) {
15228                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15229                            Process.SYSTEM_UID);
15230                    if (newMountPath != null) {
15231                        setMountPath(newMountPath);
15232                    } else {
15233                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15234                    }
15235                }
15236            }
15237            return status;
15238        }
15239
15240        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15241            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15242            String newMountPath = null;
15243            if (PackageHelper.isContainerMounted(cid)) {
15244                // Unmount the container
15245                if (!PackageHelper.unMountSdDir(cid)) {
15246                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15247                    return false;
15248                }
15249            }
15250            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15251                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15252                        " which might be stale. Will try to clean up.");
15253                // Clean up the stale container and proceed to recreate.
15254                if (!PackageHelper.destroySdDir(newCacheId)) {
15255                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15256                    return false;
15257                }
15258                // Successfully cleaned up stale container. Try to rename again.
15259                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15260                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15261                            + " inspite of cleaning it up.");
15262                    return false;
15263                }
15264            }
15265            if (!PackageHelper.isContainerMounted(newCacheId)) {
15266                Slog.w(TAG, "Mounting container " + newCacheId);
15267                newMountPath = PackageHelper.mountSdDir(newCacheId,
15268                        getEncryptKey(), Process.SYSTEM_UID);
15269            } else {
15270                newMountPath = PackageHelper.getSdDir(newCacheId);
15271            }
15272            if (newMountPath == null) {
15273                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15274                return false;
15275            }
15276            Log.i(TAG, "Succesfully renamed " + cid +
15277                    " to " + newCacheId +
15278                    " at new path: " + newMountPath);
15279            cid = newCacheId;
15280
15281            final File beforeCodeFile = new File(packagePath);
15282            setMountPath(newMountPath);
15283            final File afterCodeFile = new File(packagePath);
15284
15285            // Reflect the rename in scanned details
15286            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15287            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15288                    afterCodeFile, pkg.baseCodePath));
15289            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15290                    afterCodeFile, pkg.splitCodePaths));
15291
15292            // Reflect the rename in app info
15293            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15294            pkg.setApplicationInfoCodePath(pkg.codePath);
15295            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15296            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15297            pkg.setApplicationInfoResourcePath(pkg.codePath);
15298            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15299            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15300
15301            return true;
15302        }
15303
15304        private void setMountPath(String mountPath) {
15305            final File mountFile = new File(mountPath);
15306
15307            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15308            if (monolithicFile.exists()) {
15309                packagePath = monolithicFile.getAbsolutePath();
15310                if (isFwdLocked()) {
15311                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15312                } else {
15313                    resourcePath = packagePath;
15314                }
15315            } else {
15316                packagePath = mountFile.getAbsolutePath();
15317                resourcePath = packagePath;
15318            }
15319        }
15320
15321        int doPostInstall(int status, int uid) {
15322            if (status != PackageManager.INSTALL_SUCCEEDED) {
15323                cleanUp();
15324            } else {
15325                final int groupOwner;
15326                final String protectedFile;
15327                if (isFwdLocked()) {
15328                    groupOwner = UserHandle.getSharedAppGid(uid);
15329                    protectedFile = RES_FILE_NAME;
15330                } else {
15331                    groupOwner = -1;
15332                    protectedFile = null;
15333                }
15334
15335                if (uid < Process.FIRST_APPLICATION_UID
15336                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15337                    Slog.e(TAG, "Failed to finalize " + cid);
15338                    PackageHelper.destroySdDir(cid);
15339                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15340                }
15341
15342                boolean mounted = PackageHelper.isContainerMounted(cid);
15343                if (!mounted) {
15344                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15345                }
15346            }
15347            return status;
15348        }
15349
15350        private void cleanUp() {
15351            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15352
15353            // Destroy secure container
15354            PackageHelper.destroySdDir(cid);
15355        }
15356
15357        private List<String> getAllCodePaths() {
15358            final File codeFile = new File(getCodePath());
15359            if (codeFile != null && codeFile.exists()) {
15360                try {
15361                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15362                    return pkg.getAllCodePaths();
15363                } catch (PackageParserException e) {
15364                    // Ignored; we tried our best
15365                }
15366            }
15367            return Collections.EMPTY_LIST;
15368        }
15369
15370        void cleanUpResourcesLI() {
15371            // Enumerate all code paths before deleting
15372            cleanUpResourcesLI(getAllCodePaths());
15373        }
15374
15375        private void cleanUpResourcesLI(List<String> allCodePaths) {
15376            cleanUp();
15377            removeDexFiles(allCodePaths, instructionSets);
15378        }
15379
15380        String getPackageName() {
15381            return getAsecPackageName(cid);
15382        }
15383
15384        boolean doPostDeleteLI(boolean delete) {
15385            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15386            final List<String> allCodePaths = getAllCodePaths();
15387            boolean mounted = PackageHelper.isContainerMounted(cid);
15388            if (mounted) {
15389                // Unmount first
15390                if (PackageHelper.unMountSdDir(cid)) {
15391                    mounted = false;
15392                }
15393            }
15394            if (!mounted && delete) {
15395                cleanUpResourcesLI(allCodePaths);
15396            }
15397            return !mounted;
15398        }
15399
15400        @Override
15401        int doPreCopy() {
15402            if (isFwdLocked()) {
15403                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15404                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15405                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15406                }
15407            }
15408
15409            return PackageManager.INSTALL_SUCCEEDED;
15410        }
15411
15412        @Override
15413        int doPostCopy(int uid) {
15414            if (isFwdLocked()) {
15415                if (uid < Process.FIRST_APPLICATION_UID
15416                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15417                                RES_FILE_NAME)) {
15418                    Slog.e(TAG, "Failed to finalize " + cid);
15419                    PackageHelper.destroySdDir(cid);
15420                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15421                }
15422            }
15423
15424            return PackageManager.INSTALL_SUCCEEDED;
15425        }
15426    }
15427
15428    /**
15429     * Logic to handle movement of existing installed applications.
15430     */
15431    class MoveInstallArgs extends InstallArgs {
15432        private File codeFile;
15433        private File resourceFile;
15434
15435        /** New install */
15436        MoveInstallArgs(InstallParams params) {
15437            super(params.origin, params.move, params.observer, params.installFlags,
15438                    params.installerPackageName, params.volumeUuid,
15439                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15440                    params.grantedRuntimePermissions,
15441                    params.traceMethod, params.traceCookie, params.certificates,
15442                    params.installReason);
15443        }
15444
15445        int copyApk(IMediaContainerService imcs, boolean temp) {
15446            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15447                    + move.fromUuid + " to " + move.toUuid);
15448            synchronized (mInstaller) {
15449                try {
15450                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15451                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15452                } catch (InstallerException e) {
15453                    Slog.w(TAG, "Failed to move app", e);
15454                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15455                }
15456            }
15457
15458            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15459            resourceFile = codeFile;
15460            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15461
15462            return PackageManager.INSTALL_SUCCEEDED;
15463        }
15464
15465        int doPreInstall(int status) {
15466            if (status != PackageManager.INSTALL_SUCCEEDED) {
15467                cleanUp(move.toUuid);
15468            }
15469            return status;
15470        }
15471
15472        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15473            if (status != PackageManager.INSTALL_SUCCEEDED) {
15474                cleanUp(move.toUuid);
15475                return false;
15476            }
15477
15478            // Reflect the move in app info
15479            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15480            pkg.setApplicationInfoCodePath(pkg.codePath);
15481            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15482            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15483            pkg.setApplicationInfoResourcePath(pkg.codePath);
15484            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15485            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15486
15487            return true;
15488        }
15489
15490        int doPostInstall(int status, int uid) {
15491            if (status == PackageManager.INSTALL_SUCCEEDED) {
15492                cleanUp(move.fromUuid);
15493            } else {
15494                cleanUp(move.toUuid);
15495            }
15496            return status;
15497        }
15498
15499        @Override
15500        String getCodePath() {
15501            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15502        }
15503
15504        @Override
15505        String getResourcePath() {
15506            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15507        }
15508
15509        private boolean cleanUp(String volumeUuid) {
15510            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15511                    move.dataAppName);
15512            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15513            final int[] userIds = sUserManager.getUserIds();
15514            synchronized (mInstallLock) {
15515                // Clean up both app data and code
15516                // All package moves are frozen until finished
15517                for (int userId : userIds) {
15518                    try {
15519                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15520                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15521                    } catch (InstallerException e) {
15522                        Slog.w(TAG, String.valueOf(e));
15523                    }
15524                }
15525                removeCodePathLI(codeFile);
15526            }
15527            return true;
15528        }
15529
15530        void cleanUpResourcesLI() {
15531            throw new UnsupportedOperationException();
15532        }
15533
15534        boolean doPostDeleteLI(boolean delete) {
15535            throw new UnsupportedOperationException();
15536        }
15537    }
15538
15539    static String getAsecPackageName(String packageCid) {
15540        int idx = packageCid.lastIndexOf("-");
15541        if (idx == -1) {
15542            return packageCid;
15543        }
15544        return packageCid.substring(0, idx);
15545    }
15546
15547    // Utility method used to create code paths based on package name and available index.
15548    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15549        String idxStr = "";
15550        int idx = 1;
15551        // Fall back to default value of idx=1 if prefix is not
15552        // part of oldCodePath
15553        if (oldCodePath != null) {
15554            String subStr = oldCodePath;
15555            // Drop the suffix right away
15556            if (suffix != null && subStr.endsWith(suffix)) {
15557                subStr = subStr.substring(0, subStr.length() - suffix.length());
15558            }
15559            // If oldCodePath already contains prefix find out the
15560            // ending index to either increment or decrement.
15561            int sidx = subStr.lastIndexOf(prefix);
15562            if (sidx != -1) {
15563                subStr = subStr.substring(sidx + prefix.length());
15564                if (subStr != null) {
15565                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15566                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15567                    }
15568                    try {
15569                        idx = Integer.parseInt(subStr);
15570                        if (idx <= 1) {
15571                            idx++;
15572                        } else {
15573                            idx--;
15574                        }
15575                    } catch(NumberFormatException e) {
15576                    }
15577                }
15578            }
15579        }
15580        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15581        return prefix + idxStr;
15582    }
15583
15584    private File getNextCodePath(File targetDir, String packageName) {
15585        File result;
15586        SecureRandom random = new SecureRandom();
15587        byte[] bytes = new byte[16];
15588        do {
15589            random.nextBytes(bytes);
15590            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15591            result = new File(targetDir, packageName + "-" + suffix);
15592        } while (result.exists());
15593        return result;
15594    }
15595
15596    // Utility method that returns the relative package path with respect
15597    // to the installation directory. Like say for /data/data/com.test-1.apk
15598    // string com.test-1 is returned.
15599    static String deriveCodePathName(String codePath) {
15600        if (codePath == null) {
15601            return null;
15602        }
15603        final File codeFile = new File(codePath);
15604        final String name = codeFile.getName();
15605        if (codeFile.isDirectory()) {
15606            return name;
15607        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15608            final int lastDot = name.lastIndexOf('.');
15609            return name.substring(0, lastDot);
15610        } else {
15611            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15612            return null;
15613        }
15614    }
15615
15616    static class PackageInstalledInfo {
15617        String name;
15618        int uid;
15619        // The set of users that originally had this package installed.
15620        int[] origUsers;
15621        // The set of users that now have this package installed.
15622        int[] newUsers;
15623        PackageParser.Package pkg;
15624        int returnCode;
15625        String returnMsg;
15626        PackageRemovedInfo removedInfo;
15627        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15628
15629        public void setError(int code, String msg) {
15630            setReturnCode(code);
15631            setReturnMessage(msg);
15632            Slog.w(TAG, msg);
15633        }
15634
15635        public void setError(String msg, PackageParserException e) {
15636            setReturnCode(e.error);
15637            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15638            Slog.w(TAG, msg, e);
15639        }
15640
15641        public void setError(String msg, PackageManagerException e) {
15642            returnCode = e.error;
15643            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15644            Slog.w(TAG, msg, e);
15645        }
15646
15647        public void setReturnCode(int returnCode) {
15648            this.returnCode = returnCode;
15649            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15650            for (int i = 0; i < childCount; i++) {
15651                addedChildPackages.valueAt(i).returnCode = returnCode;
15652            }
15653        }
15654
15655        private void setReturnMessage(String returnMsg) {
15656            this.returnMsg = returnMsg;
15657            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15658            for (int i = 0; i < childCount; i++) {
15659                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15660            }
15661        }
15662
15663        // In some error cases we want to convey more info back to the observer
15664        String origPackage;
15665        String origPermission;
15666    }
15667
15668    /*
15669     * Install a non-existing package.
15670     */
15671    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15672            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15673            PackageInstalledInfo res, int installReason) {
15674        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15675
15676        // Remember this for later, in case we need to rollback this install
15677        String pkgName = pkg.packageName;
15678
15679        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15680
15681        synchronized(mPackages) {
15682            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15683            if (renamedPackage != null) {
15684                // A package with the same name is already installed, though
15685                // it has been renamed to an older name.  The package we
15686                // are trying to install should be installed as an update to
15687                // the existing one, but that has not been requested, so bail.
15688                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15689                        + " without first uninstalling package running as "
15690                        + renamedPackage);
15691                return;
15692            }
15693            if (mPackages.containsKey(pkgName)) {
15694                // Don't allow installation over an existing package with the same name.
15695                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15696                        + " without first uninstalling.");
15697                return;
15698            }
15699        }
15700
15701        try {
15702            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15703                    System.currentTimeMillis(), user);
15704
15705            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15706
15707            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15708                prepareAppDataAfterInstallLIF(newPackage);
15709
15710            } else {
15711                // Remove package from internal structures, but keep around any
15712                // data that might have already existed
15713                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15714                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15715            }
15716        } catch (PackageManagerException e) {
15717            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15718        }
15719
15720        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15721    }
15722
15723    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15724        // Can't rotate keys during boot or if sharedUser.
15725        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15726                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15727            return false;
15728        }
15729        // app is using upgradeKeySets; make sure all are valid
15730        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15731        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15732        for (int i = 0; i < upgradeKeySets.length; i++) {
15733            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15734                Slog.wtf(TAG, "Package "
15735                         + (oldPs.name != null ? oldPs.name : "<null>")
15736                         + " contains upgrade-key-set reference to unknown key-set: "
15737                         + upgradeKeySets[i]
15738                         + " reverting to signatures check.");
15739                return false;
15740            }
15741        }
15742        return true;
15743    }
15744
15745    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15746        // Upgrade keysets are being used.  Determine if new package has a superset of the
15747        // required keys.
15748        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15749        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15750        for (int i = 0; i < upgradeKeySets.length; i++) {
15751            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15752            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15753                return true;
15754            }
15755        }
15756        return false;
15757    }
15758
15759    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15760        try (DigestInputStream digestStream =
15761                new DigestInputStream(new FileInputStream(file), digest)) {
15762            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15763        }
15764    }
15765
15766    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15767            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15768            int installReason) {
15769        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15770
15771        final PackageParser.Package oldPackage;
15772        final String pkgName = pkg.packageName;
15773        final int[] allUsers;
15774        final int[] installedUsers;
15775
15776        synchronized(mPackages) {
15777            oldPackage = mPackages.get(pkgName);
15778            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15779
15780            // don't allow upgrade to target a release SDK from a pre-release SDK
15781            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15782                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15783            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15784                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15785            if (oldTargetsPreRelease
15786                    && !newTargetsPreRelease
15787                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15788                Slog.w(TAG, "Can't install package targeting released sdk");
15789                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15790                return;
15791            }
15792
15793            // don't allow an upgrade from full to ephemeral
15794            final boolean oldIsEphemeral = oldPackage.applicationInfo.isInstantApp();
15795            if (isEphemeral && !oldIsEphemeral) {
15796                // can't downgrade from full to ephemeral
15797                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15798                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15799                return;
15800            }
15801
15802            // verify signatures are valid
15803            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15804            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15805                if (!checkUpgradeKeySetLP(ps, pkg)) {
15806                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15807                            "New package not signed by keys specified by upgrade-keysets: "
15808                                    + pkgName);
15809                    return;
15810                }
15811            } else {
15812                // default to original signature matching
15813                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15814                        != PackageManager.SIGNATURE_MATCH) {
15815                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15816                            "New package has a different signature: " + pkgName);
15817                    return;
15818                }
15819            }
15820
15821            // don't allow a system upgrade unless the upgrade hash matches
15822            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15823                byte[] digestBytes = null;
15824                try {
15825                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15826                    updateDigest(digest, new File(pkg.baseCodePath));
15827                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15828                        for (String path : pkg.splitCodePaths) {
15829                            updateDigest(digest, new File(path));
15830                        }
15831                    }
15832                    digestBytes = digest.digest();
15833                } catch (NoSuchAlgorithmException | IOException e) {
15834                    res.setError(INSTALL_FAILED_INVALID_APK,
15835                            "Could not compute hash: " + pkgName);
15836                    return;
15837                }
15838                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15839                    res.setError(INSTALL_FAILED_INVALID_APK,
15840                            "New package fails restrict-update check: " + pkgName);
15841                    return;
15842                }
15843                // retain upgrade restriction
15844                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15845            }
15846
15847            // Check for shared user id changes
15848            String invalidPackageName =
15849                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15850            if (invalidPackageName != null) {
15851                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15852                        "Package " + invalidPackageName + " tried to change user "
15853                                + oldPackage.mSharedUserId);
15854                return;
15855            }
15856
15857            // In case of rollback, remember per-user/profile install state
15858            allUsers = sUserManager.getUserIds();
15859            installedUsers = ps.queryInstalledUsers(allUsers, true);
15860        }
15861
15862        // Update what is removed
15863        res.removedInfo = new PackageRemovedInfo();
15864        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15865        res.removedInfo.removedPackage = oldPackage.packageName;
15866        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15867        res.removedInfo.isUpdate = true;
15868        res.removedInfo.origUsers = installedUsers;
15869        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15870        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15871        for (int i = 0; i < installedUsers.length; i++) {
15872            final int userId = installedUsers[i];
15873            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15874        }
15875
15876        final int childCount = (oldPackage.childPackages != null)
15877                ? oldPackage.childPackages.size() : 0;
15878        for (int i = 0; i < childCount; i++) {
15879            boolean childPackageUpdated = false;
15880            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15881            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15882            if (res.addedChildPackages != null) {
15883                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15884                if (childRes != null) {
15885                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15886                    childRes.removedInfo.removedPackage = childPkg.packageName;
15887                    childRes.removedInfo.isUpdate = true;
15888                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15889                    childPackageUpdated = true;
15890                }
15891            }
15892            if (!childPackageUpdated) {
15893                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15894                childRemovedRes.removedPackage = childPkg.packageName;
15895                childRemovedRes.isUpdate = false;
15896                childRemovedRes.dataRemoved = true;
15897                synchronized (mPackages) {
15898                    if (childPs != null) {
15899                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15900                    }
15901                }
15902                if (res.removedInfo.removedChildPackages == null) {
15903                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15904                }
15905                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15906            }
15907        }
15908
15909        boolean sysPkg = (isSystemApp(oldPackage));
15910        if (sysPkg) {
15911            // Set the system/privileged flags as needed
15912            final boolean privileged =
15913                    (oldPackage.applicationInfo.privateFlags
15914                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15915            final int systemPolicyFlags = policyFlags
15916                    | PackageParser.PARSE_IS_SYSTEM
15917                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15918
15919            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15920                    user, allUsers, installerPackageName, res, installReason);
15921        } else {
15922            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15923                    user, allUsers, installerPackageName, res, installReason);
15924        }
15925    }
15926
15927    public List<String> getPreviousCodePaths(String packageName) {
15928        final PackageSetting ps = mSettings.mPackages.get(packageName);
15929        final List<String> result = new ArrayList<String>();
15930        if (ps != null && ps.oldCodePaths != null) {
15931            result.addAll(ps.oldCodePaths);
15932        }
15933        return result;
15934    }
15935
15936    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15937            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15938            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15939            int installReason) {
15940        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15941                + deletedPackage);
15942
15943        String pkgName = deletedPackage.packageName;
15944        boolean deletedPkg = true;
15945        boolean addedPkg = false;
15946        boolean updatedSettings = false;
15947        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15948        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15949                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15950
15951        final long origUpdateTime = (pkg.mExtras != null)
15952                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15953
15954        // First delete the existing package while retaining the data directory
15955        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15956                res.removedInfo, true, pkg)) {
15957            // If the existing package wasn't successfully deleted
15958            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15959            deletedPkg = false;
15960        } else {
15961            // Successfully deleted the old package; proceed with replace.
15962
15963            // If deleted package lived in a container, give users a chance to
15964            // relinquish resources before killing.
15965            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15966                if (DEBUG_INSTALL) {
15967                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15968                }
15969                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15970                final ArrayList<String> pkgList = new ArrayList<String>(1);
15971                pkgList.add(deletedPackage.applicationInfo.packageName);
15972                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15973            }
15974
15975            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15976                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15977            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15978
15979            try {
15980                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15981                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15982                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15983                        installReason);
15984
15985                // Update the in-memory copy of the previous code paths.
15986                PackageSetting ps = mSettings.mPackages.get(pkgName);
15987                if (!killApp) {
15988                    if (ps.oldCodePaths == null) {
15989                        ps.oldCodePaths = new ArraySet<>();
15990                    }
15991                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15992                    if (deletedPackage.splitCodePaths != null) {
15993                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15994                    }
15995                } else {
15996                    ps.oldCodePaths = null;
15997                }
15998                if (ps.childPackageNames != null) {
15999                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16000                        final String childPkgName = ps.childPackageNames.get(i);
16001                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16002                        childPs.oldCodePaths = ps.oldCodePaths;
16003                    }
16004                }
16005                prepareAppDataAfterInstallLIF(newPackage);
16006                addedPkg = true;
16007            } catch (PackageManagerException e) {
16008                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16009            }
16010        }
16011
16012        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16013            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16014
16015            // Revert all internal state mutations and added folders for the failed install
16016            if (addedPkg) {
16017                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16018                        res.removedInfo, true, null);
16019            }
16020
16021            // Restore the old package
16022            if (deletedPkg) {
16023                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16024                File restoreFile = new File(deletedPackage.codePath);
16025                // Parse old package
16026                boolean oldExternal = isExternal(deletedPackage);
16027                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16028                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16029                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16030                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16031                try {
16032                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16033                            null);
16034                } catch (PackageManagerException e) {
16035                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16036                            + e.getMessage());
16037                    return;
16038                }
16039
16040                synchronized (mPackages) {
16041                    // Ensure the installer package name up to date
16042                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16043
16044                    // Update permissions for restored package
16045                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16046
16047                    mSettings.writeLPr();
16048                }
16049
16050                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16051            }
16052        } else {
16053            synchronized (mPackages) {
16054                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16055                if (ps != null) {
16056                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16057                    if (res.removedInfo.removedChildPackages != null) {
16058                        final int childCount = res.removedInfo.removedChildPackages.size();
16059                        // Iterate in reverse as we may modify the collection
16060                        for (int i = childCount - 1; i >= 0; i--) {
16061                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16062                            if (res.addedChildPackages.containsKey(childPackageName)) {
16063                                res.removedInfo.removedChildPackages.removeAt(i);
16064                            } else {
16065                                PackageRemovedInfo childInfo = res.removedInfo
16066                                        .removedChildPackages.valueAt(i);
16067                                childInfo.removedForAllUsers = mPackages.get(
16068                                        childInfo.removedPackage) == null;
16069                            }
16070                        }
16071                    }
16072                }
16073            }
16074        }
16075    }
16076
16077    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16078            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16079            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16080            int installReason) {
16081        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16082                + ", old=" + deletedPackage);
16083
16084        final boolean disabledSystem;
16085
16086        // Remove existing system package
16087        removePackageLI(deletedPackage, true);
16088
16089        synchronized (mPackages) {
16090            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16091        }
16092        if (!disabledSystem) {
16093            // We didn't need to disable the .apk as a current system package,
16094            // which means we are replacing another update that is already
16095            // installed.  We need to make sure to delete the older one's .apk.
16096            res.removedInfo.args = createInstallArgsForExisting(0,
16097                    deletedPackage.applicationInfo.getCodePath(),
16098                    deletedPackage.applicationInfo.getResourcePath(),
16099                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16100        } else {
16101            res.removedInfo.args = null;
16102        }
16103
16104        // Successfully disabled the old package. Now proceed with re-installation
16105        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16106                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16107        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16108
16109        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16110        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16111                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16112
16113        PackageParser.Package newPackage = null;
16114        try {
16115            // Add the package to the internal data structures
16116            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16117
16118            // Set the update and install times
16119            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16120            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16121                    System.currentTimeMillis());
16122
16123            // Update the package dynamic state if succeeded
16124            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16125                // Now that the install succeeded make sure we remove data
16126                // directories for any child package the update removed.
16127                final int deletedChildCount = (deletedPackage.childPackages != null)
16128                        ? deletedPackage.childPackages.size() : 0;
16129                final int newChildCount = (newPackage.childPackages != null)
16130                        ? newPackage.childPackages.size() : 0;
16131                for (int i = 0; i < deletedChildCount; i++) {
16132                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16133                    boolean childPackageDeleted = true;
16134                    for (int j = 0; j < newChildCount; j++) {
16135                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16136                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16137                            childPackageDeleted = false;
16138                            break;
16139                        }
16140                    }
16141                    if (childPackageDeleted) {
16142                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16143                                deletedChildPkg.packageName);
16144                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16145                            PackageRemovedInfo removedChildRes = res.removedInfo
16146                                    .removedChildPackages.get(deletedChildPkg.packageName);
16147                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16148                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16149                        }
16150                    }
16151                }
16152
16153                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16154                        installReason);
16155                prepareAppDataAfterInstallLIF(newPackage);
16156            }
16157        } catch (PackageManagerException e) {
16158            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16159            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16160        }
16161
16162        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16163            // Re installation failed. Restore old information
16164            // Remove new pkg information
16165            if (newPackage != null) {
16166                removeInstalledPackageLI(newPackage, true);
16167            }
16168            // Add back the old system package
16169            try {
16170                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16171            } catch (PackageManagerException e) {
16172                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16173            }
16174
16175            synchronized (mPackages) {
16176                if (disabledSystem) {
16177                    enableSystemPackageLPw(deletedPackage);
16178                }
16179
16180                // Ensure the installer package name up to date
16181                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16182
16183                // Update permissions for restored package
16184                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16185
16186                mSettings.writeLPr();
16187            }
16188
16189            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16190                    + " after failed upgrade");
16191        }
16192    }
16193
16194    /**
16195     * Checks whether the parent or any of the child packages have a change shared
16196     * user. For a package to be a valid update the shred users of the parent and
16197     * the children should match. We may later support changing child shared users.
16198     * @param oldPkg The updated package.
16199     * @param newPkg The update package.
16200     * @return The shared user that change between the versions.
16201     */
16202    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16203            PackageParser.Package newPkg) {
16204        // Check parent shared user
16205        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16206            return newPkg.packageName;
16207        }
16208        // Check child shared users
16209        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16210        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16211        for (int i = 0; i < newChildCount; i++) {
16212            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16213            // If this child was present, did it have the same shared user?
16214            for (int j = 0; j < oldChildCount; j++) {
16215                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16216                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16217                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16218                    return newChildPkg.packageName;
16219                }
16220            }
16221        }
16222        return null;
16223    }
16224
16225    private void removeNativeBinariesLI(PackageSetting ps) {
16226        // Remove the lib path for the parent package
16227        if (ps != null) {
16228            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16229            // Remove the lib path for the child packages
16230            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16231            for (int i = 0; i < childCount; i++) {
16232                PackageSetting childPs = null;
16233                synchronized (mPackages) {
16234                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16235                }
16236                if (childPs != null) {
16237                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16238                            .legacyNativeLibraryPathString);
16239                }
16240            }
16241        }
16242    }
16243
16244    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16245        // Enable the parent package
16246        mSettings.enableSystemPackageLPw(pkg.packageName);
16247        // Enable the child packages
16248        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16249        for (int i = 0; i < childCount; i++) {
16250            PackageParser.Package childPkg = pkg.childPackages.get(i);
16251            mSettings.enableSystemPackageLPw(childPkg.packageName);
16252        }
16253    }
16254
16255    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16256            PackageParser.Package newPkg) {
16257        // Disable the parent package (parent always replaced)
16258        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16259        // Disable the child packages
16260        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16261        for (int i = 0; i < childCount; i++) {
16262            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16263            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16264            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16265        }
16266        return disabled;
16267    }
16268
16269    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16270            String installerPackageName) {
16271        // Enable the parent package
16272        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16273        // Enable the child packages
16274        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16275        for (int i = 0; i < childCount; i++) {
16276            PackageParser.Package childPkg = pkg.childPackages.get(i);
16277            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16278        }
16279    }
16280
16281    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16282        // Collect all used permissions in the UID
16283        ArraySet<String> usedPermissions = new ArraySet<>();
16284        final int packageCount = su.packages.size();
16285        for (int i = 0; i < packageCount; i++) {
16286            PackageSetting ps = su.packages.valueAt(i);
16287            if (ps.pkg == null) {
16288                continue;
16289            }
16290            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16291            for (int j = 0; j < requestedPermCount; j++) {
16292                String permission = ps.pkg.requestedPermissions.get(j);
16293                BasePermission bp = mSettings.mPermissions.get(permission);
16294                if (bp != null) {
16295                    usedPermissions.add(permission);
16296                }
16297            }
16298        }
16299
16300        PermissionsState permissionsState = su.getPermissionsState();
16301        // Prune install permissions
16302        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16303        final int installPermCount = installPermStates.size();
16304        for (int i = installPermCount - 1; i >= 0;  i--) {
16305            PermissionState permissionState = installPermStates.get(i);
16306            if (!usedPermissions.contains(permissionState.getName())) {
16307                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16308                if (bp != null) {
16309                    permissionsState.revokeInstallPermission(bp);
16310                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16311                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16312                }
16313            }
16314        }
16315
16316        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16317
16318        // Prune runtime permissions
16319        for (int userId : allUserIds) {
16320            List<PermissionState> runtimePermStates = permissionsState
16321                    .getRuntimePermissionStates(userId);
16322            final int runtimePermCount = runtimePermStates.size();
16323            for (int i = runtimePermCount - 1; i >= 0; i--) {
16324                PermissionState permissionState = runtimePermStates.get(i);
16325                if (!usedPermissions.contains(permissionState.getName())) {
16326                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16327                    if (bp != null) {
16328                        permissionsState.revokeRuntimePermission(bp, userId);
16329                        permissionsState.updatePermissionFlags(bp, userId,
16330                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16331                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16332                                runtimePermissionChangedUserIds, userId);
16333                    }
16334                }
16335            }
16336        }
16337
16338        return runtimePermissionChangedUserIds;
16339    }
16340
16341    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16342            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16343        // Update the parent package setting
16344        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16345                res, user, installReason);
16346        // Update the child packages setting
16347        final int childCount = (newPackage.childPackages != null)
16348                ? newPackage.childPackages.size() : 0;
16349        for (int i = 0; i < childCount; i++) {
16350            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16351            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16352            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16353                    childRes.origUsers, childRes, user, installReason);
16354        }
16355    }
16356
16357    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16358            String installerPackageName, int[] allUsers, int[] installedForUsers,
16359            PackageInstalledInfo res, UserHandle user, int installReason) {
16360        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16361
16362        String pkgName = newPackage.packageName;
16363        synchronized (mPackages) {
16364            //write settings. the installStatus will be incomplete at this stage.
16365            //note that the new package setting would have already been
16366            //added to mPackages. It hasn't been persisted yet.
16367            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16368            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16369            mSettings.writeLPr();
16370            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16371        }
16372
16373        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16374        synchronized (mPackages) {
16375            updatePermissionsLPw(newPackage.packageName, newPackage,
16376                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16377                            ? UPDATE_PERMISSIONS_ALL : 0));
16378            // For system-bundled packages, we assume that installing an upgraded version
16379            // of the package implies that the user actually wants to run that new code,
16380            // so we enable the package.
16381            PackageSetting ps = mSettings.mPackages.get(pkgName);
16382            final int userId = user.getIdentifier();
16383            if (ps != null) {
16384                if (isSystemApp(newPackage)) {
16385                    if (DEBUG_INSTALL) {
16386                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16387                    }
16388                    // Enable system package for requested users
16389                    if (res.origUsers != null) {
16390                        for (int origUserId : res.origUsers) {
16391                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16392                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16393                                        origUserId, installerPackageName);
16394                            }
16395                        }
16396                    }
16397                    // Also convey the prior install/uninstall state
16398                    if (allUsers != null && installedForUsers != null) {
16399                        for (int currentUserId : allUsers) {
16400                            final boolean installed = ArrayUtils.contains(
16401                                    installedForUsers, currentUserId);
16402                            if (DEBUG_INSTALL) {
16403                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16404                            }
16405                            ps.setInstalled(installed, currentUserId);
16406                        }
16407                        // these install state changes will be persisted in the
16408                        // upcoming call to mSettings.writeLPr().
16409                    }
16410                }
16411                // It's implied that when a user requests installation, they want the app to be
16412                // installed and enabled.
16413                if (userId != UserHandle.USER_ALL) {
16414                    ps.setInstalled(true, userId);
16415                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16416                }
16417
16418                // When replacing an existing package, preserve the original install reason for all
16419                // users that had the package installed before.
16420                final Set<Integer> previousUserIds = new ArraySet<>();
16421                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16422                    final int installReasonCount = res.removedInfo.installReasons.size();
16423                    for (int i = 0; i < installReasonCount; i++) {
16424                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16425                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16426                        ps.setInstallReason(previousInstallReason, previousUserId);
16427                        previousUserIds.add(previousUserId);
16428                    }
16429                }
16430
16431                // Set install reason for users that are having the package newly installed.
16432                if (userId == UserHandle.USER_ALL) {
16433                    for (int currentUserId : sUserManager.getUserIds()) {
16434                        if (!previousUserIds.contains(currentUserId)) {
16435                            ps.setInstallReason(installReason, currentUserId);
16436                        }
16437                    }
16438                } else if (!previousUserIds.contains(userId)) {
16439                    ps.setInstallReason(installReason, userId);
16440                }
16441            }
16442            res.name = pkgName;
16443            res.uid = newPackage.applicationInfo.uid;
16444            res.pkg = newPackage;
16445            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16446            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16447            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16448            //to update install status
16449            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16450            mSettings.writeLPr();
16451            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16452        }
16453
16454        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16455    }
16456
16457    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16458        try {
16459            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16460            installPackageLI(args, res);
16461        } finally {
16462            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16463        }
16464    }
16465
16466    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16467        final int installFlags = args.installFlags;
16468        final String installerPackageName = args.installerPackageName;
16469        final String volumeUuid = args.volumeUuid;
16470        final File tmpPackageFile = new File(args.getCodePath());
16471        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16472        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16473                || (args.volumeUuid != null));
16474        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16475        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16476        boolean replace = false;
16477        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16478        if (args.move != null) {
16479            // moving a complete application; perform an initial scan on the new install location
16480            scanFlags |= SCAN_INITIAL;
16481        }
16482        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16483            scanFlags |= SCAN_DONT_KILL_APP;
16484        }
16485
16486        // Result object to be returned
16487        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16488
16489        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16490
16491        // Sanity check
16492        if (ephemeral && (forwardLocked || onExternal)) {
16493            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16494                    + " external=" + onExternal);
16495            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16496            return;
16497        }
16498
16499        // Retrieve PackageSettings and parse package
16500        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16501                | PackageParser.PARSE_ENFORCE_CODE
16502                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16503                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16504                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16505                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16506        PackageParser pp = new PackageParser();
16507        pp.setSeparateProcesses(mSeparateProcesses);
16508        pp.setDisplayMetrics(mMetrics);
16509
16510        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16511        final PackageParser.Package pkg;
16512        try {
16513            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16514        } catch (PackageParserException e) {
16515            res.setError("Failed parse during installPackageLI", e);
16516            return;
16517        } finally {
16518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16519        }
16520
16521//        // Ephemeral apps must have target SDK >= O.
16522//        // TODO: Update conditional and error message when O gets locked down
16523//        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16524//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16525//                    "Ephemeral apps must have target SDK version of at least O");
16526//            return;
16527//        }
16528
16529        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16530            // Static shared libraries have synthetic package names
16531            renameStaticSharedLibraryPackage(pkg);
16532
16533            // No static shared libs on external storage
16534            if (onExternal) {
16535                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16536                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16537                        "Packages declaring static-shared libs cannot be updated");
16538                return;
16539            }
16540        }
16541
16542        // If we are installing a clustered package add results for the children
16543        if (pkg.childPackages != null) {
16544            synchronized (mPackages) {
16545                final int childCount = pkg.childPackages.size();
16546                for (int i = 0; i < childCount; i++) {
16547                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16548                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16549                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16550                    childRes.pkg = childPkg;
16551                    childRes.name = childPkg.packageName;
16552                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16553                    if (childPs != null) {
16554                        childRes.origUsers = childPs.queryInstalledUsers(
16555                                sUserManager.getUserIds(), true);
16556                    }
16557                    if ((mPackages.containsKey(childPkg.packageName))) {
16558                        childRes.removedInfo = new PackageRemovedInfo();
16559                        childRes.removedInfo.removedPackage = childPkg.packageName;
16560                    }
16561                    if (res.addedChildPackages == null) {
16562                        res.addedChildPackages = new ArrayMap<>();
16563                    }
16564                    res.addedChildPackages.put(childPkg.packageName, childRes);
16565                }
16566            }
16567        }
16568
16569        // If package doesn't declare API override, mark that we have an install
16570        // time CPU ABI override.
16571        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16572            pkg.cpuAbiOverride = args.abiOverride;
16573        }
16574
16575        String pkgName = res.name = pkg.packageName;
16576        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16577            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16578                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16579                return;
16580            }
16581        }
16582
16583        try {
16584            // either use what we've been given or parse directly from the APK
16585            if (args.certificates != null) {
16586                try {
16587                    PackageParser.populateCertificates(pkg, args.certificates);
16588                } catch (PackageParserException e) {
16589                    // there was something wrong with the certificates we were given;
16590                    // try to pull them from the APK
16591                    PackageParser.collectCertificates(pkg, parseFlags);
16592                }
16593            } else {
16594                PackageParser.collectCertificates(pkg, parseFlags);
16595            }
16596        } catch (PackageParserException e) {
16597            res.setError("Failed collect during installPackageLI", e);
16598            return;
16599        }
16600
16601        // Get rid of all references to package scan path via parser.
16602        pp = null;
16603        String oldCodePath = null;
16604        boolean systemApp = false;
16605        synchronized (mPackages) {
16606            // Check if installing already existing package
16607            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16608                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16609                if (pkg.mOriginalPackages != null
16610                        && pkg.mOriginalPackages.contains(oldName)
16611                        && mPackages.containsKey(oldName)) {
16612                    // This package is derived from an original package,
16613                    // and this device has been updating from that original
16614                    // name.  We must continue using the original name, so
16615                    // rename the new package here.
16616                    pkg.setPackageName(oldName);
16617                    pkgName = pkg.packageName;
16618                    replace = true;
16619                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16620                            + oldName + " pkgName=" + pkgName);
16621                } else if (mPackages.containsKey(pkgName)) {
16622                    // This package, under its official name, already exists
16623                    // on the device; we should replace it.
16624                    replace = true;
16625                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16626                }
16627
16628                // Child packages are installed through the parent package
16629                if (pkg.parentPackage != null) {
16630                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16631                            "Package " + pkg.packageName + " is child of package "
16632                                    + pkg.parentPackage.parentPackage + ". Child packages "
16633                                    + "can be updated only through the parent package.");
16634                    return;
16635                }
16636
16637                if (replace) {
16638                    // Prevent apps opting out from runtime permissions
16639                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16640                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16641                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16642                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16643                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16644                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16645                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16646                                        + " doesn't support runtime permissions but the old"
16647                                        + " target SDK " + oldTargetSdk + " does.");
16648                        return;
16649                    }
16650
16651                    // Prevent installing of child packages
16652                    if (oldPackage.parentPackage != null) {
16653                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16654                                "Package " + pkg.packageName + " is child of package "
16655                                        + oldPackage.parentPackage + ". Child packages "
16656                                        + "can be updated only through the parent package.");
16657                        return;
16658                    }
16659                }
16660            }
16661
16662            PackageSetting ps = mSettings.mPackages.get(pkgName);
16663            if (ps != null) {
16664                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16665
16666                // Static shared libs have same package with different versions where
16667                // we internally use a synthetic package name to allow multiple versions
16668                // of the same package, therefore we need to compare signatures against
16669                // the package setting for the latest library version.
16670                PackageSetting signatureCheckPs = ps;
16671                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16672                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16673                    if (libraryEntry != null) {
16674                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16675                    }
16676                }
16677
16678                // Quick sanity check that we're signed correctly if updating;
16679                // we'll check this again later when scanning, but we want to
16680                // bail early here before tripping over redefined permissions.
16681                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16682                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16683                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16684                                + pkg.packageName + " upgrade keys do not match the "
16685                                + "previously installed version");
16686                        return;
16687                    }
16688                } else {
16689                    try {
16690                        verifySignaturesLP(signatureCheckPs, pkg);
16691                    } catch (PackageManagerException e) {
16692                        res.setError(e.error, e.getMessage());
16693                        return;
16694                    }
16695                }
16696
16697                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16698                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16699                    systemApp = (ps.pkg.applicationInfo.flags &
16700                            ApplicationInfo.FLAG_SYSTEM) != 0;
16701                }
16702                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16703            }
16704
16705            // Check whether the newly-scanned package wants to define an already-defined perm
16706            int N = pkg.permissions.size();
16707            for (int i = N-1; i >= 0; i--) {
16708                PackageParser.Permission perm = pkg.permissions.get(i);
16709                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16710                if (bp != null) {
16711                    // If the defining package is signed with our cert, it's okay.  This
16712                    // also includes the "updating the same package" case, of course.
16713                    // "updating same package" could also involve key-rotation.
16714                    final boolean sigsOk;
16715                    if (bp.sourcePackage.equals(pkg.packageName)
16716                            && (bp.packageSetting instanceof PackageSetting)
16717                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16718                                    scanFlags))) {
16719                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16720                    } else {
16721                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16722                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16723                    }
16724                    if (!sigsOk) {
16725                        // If the owning package is the system itself, we log but allow
16726                        // install to proceed; we fail the install on all other permission
16727                        // redefinitions.
16728                        if (!bp.sourcePackage.equals("android")) {
16729                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16730                                    + pkg.packageName + " attempting to redeclare permission "
16731                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16732                            res.origPermission = perm.info.name;
16733                            res.origPackage = bp.sourcePackage;
16734                            return;
16735                        } else {
16736                            Slog.w(TAG, "Package " + pkg.packageName
16737                                    + " attempting to redeclare system permission "
16738                                    + perm.info.name + "; ignoring new declaration");
16739                            pkg.permissions.remove(i);
16740                        }
16741                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16742                        // Prevent apps to change protection level to dangerous from any other
16743                        // type as this would allow a privilege escalation where an app adds a
16744                        // normal/signature permission in other app's group and later redefines
16745                        // it as dangerous leading to the group auto-grant.
16746                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16747                                == PermissionInfo.PROTECTION_DANGEROUS) {
16748                            if (bp != null && !bp.isRuntime()) {
16749                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16750                                        + "non-runtime permission " + perm.info.name
16751                                        + " to runtime; keeping old protection level");
16752                                perm.info.protectionLevel = bp.protectionLevel;
16753                            }
16754                        }
16755                    }
16756                }
16757            }
16758        }
16759
16760        if (systemApp) {
16761            if (onExternal) {
16762                // Abort update; system app can't be replaced with app on sdcard
16763                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16764                        "Cannot install updates to system apps on sdcard");
16765                return;
16766            } else if (ephemeral) {
16767                // Abort update; system app can't be replaced with an ephemeral app
16768                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16769                        "Cannot update a system app with an ephemeral app");
16770                return;
16771            }
16772        }
16773
16774        if (args.move != null) {
16775            // We did an in-place move, so dex is ready to roll
16776            scanFlags |= SCAN_NO_DEX;
16777            scanFlags |= SCAN_MOVE;
16778
16779            synchronized (mPackages) {
16780                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16781                if (ps == null) {
16782                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16783                            "Missing settings for moved package " + pkgName);
16784                }
16785
16786                // We moved the entire application as-is, so bring over the
16787                // previously derived ABI information.
16788                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16789                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16790            }
16791
16792        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16793            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16794            scanFlags |= SCAN_NO_DEX;
16795
16796            try {
16797                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16798                    args.abiOverride : pkg.cpuAbiOverride);
16799                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16800                        true /*extractLibs*/, mAppLib32InstallDir);
16801            } catch (PackageManagerException pme) {
16802                Slog.e(TAG, "Error deriving application ABI", pme);
16803                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16804                return;
16805            }
16806
16807            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16808            // Do not run PackageDexOptimizer through the local performDexOpt
16809            // method because `pkg` may not be in `mPackages` yet.
16810            //
16811            // Also, don't fail application installs if the dexopt step fails.
16812            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16813                    null /* instructionSets */, false /* checkProfiles */,
16814                    getCompilerFilterForReason(REASON_INSTALL),
16815                    getOrCreateCompilerPackageStats(pkg));
16816            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16817
16818            // Notify BackgroundDexOptJobService that the package has been changed.
16819            // If this is an update of a package which used to fail to compile,
16820            // BDOS will remove it from its blacklist.
16821            // TODO: Layering violation
16822            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16823        }
16824
16825        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16826            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16827            return;
16828        }
16829
16830        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16831
16832        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16833                "installPackageLI")) {
16834            if (replace) {
16835                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16836                    // Static libs have a synthetic package name containing the version
16837                    // and cannot be updated as an update would get a new package name,
16838                    // unless this is the exact same version code which is useful for
16839                    // development.
16840                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16841                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16842                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16843                                + "static-shared libs cannot be updated");
16844                        return;
16845                    }
16846                }
16847                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16848                        installerPackageName, res, args.installReason);
16849            } else {
16850                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16851                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16852            }
16853        }
16854        synchronized (mPackages) {
16855            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16856            if (ps != null) {
16857                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16858            }
16859
16860            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16861            for (int i = 0; i < childCount; i++) {
16862                PackageParser.Package childPkg = pkg.childPackages.get(i);
16863                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16864                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16865                if (childPs != null) {
16866                    childRes.newUsers = childPs.queryInstalledUsers(
16867                            sUserManager.getUserIds(), true);
16868                }
16869            }
16870        }
16871    }
16872
16873    private void startIntentFilterVerifications(int userId, boolean replacing,
16874            PackageParser.Package pkg) {
16875        if (mIntentFilterVerifierComponent == null) {
16876            Slog.w(TAG, "No IntentFilter verification will not be done as "
16877                    + "there is no IntentFilterVerifier available!");
16878            return;
16879        }
16880
16881        final int verifierUid = getPackageUid(
16882                mIntentFilterVerifierComponent.getPackageName(),
16883                MATCH_DEBUG_TRIAGED_MISSING,
16884                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16885
16886        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16887        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16888        mHandler.sendMessage(msg);
16889
16890        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16891        for (int i = 0; i < childCount; i++) {
16892            PackageParser.Package childPkg = pkg.childPackages.get(i);
16893            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16894            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16895            mHandler.sendMessage(msg);
16896        }
16897    }
16898
16899    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16900            PackageParser.Package pkg) {
16901        int size = pkg.activities.size();
16902        if (size == 0) {
16903            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16904                    "No activity, so no need to verify any IntentFilter!");
16905            return;
16906        }
16907
16908        final boolean hasDomainURLs = hasDomainURLs(pkg);
16909        if (!hasDomainURLs) {
16910            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16911                    "No domain URLs, so no need to verify any IntentFilter!");
16912            return;
16913        }
16914
16915        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16916                + " if any IntentFilter from the " + size
16917                + " Activities needs verification ...");
16918
16919        int count = 0;
16920        final String packageName = pkg.packageName;
16921
16922        synchronized (mPackages) {
16923            // If this is a new install and we see that we've already run verification for this
16924            // package, we have nothing to do: it means the state was restored from backup.
16925            if (!replacing) {
16926                IntentFilterVerificationInfo ivi =
16927                        mSettings.getIntentFilterVerificationLPr(packageName);
16928                if (ivi != null) {
16929                    if (DEBUG_DOMAIN_VERIFICATION) {
16930                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16931                                + ivi.getStatusString());
16932                    }
16933                    return;
16934                }
16935            }
16936
16937            // If any filters need to be verified, then all need to be.
16938            boolean needToVerify = false;
16939            for (PackageParser.Activity a : pkg.activities) {
16940                for (ActivityIntentInfo filter : a.intents) {
16941                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16942                        if (DEBUG_DOMAIN_VERIFICATION) {
16943                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16944                        }
16945                        needToVerify = true;
16946                        break;
16947                    }
16948                }
16949            }
16950
16951            if (needToVerify) {
16952                final int verificationId = mIntentFilterVerificationToken++;
16953                for (PackageParser.Activity a : pkg.activities) {
16954                    for (ActivityIntentInfo filter : a.intents) {
16955                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16956                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16957                                    "Verification needed for IntentFilter:" + filter.toString());
16958                            mIntentFilterVerifier.addOneIntentFilterVerification(
16959                                    verifierUid, userId, verificationId, filter, packageName);
16960                            count++;
16961                        }
16962                    }
16963                }
16964            }
16965        }
16966
16967        if (count > 0) {
16968            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16969                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16970                    +  " for userId:" + userId);
16971            mIntentFilterVerifier.startVerifications(userId);
16972        } else {
16973            if (DEBUG_DOMAIN_VERIFICATION) {
16974                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16975            }
16976        }
16977    }
16978
16979    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16980        final ComponentName cn  = filter.activity.getComponentName();
16981        final String packageName = cn.getPackageName();
16982
16983        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16984                packageName);
16985        if (ivi == null) {
16986            return true;
16987        }
16988        int status = ivi.getStatus();
16989        switch (status) {
16990            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16991            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16992                return true;
16993
16994            default:
16995                // Nothing to do
16996                return false;
16997        }
16998    }
16999
17000    private static boolean isMultiArch(ApplicationInfo info) {
17001        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17002    }
17003
17004    private static boolean isExternal(PackageParser.Package pkg) {
17005        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17006    }
17007
17008    private static boolean isExternal(PackageSetting ps) {
17009        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17010    }
17011
17012    private static boolean isEphemeral(PackageParser.Package pkg) {
17013        return pkg.applicationInfo.isInstantApp();
17014    }
17015
17016    private static boolean isEphemeral(PackageSetting ps) {
17017        return ps.pkg != null && isEphemeral(ps.pkg);
17018    }
17019
17020    private static boolean isSystemApp(PackageParser.Package pkg) {
17021        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17022    }
17023
17024    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17025        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17026    }
17027
17028    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17029        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17030    }
17031
17032    private static boolean isSystemApp(PackageSetting ps) {
17033        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17034    }
17035
17036    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17037        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17038    }
17039
17040    private int packageFlagsToInstallFlags(PackageSetting ps) {
17041        int installFlags = 0;
17042        if (isEphemeral(ps)) {
17043            installFlags |= PackageManager.INSTALL_EPHEMERAL;
17044        }
17045        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17046            // This existing package was an external ASEC install when we have
17047            // the external flag without a UUID
17048            installFlags |= PackageManager.INSTALL_EXTERNAL;
17049        }
17050        if (ps.isForwardLocked()) {
17051            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17052        }
17053        return installFlags;
17054    }
17055
17056    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17057        if (isExternal(pkg)) {
17058            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17059                return StorageManager.UUID_PRIMARY_PHYSICAL;
17060            } else {
17061                return pkg.volumeUuid;
17062            }
17063        } else {
17064            return StorageManager.UUID_PRIVATE_INTERNAL;
17065        }
17066    }
17067
17068    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17069        if (isExternal(pkg)) {
17070            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17071                return mSettings.getExternalVersion();
17072            } else {
17073                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17074            }
17075        } else {
17076            return mSettings.getInternalVersion();
17077        }
17078    }
17079
17080    private void deleteTempPackageFiles() {
17081        final FilenameFilter filter = new FilenameFilter() {
17082            public boolean accept(File dir, String name) {
17083                return name.startsWith("vmdl") && name.endsWith(".tmp");
17084            }
17085        };
17086        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17087            file.delete();
17088        }
17089    }
17090
17091    @Override
17092    public void deletePackageAsUser(String packageName, int versionCode,
17093            IPackageDeleteObserver observer, int userId, int flags) {
17094        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17095                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17096    }
17097
17098    @Override
17099    public void deletePackageVersioned(VersionedPackage versionedPackage,
17100            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17101        mContext.enforceCallingOrSelfPermission(
17102                android.Manifest.permission.DELETE_PACKAGES, null);
17103        Preconditions.checkNotNull(versionedPackage);
17104        Preconditions.checkNotNull(observer);
17105        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17106                PackageManager.VERSION_CODE_HIGHEST,
17107                Integer.MAX_VALUE, "versionCode must be >= -1");
17108
17109        final String packageName = versionedPackage.getPackageName();
17110        // TODO: We will change version code to long, so in the new API it is long
17111        final int versionCode = (int) versionedPackage.getVersionCode();
17112        final String internalPackageName;
17113        synchronized (mPackages) {
17114            // Normalize package name to handle renamed packages and static libs
17115            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17116                    // TODO: We will change version code to long, so in the new API it is long
17117                    (int) versionedPackage.getVersionCode());
17118        }
17119
17120        final int uid = Binder.getCallingUid();
17121        if (!isOrphaned(internalPackageName)
17122                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17123            try {
17124                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17125                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17126                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17127                observer.onUserActionRequired(intent);
17128            } catch (RemoteException re) {
17129            }
17130            return;
17131        }
17132        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17133        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17134        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17135            mContext.enforceCallingOrSelfPermission(
17136                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17137                    "deletePackage for user " + userId);
17138        }
17139
17140        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17141            try {
17142                observer.onPackageDeleted(packageName,
17143                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17144            } catch (RemoteException re) {
17145            }
17146            return;
17147        }
17148
17149        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17150            try {
17151                observer.onPackageDeleted(packageName,
17152                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17153            } catch (RemoteException re) {
17154            }
17155            return;
17156        }
17157
17158        if (DEBUG_REMOVE) {
17159            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17160                    + " deleteAllUsers: " + deleteAllUsers + " version="
17161                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17162                    ? "VERSION_CODE_HIGHEST" : versionCode));
17163        }
17164        // Queue up an async operation since the package deletion may take a little while.
17165        mHandler.post(new Runnable() {
17166            public void run() {
17167                mHandler.removeCallbacks(this);
17168                int returnCode;
17169                if (!deleteAllUsers) {
17170                    returnCode = deletePackageX(internalPackageName, versionCode,
17171                            userId, deleteFlags);
17172                } else {
17173                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17174                            internalPackageName, users);
17175                    // If nobody is blocking uninstall, proceed with delete for all users
17176                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17177                        returnCode = deletePackageX(internalPackageName, versionCode,
17178                                userId, deleteFlags);
17179                    } else {
17180                        // Otherwise uninstall individually for users with blockUninstalls=false
17181                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17182                        for (int userId : users) {
17183                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17184                                returnCode = deletePackageX(internalPackageName, versionCode,
17185                                        userId, userFlags);
17186                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17187                                    Slog.w(TAG, "Package delete failed for user " + userId
17188                                            + ", returnCode " + returnCode);
17189                                }
17190                            }
17191                        }
17192                        // The app has only been marked uninstalled for certain users.
17193                        // We still need to report that delete was blocked
17194                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17195                    }
17196                }
17197                try {
17198                    observer.onPackageDeleted(packageName, returnCode, null);
17199                } catch (RemoteException e) {
17200                    Log.i(TAG, "Observer no longer exists.");
17201                } //end catch
17202            } //end run
17203        });
17204    }
17205
17206    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17207        if (pkg.staticSharedLibName != null) {
17208            return pkg.manifestPackageName;
17209        }
17210        return pkg.packageName;
17211    }
17212
17213    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17214        // Handle renamed packages
17215        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17216        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17217
17218        // Is this a static library?
17219        SparseArray<SharedLibraryEntry> versionedLib =
17220                mStaticLibsByDeclaringPackage.get(packageName);
17221        if (versionedLib == null || versionedLib.size() <= 0) {
17222            return packageName;
17223        }
17224
17225        // Figure out which lib versions the caller can see
17226        SparseIntArray versionsCallerCanSee = null;
17227        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17228        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17229                && callingAppId != Process.ROOT_UID) {
17230            versionsCallerCanSee = new SparseIntArray();
17231            String libName = versionedLib.valueAt(0).info.getName();
17232            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17233            if (uidPackages != null) {
17234                for (String uidPackage : uidPackages) {
17235                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17236                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17237                    if (libIdx >= 0) {
17238                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17239                        versionsCallerCanSee.append(libVersion, libVersion);
17240                    }
17241                }
17242            }
17243        }
17244
17245        // Caller can see nothing - done
17246        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17247            return packageName;
17248        }
17249
17250        // Find the version the caller can see and the app version code
17251        SharedLibraryEntry highestVersion = null;
17252        final int versionCount = versionedLib.size();
17253        for (int i = 0; i < versionCount; i++) {
17254            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17255            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17256                    libEntry.info.getVersion()) < 0) {
17257                continue;
17258            }
17259            // TODO: We will change version code to long, so in the new API it is long
17260            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17261            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17262                if (libVersionCode == versionCode) {
17263                    return libEntry.apk;
17264                }
17265            } else if (highestVersion == null) {
17266                highestVersion = libEntry;
17267            } else if (libVersionCode  > highestVersion.info
17268                    .getDeclaringPackage().getVersionCode()) {
17269                highestVersion = libEntry;
17270            }
17271        }
17272
17273        if (highestVersion != null) {
17274            return highestVersion.apk;
17275        }
17276
17277        return packageName;
17278    }
17279
17280    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17281        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17282              || callingUid == Process.SYSTEM_UID) {
17283            return true;
17284        }
17285        final int callingUserId = UserHandle.getUserId(callingUid);
17286        // If the caller installed the pkgName, then allow it to silently uninstall.
17287        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17288            return true;
17289        }
17290
17291        // Allow package verifier to silently uninstall.
17292        if (mRequiredVerifierPackage != null &&
17293                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17294            return true;
17295        }
17296
17297        // Allow package uninstaller to silently uninstall.
17298        if (mRequiredUninstallerPackage != null &&
17299                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17300            return true;
17301        }
17302
17303        // Allow storage manager to silently uninstall.
17304        if (mStorageManagerPackage != null &&
17305                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17306            return true;
17307        }
17308        return false;
17309    }
17310
17311    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17312        int[] result = EMPTY_INT_ARRAY;
17313        for (int userId : userIds) {
17314            if (getBlockUninstallForUser(packageName, userId)) {
17315                result = ArrayUtils.appendInt(result, userId);
17316            }
17317        }
17318        return result;
17319    }
17320
17321    @Override
17322    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17323        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17324    }
17325
17326    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17327        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17328                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17329        try {
17330            if (dpm != null) {
17331                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17332                        /* callingUserOnly =*/ false);
17333                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17334                        : deviceOwnerComponentName.getPackageName();
17335                // Does the package contains the device owner?
17336                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17337                // this check is probably not needed, since DO should be registered as a device
17338                // admin on some user too. (Original bug for this: b/17657954)
17339                if (packageName.equals(deviceOwnerPackageName)) {
17340                    return true;
17341                }
17342                // Does it contain a device admin for any user?
17343                int[] users;
17344                if (userId == UserHandle.USER_ALL) {
17345                    users = sUserManager.getUserIds();
17346                } else {
17347                    users = new int[]{userId};
17348                }
17349                for (int i = 0; i < users.length; ++i) {
17350                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17351                        return true;
17352                    }
17353                }
17354            }
17355        } catch (RemoteException e) {
17356        }
17357        return false;
17358    }
17359
17360    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17361        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17362    }
17363
17364    /**
17365     *  This method is an internal method that could be get invoked either
17366     *  to delete an installed package or to clean up a failed installation.
17367     *  After deleting an installed package, a broadcast is sent to notify any
17368     *  listeners that the package has been removed. For cleaning up a failed
17369     *  installation, the broadcast is not necessary since the package's
17370     *  installation wouldn't have sent the initial broadcast either
17371     *  The key steps in deleting a package are
17372     *  deleting the package information in internal structures like mPackages,
17373     *  deleting the packages base directories through installd
17374     *  updating mSettings to reflect current status
17375     *  persisting settings for later use
17376     *  sending a broadcast if necessary
17377     */
17378    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17379        final PackageRemovedInfo info = new PackageRemovedInfo();
17380        final boolean res;
17381
17382        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17383                ? UserHandle.USER_ALL : userId;
17384
17385        if (isPackageDeviceAdmin(packageName, removeUser)) {
17386            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17387            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17388        }
17389
17390        PackageSetting uninstalledPs = null;
17391
17392        // for the uninstall-updates case and restricted profiles, remember the per-
17393        // user handle installed state
17394        int[] allUsers;
17395        synchronized (mPackages) {
17396            uninstalledPs = mSettings.mPackages.get(packageName);
17397            if (uninstalledPs == null) {
17398                Slog.w(TAG, "Not removing non-existent package " + packageName);
17399                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17400            }
17401
17402            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17403                    && uninstalledPs.versionCode != versionCode) {
17404                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17405                        + uninstalledPs.versionCode + " != " + versionCode);
17406                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17407            }
17408
17409            // Static shared libs can be declared by any package, so let us not
17410            // allow removing a package if it provides a lib others depend on.
17411            PackageParser.Package pkg = mPackages.get(packageName);
17412            if (pkg != null && pkg.staticSharedLibName != null) {
17413                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17414                        pkg.staticSharedLibVersion);
17415                if (libEntry != null) {
17416                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17417                            libEntry.info, 0, userId);
17418                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17419                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17420                                + " hosting lib " + libEntry.info.getName() + " version "
17421                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17422                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17423                    }
17424                }
17425            }
17426
17427            allUsers = sUserManager.getUserIds();
17428            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17429        }
17430
17431        final int freezeUser;
17432        if (isUpdatedSystemApp(uninstalledPs)
17433                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17434            // We're downgrading a system app, which will apply to all users, so
17435            // freeze them all during the downgrade
17436            freezeUser = UserHandle.USER_ALL;
17437        } else {
17438            freezeUser = removeUser;
17439        }
17440
17441        synchronized (mInstallLock) {
17442            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17443            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17444                    deleteFlags, "deletePackageX")) {
17445                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17446                        deleteFlags | REMOVE_CHATTY, info, true, null);
17447            }
17448            synchronized (mPackages) {
17449                if (res) {
17450                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17451                            info.removedUsers);
17452                }
17453            }
17454        }
17455
17456        if (res) {
17457            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17458            info.sendPackageRemovedBroadcasts(killApp);
17459            info.sendSystemPackageUpdatedBroadcasts();
17460            info.sendSystemPackageAppearedBroadcasts();
17461        }
17462        // Force a gc here.
17463        Runtime.getRuntime().gc();
17464        // Delete the resources here after sending the broadcast to let
17465        // other processes clean up before deleting resources.
17466        if (info.args != null) {
17467            synchronized (mInstallLock) {
17468                info.args.doPostDeleteLI(true);
17469            }
17470        }
17471
17472        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17473    }
17474
17475    class PackageRemovedInfo {
17476        String removedPackage;
17477        int uid = -1;
17478        int removedAppId = -1;
17479        int[] origUsers;
17480        int[] removedUsers = null;
17481        SparseArray<Integer> installReasons;
17482        boolean isRemovedPackageSystemUpdate = false;
17483        boolean isUpdate;
17484        boolean dataRemoved;
17485        boolean removedForAllUsers;
17486        boolean isStaticSharedLib;
17487        // Clean up resources deleted packages.
17488        InstallArgs args = null;
17489        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17490        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17491
17492        void sendPackageRemovedBroadcasts(boolean killApp) {
17493            sendPackageRemovedBroadcastInternal(killApp);
17494            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17495            for (int i = 0; i < childCount; i++) {
17496                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17497                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17498            }
17499        }
17500
17501        void sendSystemPackageUpdatedBroadcasts() {
17502            if (isRemovedPackageSystemUpdate) {
17503                sendSystemPackageUpdatedBroadcastsInternal();
17504                final int childCount = (removedChildPackages != null)
17505                        ? removedChildPackages.size() : 0;
17506                for (int i = 0; i < childCount; i++) {
17507                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17508                    if (childInfo.isRemovedPackageSystemUpdate) {
17509                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17510                    }
17511                }
17512            }
17513        }
17514
17515        void sendSystemPackageAppearedBroadcasts() {
17516            final int packageCount = (appearedChildPackages != null)
17517                    ? appearedChildPackages.size() : 0;
17518            for (int i = 0; i < packageCount; i++) {
17519                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17520                sendPackageAddedForNewUsers(installedInfo.name, true,
17521                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17522            }
17523        }
17524
17525        private void sendSystemPackageUpdatedBroadcastsInternal() {
17526            Bundle extras = new Bundle(2);
17527            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17528            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17529            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17530                    extras, 0, null, null, null);
17531            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17532                    extras, 0, null, null, null);
17533            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17534                    null, 0, removedPackage, null, null);
17535        }
17536
17537        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17538            // Don't send static shared library removal broadcasts as these
17539            // libs are visible only the the apps that depend on them an one
17540            // cannot remove the library if it has a dependency.
17541            if (isStaticSharedLib) {
17542                return;
17543            }
17544            Bundle extras = new Bundle(2);
17545            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17546            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17547            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17548            if (isUpdate || isRemovedPackageSystemUpdate) {
17549                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17550            }
17551            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17552            if (removedPackage != null) {
17553                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17554                        extras, 0, null, null, removedUsers);
17555                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17556                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17557                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17558                            null, null, removedUsers);
17559                }
17560            }
17561            if (removedAppId >= 0) {
17562                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17563                        removedUsers);
17564            }
17565        }
17566    }
17567
17568    /*
17569     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17570     * flag is not set, the data directory is removed as well.
17571     * make sure this flag is set for partially installed apps. If not its meaningless to
17572     * delete a partially installed application.
17573     */
17574    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17575            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17576        String packageName = ps.name;
17577        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17578        // Retrieve object to delete permissions for shared user later on
17579        final PackageParser.Package deletedPkg;
17580        final PackageSetting deletedPs;
17581        // reader
17582        synchronized (mPackages) {
17583            deletedPkg = mPackages.get(packageName);
17584            deletedPs = mSettings.mPackages.get(packageName);
17585            if (outInfo != null) {
17586                outInfo.removedPackage = packageName;
17587                outInfo.isStaticSharedLib = deletedPkg != null
17588                        && deletedPkg.staticSharedLibName != null;
17589                outInfo.removedUsers = deletedPs != null
17590                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17591                        : null;
17592            }
17593        }
17594
17595        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17596
17597        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17598            final PackageParser.Package resolvedPkg;
17599            if (deletedPkg != null) {
17600                resolvedPkg = deletedPkg;
17601            } else {
17602                // We don't have a parsed package when it lives on an ejected
17603                // adopted storage device, so fake something together
17604                resolvedPkg = new PackageParser.Package(ps.name);
17605                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17606            }
17607            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17608                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17609            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17610            if (outInfo != null) {
17611                outInfo.dataRemoved = true;
17612            }
17613            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17614        }
17615
17616        int removedAppId = -1;
17617
17618        // writer
17619        synchronized (mPackages) {
17620            if (deletedPs != null) {
17621                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17622                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17623                    clearDefaultBrowserIfNeeded(packageName);
17624                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17625                    removedAppId = mSettings.removePackageLPw(packageName);
17626                    if (outInfo != null) {
17627                        outInfo.removedAppId = removedAppId;
17628                    }
17629                    updatePermissionsLPw(deletedPs.name, null, 0);
17630                    if (deletedPs.sharedUser != null) {
17631                        // Remove permissions associated with package. Since runtime
17632                        // permissions are per user we have to kill the removed package
17633                        // or packages running under the shared user of the removed
17634                        // package if revoking the permissions requested only by the removed
17635                        // package is successful and this causes a change in gids.
17636                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17637                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17638                                    userId);
17639                            if (userIdToKill == UserHandle.USER_ALL
17640                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17641                                // If gids changed for this user, kill all affected packages.
17642                                mHandler.post(new Runnable() {
17643                                    @Override
17644                                    public void run() {
17645                                        // This has to happen with no lock held.
17646                                        killApplication(deletedPs.name, deletedPs.appId,
17647                                                KILL_APP_REASON_GIDS_CHANGED);
17648                                    }
17649                                });
17650                                break;
17651                            }
17652                        }
17653                    }
17654                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17655                }
17656                // make sure to preserve per-user disabled state if this removal was just
17657                // a downgrade of a system app to the factory package
17658                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17659                    if (DEBUG_REMOVE) {
17660                        Slog.d(TAG, "Propagating install state across downgrade");
17661                    }
17662                    for (int userId : allUserHandles) {
17663                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17664                        if (DEBUG_REMOVE) {
17665                            Slog.d(TAG, "    user " + userId + " => " + installed);
17666                        }
17667                        ps.setInstalled(installed, userId);
17668                    }
17669                }
17670            }
17671            // can downgrade to reader
17672            if (writeSettings) {
17673                // Save settings now
17674                mSettings.writeLPr();
17675            }
17676        }
17677        if (removedAppId != -1) {
17678            // A user ID was deleted here. Go through all users and remove it
17679            // from KeyStore.
17680            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17681        }
17682    }
17683
17684    static boolean locationIsPrivileged(File path) {
17685        try {
17686            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17687                    .getCanonicalPath();
17688            return path.getCanonicalPath().startsWith(privilegedAppDir);
17689        } catch (IOException e) {
17690            Slog.e(TAG, "Unable to access code path " + path);
17691        }
17692        return false;
17693    }
17694
17695    /*
17696     * Tries to delete system package.
17697     */
17698    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17699            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17700            boolean writeSettings) {
17701        if (deletedPs.parentPackageName != null) {
17702            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17703            return false;
17704        }
17705
17706        final boolean applyUserRestrictions
17707                = (allUserHandles != null) && (outInfo.origUsers != null);
17708        final PackageSetting disabledPs;
17709        // Confirm if the system package has been updated
17710        // An updated system app can be deleted. This will also have to restore
17711        // the system pkg from system partition
17712        // reader
17713        synchronized (mPackages) {
17714            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17715        }
17716
17717        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17718                + " disabledPs=" + disabledPs);
17719
17720        if (disabledPs == null) {
17721            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17722            return false;
17723        } else if (DEBUG_REMOVE) {
17724            Slog.d(TAG, "Deleting system pkg from data partition");
17725        }
17726
17727        if (DEBUG_REMOVE) {
17728            if (applyUserRestrictions) {
17729                Slog.d(TAG, "Remembering install states:");
17730                for (int userId : allUserHandles) {
17731                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17732                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17733                }
17734            }
17735        }
17736
17737        // Delete the updated package
17738        outInfo.isRemovedPackageSystemUpdate = true;
17739        if (outInfo.removedChildPackages != null) {
17740            final int childCount = (deletedPs.childPackageNames != null)
17741                    ? deletedPs.childPackageNames.size() : 0;
17742            for (int i = 0; i < childCount; i++) {
17743                String childPackageName = deletedPs.childPackageNames.get(i);
17744                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17745                        .contains(childPackageName)) {
17746                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17747                            childPackageName);
17748                    if (childInfo != null) {
17749                        childInfo.isRemovedPackageSystemUpdate = true;
17750                    }
17751                }
17752            }
17753        }
17754
17755        if (disabledPs.versionCode < deletedPs.versionCode) {
17756            // Delete data for downgrades
17757            flags &= ~PackageManager.DELETE_KEEP_DATA;
17758        } else {
17759            // Preserve data by setting flag
17760            flags |= PackageManager.DELETE_KEEP_DATA;
17761        }
17762
17763        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17764                outInfo, writeSettings, disabledPs.pkg);
17765        if (!ret) {
17766            return false;
17767        }
17768
17769        // writer
17770        synchronized (mPackages) {
17771            // Reinstate the old system package
17772            enableSystemPackageLPw(disabledPs.pkg);
17773            // Remove any native libraries from the upgraded package.
17774            removeNativeBinariesLI(deletedPs);
17775        }
17776
17777        // Install the system package
17778        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17779        int parseFlags = mDefParseFlags
17780                | PackageParser.PARSE_MUST_BE_APK
17781                | PackageParser.PARSE_IS_SYSTEM
17782                | PackageParser.PARSE_IS_SYSTEM_DIR;
17783        if (locationIsPrivileged(disabledPs.codePath)) {
17784            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17785        }
17786
17787        final PackageParser.Package newPkg;
17788        try {
17789            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17790                0 /* currentTime */, null);
17791        } catch (PackageManagerException e) {
17792            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17793                    + e.getMessage());
17794            return false;
17795        }
17796
17797        try {
17798            // update shared libraries for the newly re-installed system package
17799            updateSharedLibrariesLPr(newPkg, null);
17800        } catch (PackageManagerException e) {
17801            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17802        }
17803
17804        prepareAppDataAfterInstallLIF(newPkg);
17805
17806        // writer
17807        synchronized (mPackages) {
17808            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17809
17810            // Propagate the permissions state as we do not want to drop on the floor
17811            // runtime permissions. The update permissions method below will take
17812            // care of removing obsolete permissions and grant install permissions.
17813            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17814            updatePermissionsLPw(newPkg.packageName, newPkg,
17815                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17816
17817            if (applyUserRestrictions) {
17818                if (DEBUG_REMOVE) {
17819                    Slog.d(TAG, "Propagating install state across reinstall");
17820                }
17821                for (int userId : allUserHandles) {
17822                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17823                    if (DEBUG_REMOVE) {
17824                        Slog.d(TAG, "    user " + userId + " => " + installed);
17825                    }
17826                    ps.setInstalled(installed, userId);
17827
17828                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17829                }
17830                // Regardless of writeSettings we need to ensure that this restriction
17831                // state propagation is persisted
17832                mSettings.writeAllUsersPackageRestrictionsLPr();
17833            }
17834            // can downgrade to reader here
17835            if (writeSettings) {
17836                mSettings.writeLPr();
17837            }
17838        }
17839        return true;
17840    }
17841
17842    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17843            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17844            PackageRemovedInfo outInfo, boolean writeSettings,
17845            PackageParser.Package replacingPackage) {
17846        synchronized (mPackages) {
17847            if (outInfo != null) {
17848                outInfo.uid = ps.appId;
17849            }
17850
17851            if (outInfo != null && outInfo.removedChildPackages != null) {
17852                final int childCount = (ps.childPackageNames != null)
17853                        ? ps.childPackageNames.size() : 0;
17854                for (int i = 0; i < childCount; i++) {
17855                    String childPackageName = ps.childPackageNames.get(i);
17856                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17857                    if (childPs == null) {
17858                        return false;
17859                    }
17860                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17861                            childPackageName);
17862                    if (childInfo != null) {
17863                        childInfo.uid = childPs.appId;
17864                    }
17865                }
17866            }
17867        }
17868
17869        // Delete package data from internal structures and also remove data if flag is set
17870        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17871
17872        // Delete the child packages data
17873        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17874        for (int i = 0; i < childCount; i++) {
17875            PackageSetting childPs;
17876            synchronized (mPackages) {
17877                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17878            }
17879            if (childPs != null) {
17880                PackageRemovedInfo childOutInfo = (outInfo != null
17881                        && outInfo.removedChildPackages != null)
17882                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17883                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17884                        && (replacingPackage != null
17885                        && !replacingPackage.hasChildPackage(childPs.name))
17886                        ? flags & ~DELETE_KEEP_DATA : flags;
17887                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17888                        deleteFlags, writeSettings);
17889            }
17890        }
17891
17892        // Delete application code and resources only for parent packages
17893        if (ps.parentPackageName == null) {
17894            if (deleteCodeAndResources && (outInfo != null)) {
17895                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17896                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17897                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17898            }
17899        }
17900
17901        return true;
17902    }
17903
17904    @Override
17905    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17906            int userId) {
17907        mContext.enforceCallingOrSelfPermission(
17908                android.Manifest.permission.DELETE_PACKAGES, null);
17909        synchronized (mPackages) {
17910            PackageSetting ps = mSettings.mPackages.get(packageName);
17911            if (ps == null) {
17912                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17913                return false;
17914            }
17915            // Cannot block uninstall of static shared libs as they are
17916            // considered a part of the using app (emulating static linking).
17917            // Also static libs are installed always on internal storage.
17918            PackageParser.Package pkg = mPackages.get(packageName);
17919            if (pkg != null && pkg.staticSharedLibName != null) {
17920                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17921                        + " providing static shared library: " + pkg.staticSharedLibName);
17922                return false;
17923            }
17924            if (!ps.getInstalled(userId)) {
17925                // Can't block uninstall for an app that is not installed or enabled.
17926                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17927                return false;
17928            }
17929            ps.setBlockUninstall(blockUninstall, userId);
17930            mSettings.writePackageRestrictionsLPr(userId);
17931        }
17932        return true;
17933    }
17934
17935    @Override
17936    public boolean getBlockUninstallForUser(String packageName, int userId) {
17937        synchronized (mPackages) {
17938            PackageSetting ps = mSettings.mPackages.get(packageName);
17939            if (ps == null) {
17940                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17941                return false;
17942            }
17943            return ps.getBlockUninstall(userId);
17944        }
17945    }
17946
17947    @Override
17948    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17949        int callingUid = Binder.getCallingUid();
17950        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17951            throw new SecurityException(
17952                    "setRequiredForSystemUser can only be run by the system or root");
17953        }
17954        synchronized (mPackages) {
17955            PackageSetting ps = mSettings.mPackages.get(packageName);
17956            if (ps == null) {
17957                Log.w(TAG, "Package doesn't exist: " + packageName);
17958                return false;
17959            }
17960            if (systemUserApp) {
17961                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17962            } else {
17963                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17964            }
17965            mSettings.writeLPr();
17966        }
17967        return true;
17968    }
17969
17970    /*
17971     * This method handles package deletion in general
17972     */
17973    private boolean deletePackageLIF(String packageName, UserHandle user,
17974            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17975            PackageRemovedInfo outInfo, boolean writeSettings,
17976            PackageParser.Package replacingPackage) {
17977        if (packageName == null) {
17978            Slog.w(TAG, "Attempt to delete null packageName.");
17979            return false;
17980        }
17981
17982        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17983
17984        PackageSetting ps;
17985        synchronized (mPackages) {
17986            ps = mSettings.mPackages.get(packageName);
17987            if (ps == null) {
17988                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17989                return false;
17990            }
17991
17992            if (ps.parentPackageName != null && (!isSystemApp(ps)
17993                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17994                if (DEBUG_REMOVE) {
17995                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17996                            + ((user == null) ? UserHandle.USER_ALL : user));
17997                }
17998                final int removedUserId = (user != null) ? user.getIdentifier()
17999                        : UserHandle.USER_ALL;
18000                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18001                    return false;
18002                }
18003                markPackageUninstalledForUserLPw(ps, user);
18004                scheduleWritePackageRestrictionsLocked(user);
18005                return true;
18006            }
18007        }
18008
18009        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18010                && user.getIdentifier() != UserHandle.USER_ALL)) {
18011            // The caller is asking that the package only be deleted for a single
18012            // user.  To do this, we just mark its uninstalled state and delete
18013            // its data. If this is a system app, we only allow this to happen if
18014            // they have set the special DELETE_SYSTEM_APP which requests different
18015            // semantics than normal for uninstalling system apps.
18016            markPackageUninstalledForUserLPw(ps, user);
18017
18018            if (!isSystemApp(ps)) {
18019                // Do not uninstall the APK if an app should be cached
18020                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18021                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18022                    // Other user still have this package installed, so all
18023                    // we need to do is clear this user's data and save that
18024                    // it is uninstalled.
18025                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18026                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18027                        return false;
18028                    }
18029                    scheduleWritePackageRestrictionsLocked(user);
18030                    return true;
18031                } else {
18032                    // We need to set it back to 'installed' so the uninstall
18033                    // broadcasts will be sent correctly.
18034                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18035                    ps.setInstalled(true, user.getIdentifier());
18036                }
18037            } else {
18038                // This is a system app, so we assume that the
18039                // other users still have this package installed, so all
18040                // we need to do is clear this user's data and save that
18041                // it is uninstalled.
18042                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18043                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18044                    return false;
18045                }
18046                scheduleWritePackageRestrictionsLocked(user);
18047                return true;
18048            }
18049        }
18050
18051        // If we are deleting a composite package for all users, keep track
18052        // of result for each child.
18053        if (ps.childPackageNames != null && outInfo != null) {
18054            synchronized (mPackages) {
18055                final int childCount = ps.childPackageNames.size();
18056                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18057                for (int i = 0; i < childCount; i++) {
18058                    String childPackageName = ps.childPackageNames.get(i);
18059                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18060                    childInfo.removedPackage = childPackageName;
18061                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18062                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18063                    if (childPs != null) {
18064                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18065                    }
18066                }
18067            }
18068        }
18069
18070        boolean ret = false;
18071        if (isSystemApp(ps)) {
18072            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18073            // When an updated system application is deleted we delete the existing resources
18074            // as well and fall back to existing code in system partition
18075            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18076        } else {
18077            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18078            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18079                    outInfo, writeSettings, replacingPackage);
18080        }
18081
18082        // Take a note whether we deleted the package for all users
18083        if (outInfo != null) {
18084            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18085            if (outInfo.removedChildPackages != null) {
18086                synchronized (mPackages) {
18087                    final int childCount = outInfo.removedChildPackages.size();
18088                    for (int i = 0; i < childCount; i++) {
18089                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18090                        if (childInfo != null) {
18091                            childInfo.removedForAllUsers = mPackages.get(
18092                                    childInfo.removedPackage) == null;
18093                        }
18094                    }
18095                }
18096            }
18097            // If we uninstalled an update to a system app there may be some
18098            // child packages that appeared as they are declared in the system
18099            // app but were not declared in the update.
18100            if (isSystemApp(ps)) {
18101                synchronized (mPackages) {
18102                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18103                    final int childCount = (updatedPs.childPackageNames != null)
18104                            ? updatedPs.childPackageNames.size() : 0;
18105                    for (int i = 0; i < childCount; i++) {
18106                        String childPackageName = updatedPs.childPackageNames.get(i);
18107                        if (outInfo.removedChildPackages == null
18108                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18109                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18110                            if (childPs == null) {
18111                                continue;
18112                            }
18113                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18114                            installRes.name = childPackageName;
18115                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18116                            installRes.pkg = mPackages.get(childPackageName);
18117                            installRes.uid = childPs.pkg.applicationInfo.uid;
18118                            if (outInfo.appearedChildPackages == null) {
18119                                outInfo.appearedChildPackages = new ArrayMap<>();
18120                            }
18121                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18122                        }
18123                    }
18124                }
18125            }
18126        }
18127
18128        return ret;
18129    }
18130
18131    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18132        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18133                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18134        for (int nextUserId : userIds) {
18135            if (DEBUG_REMOVE) {
18136                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18137            }
18138            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18139                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18140                    false /*hidden*/, false /*suspended*/, null, null, null,
18141                    false /*blockUninstall*/,
18142                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18143                    PackageManager.INSTALL_REASON_UNKNOWN);
18144        }
18145    }
18146
18147    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18148            PackageRemovedInfo outInfo) {
18149        final PackageParser.Package pkg;
18150        synchronized (mPackages) {
18151            pkg = mPackages.get(ps.name);
18152        }
18153
18154        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18155                : new int[] {userId};
18156        for (int nextUserId : userIds) {
18157            if (DEBUG_REMOVE) {
18158                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18159                        + nextUserId);
18160            }
18161
18162            destroyAppDataLIF(pkg, userId,
18163                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18164            destroyAppProfilesLIF(pkg, userId);
18165            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18166            schedulePackageCleaning(ps.name, nextUserId, false);
18167            synchronized (mPackages) {
18168                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18169                    scheduleWritePackageRestrictionsLocked(nextUserId);
18170                }
18171                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18172            }
18173        }
18174
18175        if (outInfo != null) {
18176            outInfo.removedPackage = ps.name;
18177            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18178            outInfo.removedAppId = ps.appId;
18179            outInfo.removedUsers = userIds;
18180        }
18181
18182        return true;
18183    }
18184
18185    private final class ClearStorageConnection implements ServiceConnection {
18186        IMediaContainerService mContainerService;
18187
18188        @Override
18189        public void onServiceConnected(ComponentName name, IBinder service) {
18190            synchronized (this) {
18191                mContainerService = IMediaContainerService.Stub
18192                        .asInterface(Binder.allowBlocking(service));
18193                notifyAll();
18194            }
18195        }
18196
18197        @Override
18198        public void onServiceDisconnected(ComponentName name) {
18199        }
18200    }
18201
18202    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18203        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18204
18205        final boolean mounted;
18206        if (Environment.isExternalStorageEmulated()) {
18207            mounted = true;
18208        } else {
18209            final String status = Environment.getExternalStorageState();
18210
18211            mounted = status.equals(Environment.MEDIA_MOUNTED)
18212                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18213        }
18214
18215        if (!mounted) {
18216            return;
18217        }
18218
18219        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18220        int[] users;
18221        if (userId == UserHandle.USER_ALL) {
18222            users = sUserManager.getUserIds();
18223        } else {
18224            users = new int[] { userId };
18225        }
18226        final ClearStorageConnection conn = new ClearStorageConnection();
18227        if (mContext.bindServiceAsUser(
18228                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18229            try {
18230                for (int curUser : users) {
18231                    long timeout = SystemClock.uptimeMillis() + 5000;
18232                    synchronized (conn) {
18233                        long now;
18234                        while (conn.mContainerService == null &&
18235                                (now = SystemClock.uptimeMillis()) < timeout) {
18236                            try {
18237                                conn.wait(timeout - now);
18238                            } catch (InterruptedException e) {
18239                            }
18240                        }
18241                    }
18242                    if (conn.mContainerService == null) {
18243                        return;
18244                    }
18245
18246                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18247                    clearDirectory(conn.mContainerService,
18248                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18249                    if (allData) {
18250                        clearDirectory(conn.mContainerService,
18251                                userEnv.buildExternalStorageAppDataDirs(packageName));
18252                        clearDirectory(conn.mContainerService,
18253                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18254                    }
18255                }
18256            } finally {
18257                mContext.unbindService(conn);
18258            }
18259        }
18260    }
18261
18262    @Override
18263    public void clearApplicationProfileData(String packageName) {
18264        enforceSystemOrRoot("Only the system can clear all profile data");
18265
18266        final PackageParser.Package pkg;
18267        synchronized (mPackages) {
18268            pkg = mPackages.get(packageName);
18269        }
18270
18271        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18272            synchronized (mInstallLock) {
18273                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18274                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18275                        true /* removeBaseMarker */);
18276            }
18277        }
18278    }
18279
18280    @Override
18281    public void clearApplicationUserData(final String packageName,
18282            final IPackageDataObserver observer, final int userId) {
18283        mContext.enforceCallingOrSelfPermission(
18284                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18285
18286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18287                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18288
18289        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18290            throw new SecurityException("Cannot clear data for a protected package: "
18291                    + packageName);
18292        }
18293        // Queue up an async operation since the package deletion may take a little while.
18294        mHandler.post(new Runnable() {
18295            public void run() {
18296                mHandler.removeCallbacks(this);
18297                final boolean succeeded;
18298                try (PackageFreezer freezer = freezePackage(packageName,
18299                        "clearApplicationUserData")) {
18300                    synchronized (mInstallLock) {
18301                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18302                    }
18303                    clearExternalStorageDataSync(packageName, userId, true);
18304                    synchronized (mPackages) {
18305                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18306                                packageName, userId);
18307                    }
18308                }
18309                if (succeeded) {
18310                    // invoke DeviceStorageMonitor's update method to clear any notifications
18311                    DeviceStorageMonitorInternal dsm = LocalServices
18312                            .getService(DeviceStorageMonitorInternal.class);
18313                    if (dsm != null) {
18314                        dsm.checkMemory();
18315                    }
18316                }
18317                if(observer != null) {
18318                    try {
18319                        observer.onRemoveCompleted(packageName, succeeded);
18320                    } catch (RemoteException e) {
18321                        Log.i(TAG, "Observer no longer exists.");
18322                    }
18323                } //end if observer
18324            } //end run
18325        });
18326    }
18327
18328    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18329        if (packageName == null) {
18330            Slog.w(TAG, "Attempt to delete null packageName.");
18331            return false;
18332        }
18333
18334        // Try finding details about the requested package
18335        PackageParser.Package pkg;
18336        synchronized (mPackages) {
18337            pkg = mPackages.get(packageName);
18338            if (pkg == null) {
18339                final PackageSetting ps = mSettings.mPackages.get(packageName);
18340                if (ps != null) {
18341                    pkg = ps.pkg;
18342                }
18343            }
18344
18345            if (pkg == null) {
18346                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18347                return false;
18348            }
18349
18350            PackageSetting ps = (PackageSetting) pkg.mExtras;
18351            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18352        }
18353
18354        clearAppDataLIF(pkg, userId,
18355                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18356
18357        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18358        removeKeystoreDataIfNeeded(userId, appId);
18359
18360        UserManagerInternal umInternal = getUserManagerInternal();
18361        final int flags;
18362        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18363            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18364        } else if (umInternal.isUserRunning(userId)) {
18365            flags = StorageManager.FLAG_STORAGE_DE;
18366        } else {
18367            flags = 0;
18368        }
18369        prepareAppDataContentsLIF(pkg, userId, flags);
18370
18371        return true;
18372    }
18373
18374    /**
18375     * Reverts user permission state changes (permissions and flags) in
18376     * all packages for a given user.
18377     *
18378     * @param userId The device user for which to do a reset.
18379     */
18380    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18381        final int packageCount = mPackages.size();
18382        for (int i = 0; i < packageCount; i++) {
18383            PackageParser.Package pkg = mPackages.valueAt(i);
18384            PackageSetting ps = (PackageSetting) pkg.mExtras;
18385            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18386        }
18387    }
18388
18389    private void resetNetworkPolicies(int userId) {
18390        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18391    }
18392
18393    /**
18394     * Reverts user permission state changes (permissions and flags).
18395     *
18396     * @param ps The package for which to reset.
18397     * @param userId The device user for which to do a reset.
18398     */
18399    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18400            final PackageSetting ps, final int userId) {
18401        if (ps.pkg == null) {
18402            return;
18403        }
18404
18405        // These are flags that can change base on user actions.
18406        final int userSettableMask = FLAG_PERMISSION_USER_SET
18407                | FLAG_PERMISSION_USER_FIXED
18408                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18409                | FLAG_PERMISSION_REVIEW_REQUIRED;
18410
18411        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18412                | FLAG_PERMISSION_POLICY_FIXED;
18413
18414        boolean writeInstallPermissions = false;
18415        boolean writeRuntimePermissions = false;
18416
18417        final int permissionCount = ps.pkg.requestedPermissions.size();
18418        for (int i = 0; i < permissionCount; i++) {
18419            String permission = ps.pkg.requestedPermissions.get(i);
18420
18421            BasePermission bp = mSettings.mPermissions.get(permission);
18422            if (bp == null) {
18423                continue;
18424            }
18425
18426            // If shared user we just reset the state to which only this app contributed.
18427            if (ps.sharedUser != null) {
18428                boolean used = false;
18429                final int packageCount = ps.sharedUser.packages.size();
18430                for (int j = 0; j < packageCount; j++) {
18431                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18432                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18433                            && pkg.pkg.requestedPermissions.contains(permission)) {
18434                        used = true;
18435                        break;
18436                    }
18437                }
18438                if (used) {
18439                    continue;
18440                }
18441            }
18442
18443            PermissionsState permissionsState = ps.getPermissionsState();
18444
18445            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18446
18447            // Always clear the user settable flags.
18448            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18449                    bp.name) != null;
18450            // If permission review is enabled and this is a legacy app, mark the
18451            // permission as requiring a review as this is the initial state.
18452            int flags = 0;
18453            if (mPermissionReviewRequired
18454                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18455                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18456            }
18457            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18458                if (hasInstallState) {
18459                    writeInstallPermissions = true;
18460                } else {
18461                    writeRuntimePermissions = true;
18462                }
18463            }
18464
18465            // Below is only runtime permission handling.
18466            if (!bp.isRuntime()) {
18467                continue;
18468            }
18469
18470            // Never clobber system or policy.
18471            if ((oldFlags & policyOrSystemFlags) != 0) {
18472                continue;
18473            }
18474
18475            // If this permission was granted by default, make sure it is.
18476            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18477                if (permissionsState.grantRuntimePermission(bp, userId)
18478                        != PERMISSION_OPERATION_FAILURE) {
18479                    writeRuntimePermissions = true;
18480                }
18481            // If permission review is enabled the permissions for a legacy apps
18482            // are represented as constantly granted runtime ones, so don't revoke.
18483            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18484                // Otherwise, reset the permission.
18485                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18486                switch (revokeResult) {
18487                    case PERMISSION_OPERATION_SUCCESS:
18488                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18489                        writeRuntimePermissions = true;
18490                        final int appId = ps.appId;
18491                        mHandler.post(new Runnable() {
18492                            @Override
18493                            public void run() {
18494                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18495                            }
18496                        });
18497                    } break;
18498                }
18499            }
18500        }
18501
18502        // Synchronously write as we are taking permissions away.
18503        if (writeRuntimePermissions) {
18504            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18505        }
18506
18507        // Synchronously write as we are taking permissions away.
18508        if (writeInstallPermissions) {
18509            mSettings.writeLPr();
18510        }
18511    }
18512
18513    /**
18514     * Remove entries from the keystore daemon. Will only remove it if the
18515     * {@code appId} is valid.
18516     */
18517    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18518        if (appId < 0) {
18519            return;
18520        }
18521
18522        final KeyStore keyStore = KeyStore.getInstance();
18523        if (keyStore != null) {
18524            if (userId == UserHandle.USER_ALL) {
18525                for (final int individual : sUserManager.getUserIds()) {
18526                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18527                }
18528            } else {
18529                keyStore.clearUid(UserHandle.getUid(userId, appId));
18530            }
18531        } else {
18532            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18533        }
18534    }
18535
18536    @Override
18537    public void deleteApplicationCacheFiles(final String packageName,
18538            final IPackageDataObserver observer) {
18539        final int userId = UserHandle.getCallingUserId();
18540        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18541    }
18542
18543    @Override
18544    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18545            final IPackageDataObserver observer) {
18546        mContext.enforceCallingOrSelfPermission(
18547                android.Manifest.permission.DELETE_CACHE_FILES, null);
18548        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18549                /* requireFullPermission= */ true, /* checkShell= */ false,
18550                "delete application cache files");
18551
18552        final PackageParser.Package pkg;
18553        synchronized (mPackages) {
18554            pkg = mPackages.get(packageName);
18555        }
18556
18557        // Queue up an async operation since the package deletion may take a little while.
18558        mHandler.post(new Runnable() {
18559            public void run() {
18560                synchronized (mInstallLock) {
18561                    final int flags = StorageManager.FLAG_STORAGE_DE
18562                            | StorageManager.FLAG_STORAGE_CE;
18563                    // We're only clearing cache files, so we don't care if the
18564                    // app is unfrozen and still able to run
18565                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18566                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18567                }
18568                clearExternalStorageDataSync(packageName, userId, false);
18569                if (observer != null) {
18570                    try {
18571                        observer.onRemoveCompleted(packageName, true);
18572                    } catch (RemoteException e) {
18573                        Log.i(TAG, "Observer no longer exists.");
18574                    }
18575                }
18576            }
18577        });
18578    }
18579
18580    @Override
18581    public void getPackageSizeInfo(final String packageName, int userHandle,
18582            final IPackageStatsObserver observer) {
18583        mContext.enforceCallingOrSelfPermission(
18584                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18585        if (packageName == null) {
18586            throw new IllegalArgumentException("Attempt to get size of null packageName");
18587        }
18588
18589        PackageStats stats = new PackageStats(packageName, userHandle);
18590
18591        /*
18592         * Queue up an async operation since the package measurement may take a
18593         * little while.
18594         */
18595        Message msg = mHandler.obtainMessage(INIT_COPY);
18596        msg.obj = new MeasureParams(stats, observer);
18597        mHandler.sendMessage(msg);
18598    }
18599
18600    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18601        final PackageSetting ps;
18602        synchronized (mPackages) {
18603            ps = mSettings.mPackages.get(packageName);
18604            if (ps == null) {
18605                Slog.w(TAG, "Failed to find settings for " + packageName);
18606                return false;
18607            }
18608        }
18609
18610        final String[] packageNames = { packageName };
18611        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18612        final String[] codePaths = { ps.codePathString };
18613
18614        try {
18615            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18616                    ps.appId, ceDataInodes, codePaths, stats);
18617
18618            // For now, ignore code size of packages on system partition
18619            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18620                stats.codeSize = 0;
18621            }
18622
18623            // External clients expect these to be tracked separately
18624            stats.dataSize -= stats.cacheSize;
18625
18626        } catch (InstallerException e) {
18627            Slog.w(TAG, String.valueOf(e));
18628            return false;
18629        }
18630
18631        return true;
18632    }
18633
18634    private int getUidTargetSdkVersionLockedLPr(int uid) {
18635        Object obj = mSettings.getUserIdLPr(uid);
18636        if (obj instanceof SharedUserSetting) {
18637            final SharedUserSetting sus = (SharedUserSetting) obj;
18638            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18639            final Iterator<PackageSetting> it = sus.packages.iterator();
18640            while (it.hasNext()) {
18641                final PackageSetting ps = it.next();
18642                if (ps.pkg != null) {
18643                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18644                    if (v < vers) vers = v;
18645                }
18646            }
18647            return vers;
18648        } else if (obj instanceof PackageSetting) {
18649            final PackageSetting ps = (PackageSetting) obj;
18650            if (ps.pkg != null) {
18651                return ps.pkg.applicationInfo.targetSdkVersion;
18652            }
18653        }
18654        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18655    }
18656
18657    @Override
18658    public void addPreferredActivity(IntentFilter filter, int match,
18659            ComponentName[] set, ComponentName activity, int userId) {
18660        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18661                "Adding preferred");
18662    }
18663
18664    private void addPreferredActivityInternal(IntentFilter filter, int match,
18665            ComponentName[] set, ComponentName activity, boolean always, int userId,
18666            String opname) {
18667        // writer
18668        int callingUid = Binder.getCallingUid();
18669        enforceCrossUserPermission(callingUid, userId,
18670                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18671        if (filter.countActions() == 0) {
18672            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18673            return;
18674        }
18675        synchronized (mPackages) {
18676            if (mContext.checkCallingOrSelfPermission(
18677                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18678                    != PackageManager.PERMISSION_GRANTED) {
18679                if (getUidTargetSdkVersionLockedLPr(callingUid)
18680                        < Build.VERSION_CODES.FROYO) {
18681                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18682                            + callingUid);
18683                    return;
18684                }
18685                mContext.enforceCallingOrSelfPermission(
18686                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18687            }
18688
18689            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18690            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18691                    + userId + ":");
18692            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18693            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18694            scheduleWritePackageRestrictionsLocked(userId);
18695            postPreferredActivityChangedBroadcast(userId);
18696        }
18697    }
18698
18699    private void postPreferredActivityChangedBroadcast(int userId) {
18700        mHandler.post(() -> {
18701            final IActivityManager am = ActivityManager.getService();
18702            if (am == null) {
18703                return;
18704            }
18705
18706            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18707            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18708            try {
18709                am.broadcastIntent(null, intent, null, null,
18710                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18711                        null, false, false, userId);
18712            } catch (RemoteException e) {
18713            }
18714        });
18715    }
18716
18717    @Override
18718    public void replacePreferredActivity(IntentFilter filter, int match,
18719            ComponentName[] set, ComponentName activity, int userId) {
18720        if (filter.countActions() != 1) {
18721            throw new IllegalArgumentException(
18722                    "replacePreferredActivity expects filter to have only 1 action.");
18723        }
18724        if (filter.countDataAuthorities() != 0
18725                || filter.countDataPaths() != 0
18726                || filter.countDataSchemes() > 1
18727                || filter.countDataTypes() != 0) {
18728            throw new IllegalArgumentException(
18729                    "replacePreferredActivity expects filter to have no data authorities, " +
18730                    "paths, or types; and at most one scheme.");
18731        }
18732
18733        final int callingUid = Binder.getCallingUid();
18734        enforceCrossUserPermission(callingUid, userId,
18735                true /* requireFullPermission */, false /* checkShell */,
18736                "replace preferred activity");
18737        synchronized (mPackages) {
18738            if (mContext.checkCallingOrSelfPermission(
18739                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18740                    != PackageManager.PERMISSION_GRANTED) {
18741                if (getUidTargetSdkVersionLockedLPr(callingUid)
18742                        < Build.VERSION_CODES.FROYO) {
18743                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18744                            + Binder.getCallingUid());
18745                    return;
18746                }
18747                mContext.enforceCallingOrSelfPermission(
18748                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18749            }
18750
18751            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18752            if (pir != null) {
18753                // Get all of the existing entries that exactly match this filter.
18754                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18755                if (existing != null && existing.size() == 1) {
18756                    PreferredActivity cur = existing.get(0);
18757                    if (DEBUG_PREFERRED) {
18758                        Slog.i(TAG, "Checking replace of preferred:");
18759                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18760                        if (!cur.mPref.mAlways) {
18761                            Slog.i(TAG, "  -- CUR; not mAlways!");
18762                        } else {
18763                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18764                            Slog.i(TAG, "  -- CUR: mSet="
18765                                    + Arrays.toString(cur.mPref.mSetComponents));
18766                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18767                            Slog.i(TAG, "  -- NEW: mMatch="
18768                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18769                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18770                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18771                        }
18772                    }
18773                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18774                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18775                            && cur.mPref.sameSet(set)) {
18776                        // Setting the preferred activity to what it happens to be already
18777                        if (DEBUG_PREFERRED) {
18778                            Slog.i(TAG, "Replacing with same preferred activity "
18779                                    + cur.mPref.mShortComponent + " for user "
18780                                    + userId + ":");
18781                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18782                        }
18783                        return;
18784                    }
18785                }
18786
18787                if (existing != null) {
18788                    if (DEBUG_PREFERRED) {
18789                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18790                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18791                    }
18792                    for (int i = 0; i < existing.size(); i++) {
18793                        PreferredActivity pa = existing.get(i);
18794                        if (DEBUG_PREFERRED) {
18795                            Slog.i(TAG, "Removing existing preferred activity "
18796                                    + pa.mPref.mComponent + ":");
18797                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18798                        }
18799                        pir.removeFilter(pa);
18800                    }
18801                }
18802            }
18803            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18804                    "Replacing preferred");
18805        }
18806    }
18807
18808    @Override
18809    public void clearPackagePreferredActivities(String packageName) {
18810        final int uid = Binder.getCallingUid();
18811        // writer
18812        synchronized (mPackages) {
18813            PackageParser.Package pkg = mPackages.get(packageName);
18814            if (pkg == null || pkg.applicationInfo.uid != uid) {
18815                if (mContext.checkCallingOrSelfPermission(
18816                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18817                        != PackageManager.PERMISSION_GRANTED) {
18818                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18819                            < Build.VERSION_CODES.FROYO) {
18820                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18821                                + Binder.getCallingUid());
18822                        return;
18823                    }
18824                    mContext.enforceCallingOrSelfPermission(
18825                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18826                }
18827            }
18828
18829            int user = UserHandle.getCallingUserId();
18830            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18831                scheduleWritePackageRestrictionsLocked(user);
18832            }
18833        }
18834    }
18835
18836    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18837    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18838        ArrayList<PreferredActivity> removed = null;
18839        boolean changed = false;
18840        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18841            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18842            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18843            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18844                continue;
18845            }
18846            Iterator<PreferredActivity> it = pir.filterIterator();
18847            while (it.hasNext()) {
18848                PreferredActivity pa = it.next();
18849                // Mark entry for removal only if it matches the package name
18850                // and the entry is of type "always".
18851                if (packageName == null ||
18852                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18853                                && pa.mPref.mAlways)) {
18854                    if (removed == null) {
18855                        removed = new ArrayList<PreferredActivity>();
18856                    }
18857                    removed.add(pa);
18858                }
18859            }
18860            if (removed != null) {
18861                for (int j=0; j<removed.size(); j++) {
18862                    PreferredActivity pa = removed.get(j);
18863                    pir.removeFilter(pa);
18864                }
18865                changed = true;
18866            }
18867        }
18868        if (changed) {
18869            postPreferredActivityChangedBroadcast(userId);
18870        }
18871        return changed;
18872    }
18873
18874    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18875    private void clearIntentFilterVerificationsLPw(int userId) {
18876        final int packageCount = mPackages.size();
18877        for (int i = 0; i < packageCount; i++) {
18878            PackageParser.Package pkg = mPackages.valueAt(i);
18879            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18880        }
18881    }
18882
18883    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18884    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18885        if (userId == UserHandle.USER_ALL) {
18886            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18887                    sUserManager.getUserIds())) {
18888                for (int oneUserId : sUserManager.getUserIds()) {
18889                    scheduleWritePackageRestrictionsLocked(oneUserId);
18890                }
18891            }
18892        } else {
18893            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18894                scheduleWritePackageRestrictionsLocked(userId);
18895            }
18896        }
18897    }
18898
18899    void clearDefaultBrowserIfNeeded(String packageName) {
18900        for (int oneUserId : sUserManager.getUserIds()) {
18901            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18902            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18903            if (packageName.equals(defaultBrowserPackageName)) {
18904                setDefaultBrowserPackageName(null, oneUserId);
18905            }
18906        }
18907    }
18908
18909    @Override
18910    public void resetApplicationPreferences(int userId) {
18911        mContext.enforceCallingOrSelfPermission(
18912                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18913        final long identity = Binder.clearCallingIdentity();
18914        // writer
18915        try {
18916            synchronized (mPackages) {
18917                clearPackagePreferredActivitiesLPw(null, userId);
18918                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18919                // TODO: We have to reset the default SMS and Phone. This requires
18920                // significant refactoring to keep all default apps in the package
18921                // manager (cleaner but more work) or have the services provide
18922                // callbacks to the package manager to request a default app reset.
18923                applyFactoryDefaultBrowserLPw(userId);
18924                clearIntentFilterVerificationsLPw(userId);
18925                primeDomainVerificationsLPw(userId);
18926                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18927                scheduleWritePackageRestrictionsLocked(userId);
18928            }
18929            resetNetworkPolicies(userId);
18930        } finally {
18931            Binder.restoreCallingIdentity(identity);
18932        }
18933    }
18934
18935    @Override
18936    public int getPreferredActivities(List<IntentFilter> outFilters,
18937            List<ComponentName> outActivities, String packageName) {
18938
18939        int num = 0;
18940        final int userId = UserHandle.getCallingUserId();
18941        // reader
18942        synchronized (mPackages) {
18943            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18944            if (pir != null) {
18945                final Iterator<PreferredActivity> it = pir.filterIterator();
18946                while (it.hasNext()) {
18947                    final PreferredActivity pa = it.next();
18948                    if (packageName == null
18949                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18950                                    && pa.mPref.mAlways)) {
18951                        if (outFilters != null) {
18952                            outFilters.add(new IntentFilter(pa));
18953                        }
18954                        if (outActivities != null) {
18955                            outActivities.add(pa.mPref.mComponent);
18956                        }
18957                    }
18958                }
18959            }
18960        }
18961
18962        return num;
18963    }
18964
18965    @Override
18966    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18967            int userId) {
18968        int callingUid = Binder.getCallingUid();
18969        if (callingUid != Process.SYSTEM_UID) {
18970            throw new SecurityException(
18971                    "addPersistentPreferredActivity can only be run by the system");
18972        }
18973        if (filter.countActions() == 0) {
18974            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18975            return;
18976        }
18977        synchronized (mPackages) {
18978            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18979                    ":");
18980            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18981            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18982                    new PersistentPreferredActivity(filter, activity));
18983            scheduleWritePackageRestrictionsLocked(userId);
18984            postPreferredActivityChangedBroadcast(userId);
18985        }
18986    }
18987
18988    @Override
18989    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18990        int callingUid = Binder.getCallingUid();
18991        if (callingUid != Process.SYSTEM_UID) {
18992            throw new SecurityException(
18993                    "clearPackagePersistentPreferredActivities can only be run by the system");
18994        }
18995        ArrayList<PersistentPreferredActivity> removed = null;
18996        boolean changed = false;
18997        synchronized (mPackages) {
18998            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18999                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19000                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19001                        .valueAt(i);
19002                if (userId != thisUserId) {
19003                    continue;
19004                }
19005                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19006                while (it.hasNext()) {
19007                    PersistentPreferredActivity ppa = it.next();
19008                    // Mark entry for removal only if it matches the package name.
19009                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19010                        if (removed == null) {
19011                            removed = new ArrayList<PersistentPreferredActivity>();
19012                        }
19013                        removed.add(ppa);
19014                    }
19015                }
19016                if (removed != null) {
19017                    for (int j=0; j<removed.size(); j++) {
19018                        PersistentPreferredActivity ppa = removed.get(j);
19019                        ppir.removeFilter(ppa);
19020                    }
19021                    changed = true;
19022                }
19023            }
19024
19025            if (changed) {
19026                scheduleWritePackageRestrictionsLocked(userId);
19027                postPreferredActivityChangedBroadcast(userId);
19028            }
19029        }
19030    }
19031
19032    /**
19033     * Common machinery for picking apart a restored XML blob and passing
19034     * it to a caller-supplied functor to be applied to the running system.
19035     */
19036    private void restoreFromXml(XmlPullParser parser, int userId,
19037            String expectedStartTag, BlobXmlRestorer functor)
19038            throws IOException, XmlPullParserException {
19039        int type;
19040        while ((type = parser.next()) != XmlPullParser.START_TAG
19041                && type != XmlPullParser.END_DOCUMENT) {
19042        }
19043        if (type != XmlPullParser.START_TAG) {
19044            // oops didn't find a start tag?!
19045            if (DEBUG_BACKUP) {
19046                Slog.e(TAG, "Didn't find start tag during restore");
19047            }
19048            return;
19049        }
19050Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19051        // this is supposed to be TAG_PREFERRED_BACKUP
19052        if (!expectedStartTag.equals(parser.getName())) {
19053            if (DEBUG_BACKUP) {
19054                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19055            }
19056            return;
19057        }
19058
19059        // skip interfering stuff, then we're aligned with the backing implementation
19060        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19061Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19062        functor.apply(parser, userId);
19063    }
19064
19065    private interface BlobXmlRestorer {
19066        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19067    }
19068
19069    /**
19070     * Non-Binder method, support for the backup/restore mechanism: write the
19071     * full set of preferred activities in its canonical XML format.  Returns the
19072     * XML output as a byte array, or null if there is none.
19073     */
19074    @Override
19075    public byte[] getPreferredActivityBackup(int userId) {
19076        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19077            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19078        }
19079
19080        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19081        try {
19082            final XmlSerializer serializer = new FastXmlSerializer();
19083            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19084            serializer.startDocument(null, true);
19085            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19086
19087            synchronized (mPackages) {
19088                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19089            }
19090
19091            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19092            serializer.endDocument();
19093            serializer.flush();
19094        } catch (Exception e) {
19095            if (DEBUG_BACKUP) {
19096                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19097            }
19098            return null;
19099        }
19100
19101        return dataStream.toByteArray();
19102    }
19103
19104    @Override
19105    public void restorePreferredActivities(byte[] backup, int userId) {
19106        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19107            throw new SecurityException("Only the system may call restorePreferredActivities()");
19108        }
19109
19110        try {
19111            final XmlPullParser parser = Xml.newPullParser();
19112            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19113            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19114                    new BlobXmlRestorer() {
19115                        @Override
19116                        public void apply(XmlPullParser parser, int userId)
19117                                throws XmlPullParserException, IOException {
19118                            synchronized (mPackages) {
19119                                mSettings.readPreferredActivitiesLPw(parser, userId);
19120                            }
19121                        }
19122                    } );
19123        } catch (Exception e) {
19124            if (DEBUG_BACKUP) {
19125                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19126            }
19127        }
19128    }
19129
19130    /**
19131     * Non-Binder method, support for the backup/restore mechanism: write the
19132     * default browser (etc) settings in its canonical XML format.  Returns the default
19133     * browser XML representation as a byte array, or null if there is none.
19134     */
19135    @Override
19136    public byte[] getDefaultAppsBackup(int userId) {
19137        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19138            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19139        }
19140
19141        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19142        try {
19143            final XmlSerializer serializer = new FastXmlSerializer();
19144            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19145            serializer.startDocument(null, true);
19146            serializer.startTag(null, TAG_DEFAULT_APPS);
19147
19148            synchronized (mPackages) {
19149                mSettings.writeDefaultAppsLPr(serializer, userId);
19150            }
19151
19152            serializer.endTag(null, TAG_DEFAULT_APPS);
19153            serializer.endDocument();
19154            serializer.flush();
19155        } catch (Exception e) {
19156            if (DEBUG_BACKUP) {
19157                Slog.e(TAG, "Unable to write default apps for backup", e);
19158            }
19159            return null;
19160        }
19161
19162        return dataStream.toByteArray();
19163    }
19164
19165    @Override
19166    public void restoreDefaultApps(byte[] backup, int userId) {
19167        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19168            throw new SecurityException("Only the system may call restoreDefaultApps()");
19169        }
19170
19171        try {
19172            final XmlPullParser parser = Xml.newPullParser();
19173            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19174            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19175                    new BlobXmlRestorer() {
19176                        @Override
19177                        public void apply(XmlPullParser parser, int userId)
19178                                throws XmlPullParserException, IOException {
19179                            synchronized (mPackages) {
19180                                mSettings.readDefaultAppsLPw(parser, userId);
19181                            }
19182                        }
19183                    } );
19184        } catch (Exception e) {
19185            if (DEBUG_BACKUP) {
19186                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19187            }
19188        }
19189    }
19190
19191    @Override
19192    public byte[] getIntentFilterVerificationBackup(int userId) {
19193        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19194            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19195        }
19196
19197        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19198        try {
19199            final XmlSerializer serializer = new FastXmlSerializer();
19200            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19201            serializer.startDocument(null, true);
19202            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19203
19204            synchronized (mPackages) {
19205                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19206            }
19207
19208            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19209            serializer.endDocument();
19210            serializer.flush();
19211        } catch (Exception e) {
19212            if (DEBUG_BACKUP) {
19213                Slog.e(TAG, "Unable to write default apps for backup", e);
19214            }
19215            return null;
19216        }
19217
19218        return dataStream.toByteArray();
19219    }
19220
19221    @Override
19222    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19223        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19224            throw new SecurityException("Only the system may call restorePreferredActivities()");
19225        }
19226
19227        try {
19228            final XmlPullParser parser = Xml.newPullParser();
19229            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19230            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19231                    new BlobXmlRestorer() {
19232                        @Override
19233                        public void apply(XmlPullParser parser, int userId)
19234                                throws XmlPullParserException, IOException {
19235                            synchronized (mPackages) {
19236                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19237                                mSettings.writeLPr();
19238                            }
19239                        }
19240                    } );
19241        } catch (Exception e) {
19242            if (DEBUG_BACKUP) {
19243                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19244            }
19245        }
19246    }
19247
19248    @Override
19249    public byte[] getPermissionGrantBackup(int userId) {
19250        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19251            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19252        }
19253
19254        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19255        try {
19256            final XmlSerializer serializer = new FastXmlSerializer();
19257            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19258            serializer.startDocument(null, true);
19259            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19260
19261            synchronized (mPackages) {
19262                serializeRuntimePermissionGrantsLPr(serializer, userId);
19263            }
19264
19265            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19266            serializer.endDocument();
19267            serializer.flush();
19268        } catch (Exception e) {
19269            if (DEBUG_BACKUP) {
19270                Slog.e(TAG, "Unable to write default apps for backup", e);
19271            }
19272            return null;
19273        }
19274
19275        return dataStream.toByteArray();
19276    }
19277
19278    @Override
19279    public void restorePermissionGrants(byte[] backup, int userId) {
19280        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19281            throw new SecurityException("Only the system may call restorePermissionGrants()");
19282        }
19283
19284        try {
19285            final XmlPullParser parser = Xml.newPullParser();
19286            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19287            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19288                    new BlobXmlRestorer() {
19289                        @Override
19290                        public void apply(XmlPullParser parser, int userId)
19291                                throws XmlPullParserException, IOException {
19292                            synchronized (mPackages) {
19293                                processRestoredPermissionGrantsLPr(parser, userId);
19294                            }
19295                        }
19296                    } );
19297        } catch (Exception e) {
19298            if (DEBUG_BACKUP) {
19299                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19300            }
19301        }
19302    }
19303
19304    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19305            throws IOException {
19306        serializer.startTag(null, TAG_ALL_GRANTS);
19307
19308        final int N = mSettings.mPackages.size();
19309        for (int i = 0; i < N; i++) {
19310            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19311            boolean pkgGrantsKnown = false;
19312
19313            PermissionsState packagePerms = ps.getPermissionsState();
19314
19315            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19316                final int grantFlags = state.getFlags();
19317                // only look at grants that are not system/policy fixed
19318                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19319                    final boolean isGranted = state.isGranted();
19320                    // And only back up the user-twiddled state bits
19321                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19322                        final String packageName = mSettings.mPackages.keyAt(i);
19323                        if (!pkgGrantsKnown) {
19324                            serializer.startTag(null, TAG_GRANT);
19325                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19326                            pkgGrantsKnown = true;
19327                        }
19328
19329                        final boolean userSet =
19330                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19331                        final boolean userFixed =
19332                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19333                        final boolean revoke =
19334                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19335
19336                        serializer.startTag(null, TAG_PERMISSION);
19337                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19338                        if (isGranted) {
19339                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19340                        }
19341                        if (userSet) {
19342                            serializer.attribute(null, ATTR_USER_SET, "true");
19343                        }
19344                        if (userFixed) {
19345                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19346                        }
19347                        if (revoke) {
19348                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19349                        }
19350                        serializer.endTag(null, TAG_PERMISSION);
19351                    }
19352                }
19353            }
19354
19355            if (pkgGrantsKnown) {
19356                serializer.endTag(null, TAG_GRANT);
19357            }
19358        }
19359
19360        serializer.endTag(null, TAG_ALL_GRANTS);
19361    }
19362
19363    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19364            throws XmlPullParserException, IOException {
19365        String pkgName = null;
19366        int outerDepth = parser.getDepth();
19367        int type;
19368        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19369                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19370            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19371                continue;
19372            }
19373
19374            final String tagName = parser.getName();
19375            if (tagName.equals(TAG_GRANT)) {
19376                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19377                if (DEBUG_BACKUP) {
19378                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19379                }
19380            } else if (tagName.equals(TAG_PERMISSION)) {
19381
19382                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19383                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19384
19385                int newFlagSet = 0;
19386                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19387                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19388                }
19389                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19390                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19391                }
19392                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19393                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19394                }
19395                if (DEBUG_BACKUP) {
19396                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19397                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19398                }
19399                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19400                if (ps != null) {
19401                    // Already installed so we apply the grant immediately
19402                    if (DEBUG_BACKUP) {
19403                        Slog.v(TAG, "        + already installed; applying");
19404                    }
19405                    PermissionsState perms = ps.getPermissionsState();
19406                    BasePermission bp = mSettings.mPermissions.get(permName);
19407                    if (bp != null) {
19408                        if (isGranted) {
19409                            perms.grantRuntimePermission(bp, userId);
19410                        }
19411                        if (newFlagSet != 0) {
19412                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19413                        }
19414                    }
19415                } else {
19416                    // Need to wait for post-restore install to apply the grant
19417                    if (DEBUG_BACKUP) {
19418                        Slog.v(TAG, "        - not yet installed; saving for later");
19419                    }
19420                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19421                            isGranted, newFlagSet, userId);
19422                }
19423            } else {
19424                PackageManagerService.reportSettingsProblem(Log.WARN,
19425                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19426                XmlUtils.skipCurrentTag(parser);
19427            }
19428        }
19429
19430        scheduleWriteSettingsLocked();
19431        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19432    }
19433
19434    @Override
19435    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19436            int sourceUserId, int targetUserId, int flags) {
19437        mContext.enforceCallingOrSelfPermission(
19438                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19439        int callingUid = Binder.getCallingUid();
19440        enforceOwnerRights(ownerPackage, callingUid);
19441        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19442        if (intentFilter.countActions() == 0) {
19443            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19444            return;
19445        }
19446        synchronized (mPackages) {
19447            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19448                    ownerPackage, targetUserId, flags);
19449            CrossProfileIntentResolver resolver =
19450                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19451            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19452            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19453            if (existing != null) {
19454                int size = existing.size();
19455                for (int i = 0; i < size; i++) {
19456                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19457                        return;
19458                    }
19459                }
19460            }
19461            resolver.addFilter(newFilter);
19462            scheduleWritePackageRestrictionsLocked(sourceUserId);
19463        }
19464    }
19465
19466    @Override
19467    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19468        mContext.enforceCallingOrSelfPermission(
19469                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19470        int callingUid = Binder.getCallingUid();
19471        enforceOwnerRights(ownerPackage, callingUid);
19472        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19473        synchronized (mPackages) {
19474            CrossProfileIntentResolver resolver =
19475                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19476            ArraySet<CrossProfileIntentFilter> set =
19477                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19478            for (CrossProfileIntentFilter filter : set) {
19479                if (filter.getOwnerPackage().equals(ownerPackage)) {
19480                    resolver.removeFilter(filter);
19481                }
19482            }
19483            scheduleWritePackageRestrictionsLocked(sourceUserId);
19484        }
19485    }
19486
19487    // Enforcing that callingUid is owning pkg on userId
19488    private void enforceOwnerRights(String pkg, int callingUid) {
19489        // The system owns everything.
19490        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19491            return;
19492        }
19493        int callingUserId = UserHandle.getUserId(callingUid);
19494        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19495        if (pi == null) {
19496            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19497                    + callingUserId);
19498        }
19499        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19500            throw new SecurityException("Calling uid " + callingUid
19501                    + " does not own package " + pkg);
19502        }
19503    }
19504
19505    @Override
19506    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19507        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19508    }
19509
19510    private Intent getHomeIntent() {
19511        Intent intent = new Intent(Intent.ACTION_MAIN);
19512        intent.addCategory(Intent.CATEGORY_HOME);
19513        intent.addCategory(Intent.CATEGORY_DEFAULT);
19514        return intent;
19515    }
19516
19517    private IntentFilter getHomeFilter() {
19518        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19519        filter.addCategory(Intent.CATEGORY_HOME);
19520        filter.addCategory(Intent.CATEGORY_DEFAULT);
19521        return filter;
19522    }
19523
19524    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19525            int userId) {
19526        Intent intent  = getHomeIntent();
19527        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19528                PackageManager.GET_META_DATA, userId);
19529        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19530                true, false, false, userId);
19531
19532        allHomeCandidates.clear();
19533        if (list != null) {
19534            for (ResolveInfo ri : list) {
19535                allHomeCandidates.add(ri);
19536            }
19537        }
19538        return (preferred == null || preferred.activityInfo == null)
19539                ? null
19540                : new ComponentName(preferred.activityInfo.packageName,
19541                        preferred.activityInfo.name);
19542    }
19543
19544    @Override
19545    public void setHomeActivity(ComponentName comp, int userId) {
19546        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19547        getHomeActivitiesAsUser(homeActivities, userId);
19548
19549        boolean found = false;
19550
19551        final int size = homeActivities.size();
19552        final ComponentName[] set = new ComponentName[size];
19553        for (int i = 0; i < size; i++) {
19554            final ResolveInfo candidate = homeActivities.get(i);
19555            final ActivityInfo info = candidate.activityInfo;
19556            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19557            set[i] = activityName;
19558            if (!found && activityName.equals(comp)) {
19559                found = true;
19560            }
19561        }
19562        if (!found) {
19563            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19564                    + userId);
19565        }
19566        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19567                set, comp, userId);
19568    }
19569
19570    private @Nullable String getSetupWizardPackageName() {
19571        final Intent intent = new Intent(Intent.ACTION_MAIN);
19572        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19573
19574        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19575                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19576                        | MATCH_DISABLED_COMPONENTS,
19577                UserHandle.myUserId());
19578        if (matches.size() == 1) {
19579            return matches.get(0).getComponentInfo().packageName;
19580        } else {
19581            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19582                    + ": matches=" + matches);
19583            return null;
19584        }
19585    }
19586
19587    private @Nullable String getStorageManagerPackageName() {
19588        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19589
19590        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19591                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19592                        | MATCH_DISABLED_COMPONENTS,
19593                UserHandle.myUserId());
19594        if (matches.size() == 1) {
19595            return matches.get(0).getComponentInfo().packageName;
19596        } else {
19597            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19598                    + matches.size() + ": matches=" + matches);
19599            return null;
19600        }
19601    }
19602
19603    @Override
19604    public void setApplicationEnabledSetting(String appPackageName,
19605            int newState, int flags, int userId, String callingPackage) {
19606        if (!sUserManager.exists(userId)) return;
19607        if (callingPackage == null) {
19608            callingPackage = Integer.toString(Binder.getCallingUid());
19609        }
19610        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19611    }
19612
19613    @Override
19614    public void setComponentEnabledSetting(ComponentName componentName,
19615            int newState, int flags, int userId) {
19616        if (!sUserManager.exists(userId)) return;
19617        setEnabledSetting(componentName.getPackageName(),
19618                componentName.getClassName(), newState, flags, userId, null);
19619    }
19620
19621    private void setEnabledSetting(final String packageName, String className, int newState,
19622            final int flags, int userId, String callingPackage) {
19623        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19624              || newState == COMPONENT_ENABLED_STATE_ENABLED
19625              || newState == COMPONENT_ENABLED_STATE_DISABLED
19626              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19627              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19628            throw new IllegalArgumentException("Invalid new component state: "
19629                    + newState);
19630        }
19631        PackageSetting pkgSetting;
19632        final int uid = Binder.getCallingUid();
19633        final int permission;
19634        if (uid == Process.SYSTEM_UID) {
19635            permission = PackageManager.PERMISSION_GRANTED;
19636        } else {
19637            permission = mContext.checkCallingOrSelfPermission(
19638                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19639        }
19640        enforceCrossUserPermission(uid, userId,
19641                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19642        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19643        boolean sendNow = false;
19644        boolean isApp = (className == null);
19645        String componentName = isApp ? packageName : className;
19646        int packageUid = -1;
19647        ArrayList<String> components;
19648
19649        // writer
19650        synchronized (mPackages) {
19651            pkgSetting = mSettings.mPackages.get(packageName);
19652            if (pkgSetting == null) {
19653                if (className == null) {
19654                    throw new IllegalArgumentException("Unknown package: " + packageName);
19655                }
19656                throw new IllegalArgumentException(
19657                        "Unknown component: " + packageName + "/" + className);
19658            }
19659        }
19660
19661        // Limit who can change which apps
19662        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19663            // Don't allow apps that don't have permission to modify other apps
19664            if (!allowedByPermission) {
19665                throw new SecurityException(
19666                        "Permission Denial: attempt to change component state from pid="
19667                        + Binder.getCallingPid()
19668                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19669            }
19670            // Don't allow changing protected packages.
19671            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19672                throw new SecurityException("Cannot disable a protected package: " + packageName);
19673            }
19674        }
19675
19676        synchronized (mPackages) {
19677            if (uid == Process.SHELL_UID
19678                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19679                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19680                // unless it is a test package.
19681                int oldState = pkgSetting.getEnabled(userId);
19682                if (className == null
19683                    &&
19684                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19685                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19686                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19687                    &&
19688                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19689                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19690                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19691                    // ok
19692                } else {
19693                    throw new SecurityException(
19694                            "Shell cannot change component state for " + packageName + "/"
19695                            + className + " to " + newState);
19696                }
19697            }
19698            if (className == null) {
19699                // We're dealing with an application/package level state change
19700                if (pkgSetting.getEnabled(userId) == newState) {
19701                    // Nothing to do
19702                    return;
19703                }
19704                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19705                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19706                    // Don't care about who enables an app.
19707                    callingPackage = null;
19708                }
19709                pkgSetting.setEnabled(newState, userId, callingPackage);
19710                // pkgSetting.pkg.mSetEnabled = newState;
19711            } else {
19712                // We're dealing with a component level state change
19713                // First, verify that this is a valid class name.
19714                PackageParser.Package pkg = pkgSetting.pkg;
19715                if (pkg == null || !pkg.hasComponentClassName(className)) {
19716                    if (pkg != null &&
19717                            pkg.applicationInfo.targetSdkVersion >=
19718                                    Build.VERSION_CODES.JELLY_BEAN) {
19719                        throw new IllegalArgumentException("Component class " + className
19720                                + " does not exist in " + packageName);
19721                    } else {
19722                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19723                                + className + " does not exist in " + packageName);
19724                    }
19725                }
19726                switch (newState) {
19727                case COMPONENT_ENABLED_STATE_ENABLED:
19728                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19729                        return;
19730                    }
19731                    break;
19732                case COMPONENT_ENABLED_STATE_DISABLED:
19733                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19734                        return;
19735                    }
19736                    break;
19737                case COMPONENT_ENABLED_STATE_DEFAULT:
19738                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19739                        return;
19740                    }
19741                    break;
19742                default:
19743                    Slog.e(TAG, "Invalid new component state: " + newState);
19744                    return;
19745                }
19746            }
19747            scheduleWritePackageRestrictionsLocked(userId);
19748            components = mPendingBroadcasts.get(userId, packageName);
19749            final boolean newPackage = components == null;
19750            if (newPackage) {
19751                components = new ArrayList<String>();
19752            }
19753            if (!components.contains(componentName)) {
19754                components.add(componentName);
19755            }
19756            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19757                sendNow = true;
19758                // Purge entry from pending broadcast list if another one exists already
19759                // since we are sending one right away.
19760                mPendingBroadcasts.remove(userId, packageName);
19761            } else {
19762                if (newPackage) {
19763                    mPendingBroadcasts.put(userId, packageName, components);
19764                }
19765                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19766                    // Schedule a message
19767                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19768                }
19769            }
19770        }
19771
19772        long callingId = Binder.clearCallingIdentity();
19773        try {
19774            if (sendNow) {
19775                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19776                sendPackageChangedBroadcast(packageName,
19777                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19778            }
19779        } finally {
19780            Binder.restoreCallingIdentity(callingId);
19781        }
19782    }
19783
19784    @Override
19785    public void flushPackageRestrictionsAsUser(int userId) {
19786        if (!sUserManager.exists(userId)) {
19787            return;
19788        }
19789        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19790                false /* checkShell */, "flushPackageRestrictions");
19791        synchronized (mPackages) {
19792            mSettings.writePackageRestrictionsLPr(userId);
19793            mDirtyUsers.remove(userId);
19794            if (mDirtyUsers.isEmpty()) {
19795                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19796            }
19797        }
19798    }
19799
19800    private void sendPackageChangedBroadcast(String packageName,
19801            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19802        if (DEBUG_INSTALL)
19803            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19804                    + componentNames);
19805        Bundle extras = new Bundle(4);
19806        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19807        String nameList[] = new String[componentNames.size()];
19808        componentNames.toArray(nameList);
19809        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19810        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19811        extras.putInt(Intent.EXTRA_UID, packageUid);
19812        // If this is not reporting a change of the overall package, then only send it
19813        // to registered receivers.  We don't want to launch a swath of apps for every
19814        // little component state change.
19815        final int flags = !componentNames.contains(packageName)
19816                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19817        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19818                new int[] {UserHandle.getUserId(packageUid)});
19819    }
19820
19821    @Override
19822    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19823        if (!sUserManager.exists(userId)) return;
19824        final int uid = Binder.getCallingUid();
19825        final int permission = mContext.checkCallingOrSelfPermission(
19826                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19827        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19828        enforceCrossUserPermission(uid, userId,
19829                true /* requireFullPermission */, true /* checkShell */, "stop package");
19830        // writer
19831        synchronized (mPackages) {
19832            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19833                    allowedByPermission, uid, userId)) {
19834                scheduleWritePackageRestrictionsLocked(userId);
19835            }
19836        }
19837    }
19838
19839    @Override
19840    public String getInstallerPackageName(String packageName) {
19841        // reader
19842        synchronized (mPackages) {
19843            return mSettings.getInstallerPackageNameLPr(packageName);
19844        }
19845    }
19846
19847    public boolean isOrphaned(String packageName) {
19848        // reader
19849        synchronized (mPackages) {
19850            return mSettings.isOrphaned(packageName);
19851        }
19852    }
19853
19854    @Override
19855    public int getApplicationEnabledSetting(String packageName, int userId) {
19856        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19857        int uid = Binder.getCallingUid();
19858        enforceCrossUserPermission(uid, userId,
19859                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19860        // reader
19861        synchronized (mPackages) {
19862            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19863        }
19864    }
19865
19866    @Override
19867    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19868        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19869        int uid = Binder.getCallingUid();
19870        enforceCrossUserPermission(uid, userId,
19871                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19872        // reader
19873        synchronized (mPackages) {
19874            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19875        }
19876    }
19877
19878    @Override
19879    public void enterSafeMode() {
19880        enforceSystemOrRoot("Only the system can request entering safe mode");
19881
19882        if (!mSystemReady) {
19883            mSafeMode = true;
19884        }
19885    }
19886
19887    @Override
19888    public void systemReady() {
19889        mSystemReady = true;
19890
19891        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19892        // disabled after already being started.
19893        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19894                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19895
19896        // Read the compatibilty setting when the system is ready.
19897        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19898                mContext.getContentResolver(),
19899                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19900        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19901        if (DEBUG_SETTINGS) {
19902            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19903        }
19904
19905        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19906
19907        synchronized (mPackages) {
19908            // Verify that all of the preferred activity components actually
19909            // exist.  It is possible for applications to be updated and at
19910            // that point remove a previously declared activity component that
19911            // had been set as a preferred activity.  We try to clean this up
19912            // the next time we encounter that preferred activity, but it is
19913            // possible for the user flow to never be able to return to that
19914            // situation so here we do a sanity check to make sure we haven't
19915            // left any junk around.
19916            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19917            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19918                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19919                removed.clear();
19920                for (PreferredActivity pa : pir.filterSet()) {
19921                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19922                        removed.add(pa);
19923                    }
19924                }
19925                if (removed.size() > 0) {
19926                    for (int r=0; r<removed.size(); r++) {
19927                        PreferredActivity pa = removed.get(r);
19928                        Slog.w(TAG, "Removing dangling preferred activity: "
19929                                + pa.mPref.mComponent);
19930                        pir.removeFilter(pa);
19931                    }
19932                    mSettings.writePackageRestrictionsLPr(
19933                            mSettings.mPreferredActivities.keyAt(i));
19934                }
19935            }
19936
19937            for (int userId : UserManagerService.getInstance().getUserIds()) {
19938                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19939                    grantPermissionsUserIds = ArrayUtils.appendInt(
19940                            grantPermissionsUserIds, userId);
19941                }
19942            }
19943        }
19944        sUserManager.systemReady();
19945
19946        // If we upgraded grant all default permissions before kicking off.
19947        for (int userId : grantPermissionsUserIds) {
19948            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19949        }
19950
19951        // If we did not grant default permissions, we preload from this the
19952        // default permission exceptions lazily to ensure we don't hit the
19953        // disk on a new user creation.
19954        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19955            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19956        }
19957
19958        // Kick off any messages waiting for system ready
19959        if (mPostSystemReadyMessages != null) {
19960            for (Message msg : mPostSystemReadyMessages) {
19961                msg.sendToTarget();
19962            }
19963            mPostSystemReadyMessages = null;
19964        }
19965
19966        // Watch for external volumes that come and go over time
19967        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19968        storage.registerListener(mStorageListener);
19969
19970        mInstallerService.systemReady();
19971        mPackageDexOptimizer.systemReady();
19972
19973        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19974                StorageManagerInternal.class);
19975        StorageManagerInternal.addExternalStoragePolicy(
19976                new StorageManagerInternal.ExternalStorageMountPolicy() {
19977            @Override
19978            public int getMountMode(int uid, String packageName) {
19979                if (Process.isIsolated(uid)) {
19980                    return Zygote.MOUNT_EXTERNAL_NONE;
19981                }
19982                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19983                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19984                }
19985                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19986                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19987                }
19988                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19989                    return Zygote.MOUNT_EXTERNAL_READ;
19990                }
19991                return Zygote.MOUNT_EXTERNAL_WRITE;
19992            }
19993
19994            @Override
19995            public boolean hasExternalStorage(int uid, String packageName) {
19996                return true;
19997            }
19998        });
19999
20000        // Now that we're mostly running, clean up stale users and apps
20001        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20002        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20003
20004        if (mPrivappPermissionsViolations != null) {
20005            Slog.wtf(TAG,"Signature|privileged permissions not in "
20006                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20007            mPrivappPermissionsViolations = null;
20008        }
20009    }
20010
20011    @Override
20012    public boolean isSafeMode() {
20013        return mSafeMode;
20014    }
20015
20016    @Override
20017    public boolean hasSystemUidErrors() {
20018        return mHasSystemUidErrors;
20019    }
20020
20021    static String arrayToString(int[] array) {
20022        StringBuffer buf = new StringBuffer(128);
20023        buf.append('[');
20024        if (array != null) {
20025            for (int i=0; i<array.length; i++) {
20026                if (i > 0) buf.append(", ");
20027                buf.append(array[i]);
20028            }
20029        }
20030        buf.append(']');
20031        return buf.toString();
20032    }
20033
20034    static class DumpState {
20035        public static final int DUMP_LIBS = 1 << 0;
20036        public static final int DUMP_FEATURES = 1 << 1;
20037        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20038        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20039        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20040        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20041        public static final int DUMP_PERMISSIONS = 1 << 6;
20042        public static final int DUMP_PACKAGES = 1 << 7;
20043        public static final int DUMP_SHARED_USERS = 1 << 8;
20044        public static final int DUMP_MESSAGES = 1 << 9;
20045        public static final int DUMP_PROVIDERS = 1 << 10;
20046        public static final int DUMP_VERIFIERS = 1 << 11;
20047        public static final int DUMP_PREFERRED = 1 << 12;
20048        public static final int DUMP_PREFERRED_XML = 1 << 13;
20049        public static final int DUMP_KEYSETS = 1 << 14;
20050        public static final int DUMP_VERSION = 1 << 15;
20051        public static final int DUMP_INSTALLS = 1 << 16;
20052        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20053        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20054        public static final int DUMP_FROZEN = 1 << 19;
20055        public static final int DUMP_DEXOPT = 1 << 20;
20056        public static final int DUMP_COMPILER_STATS = 1 << 21;
20057
20058        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20059
20060        private int mTypes;
20061
20062        private int mOptions;
20063
20064        private boolean mTitlePrinted;
20065
20066        private SharedUserSetting mSharedUser;
20067
20068        public boolean isDumping(int type) {
20069            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20070                return true;
20071            }
20072
20073            return (mTypes & type) != 0;
20074        }
20075
20076        public void setDump(int type) {
20077            mTypes |= type;
20078        }
20079
20080        public boolean isOptionEnabled(int option) {
20081            return (mOptions & option) != 0;
20082        }
20083
20084        public void setOptionEnabled(int option) {
20085            mOptions |= option;
20086        }
20087
20088        public boolean onTitlePrinted() {
20089            final boolean printed = mTitlePrinted;
20090            mTitlePrinted = true;
20091            return printed;
20092        }
20093
20094        public boolean getTitlePrinted() {
20095            return mTitlePrinted;
20096        }
20097
20098        public void setTitlePrinted(boolean enabled) {
20099            mTitlePrinted = enabled;
20100        }
20101
20102        public SharedUserSetting getSharedUser() {
20103            return mSharedUser;
20104        }
20105
20106        public void setSharedUser(SharedUserSetting user) {
20107            mSharedUser = user;
20108        }
20109    }
20110
20111    @Override
20112    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20113            FileDescriptor err, String[] args, ShellCallback callback,
20114            ResultReceiver resultReceiver) {
20115        (new PackageManagerShellCommand(this)).exec(
20116                this, in, out, err, args, callback, resultReceiver);
20117    }
20118
20119    @Override
20120    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20121        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20122                != PackageManager.PERMISSION_GRANTED) {
20123            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20124                    + Binder.getCallingPid()
20125                    + ", uid=" + Binder.getCallingUid()
20126                    + " without permission "
20127                    + android.Manifest.permission.DUMP);
20128            return;
20129        }
20130
20131        DumpState dumpState = new DumpState();
20132        boolean fullPreferred = false;
20133        boolean checkin = false;
20134
20135        String packageName = null;
20136        ArraySet<String> permissionNames = null;
20137
20138        int opti = 0;
20139        while (opti < args.length) {
20140            String opt = args[opti];
20141            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20142                break;
20143            }
20144            opti++;
20145
20146            if ("-a".equals(opt)) {
20147                // Right now we only know how to print all.
20148            } else if ("-h".equals(opt)) {
20149                pw.println("Package manager dump options:");
20150                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20151                pw.println("    --checkin: dump for a checkin");
20152                pw.println("    -f: print details of intent filters");
20153                pw.println("    -h: print this help");
20154                pw.println("  cmd may be one of:");
20155                pw.println("    l[ibraries]: list known shared libraries");
20156                pw.println("    f[eatures]: list device features");
20157                pw.println("    k[eysets]: print known keysets");
20158                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20159                pw.println("    perm[issions]: dump permissions");
20160                pw.println("    permission [name ...]: dump declaration and use of given permission");
20161                pw.println("    pref[erred]: print preferred package settings");
20162                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20163                pw.println("    prov[iders]: dump content providers");
20164                pw.println("    p[ackages]: dump installed packages");
20165                pw.println("    s[hared-users]: dump shared user IDs");
20166                pw.println("    m[essages]: print collected runtime messages");
20167                pw.println("    v[erifiers]: print package verifier info");
20168                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20169                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20170                pw.println("    version: print database version info");
20171                pw.println("    write: write current settings now");
20172                pw.println("    installs: details about install sessions");
20173                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20174                pw.println("    dexopt: dump dexopt state");
20175                pw.println("    compiler-stats: dump compiler statistics");
20176                pw.println("    <package.name>: info about given package");
20177                return;
20178            } else if ("--checkin".equals(opt)) {
20179                checkin = true;
20180            } else if ("-f".equals(opt)) {
20181                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20182            } else {
20183                pw.println("Unknown argument: " + opt + "; use -h for help");
20184            }
20185        }
20186
20187        // Is the caller requesting to dump a particular piece of data?
20188        if (opti < args.length) {
20189            String cmd = args[opti];
20190            opti++;
20191            // Is this a package name?
20192            if ("android".equals(cmd) || cmd.contains(".")) {
20193                packageName = cmd;
20194                // When dumping a single package, we always dump all of its
20195                // filter information since the amount of data will be reasonable.
20196                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20197            } else if ("check-permission".equals(cmd)) {
20198                if (opti >= args.length) {
20199                    pw.println("Error: check-permission missing permission argument");
20200                    return;
20201                }
20202                String perm = args[opti];
20203                opti++;
20204                if (opti >= args.length) {
20205                    pw.println("Error: check-permission missing package argument");
20206                    return;
20207                }
20208
20209                String pkg = args[opti];
20210                opti++;
20211                int user = UserHandle.getUserId(Binder.getCallingUid());
20212                if (opti < args.length) {
20213                    try {
20214                        user = Integer.parseInt(args[opti]);
20215                    } catch (NumberFormatException e) {
20216                        pw.println("Error: check-permission user argument is not a number: "
20217                                + args[opti]);
20218                        return;
20219                    }
20220                }
20221
20222                // Normalize package name to handle renamed packages and static libs
20223                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20224
20225                pw.println(checkPermission(perm, pkg, user));
20226                return;
20227            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20228                dumpState.setDump(DumpState.DUMP_LIBS);
20229            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20230                dumpState.setDump(DumpState.DUMP_FEATURES);
20231            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20232                if (opti >= args.length) {
20233                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20234                            | DumpState.DUMP_SERVICE_RESOLVERS
20235                            | DumpState.DUMP_RECEIVER_RESOLVERS
20236                            | DumpState.DUMP_CONTENT_RESOLVERS);
20237                } else {
20238                    while (opti < args.length) {
20239                        String name = args[opti];
20240                        if ("a".equals(name) || "activity".equals(name)) {
20241                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20242                        } else if ("s".equals(name) || "service".equals(name)) {
20243                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20244                        } else if ("r".equals(name) || "receiver".equals(name)) {
20245                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20246                        } else if ("c".equals(name) || "content".equals(name)) {
20247                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20248                        } else {
20249                            pw.println("Error: unknown resolver table type: " + name);
20250                            return;
20251                        }
20252                        opti++;
20253                    }
20254                }
20255            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20256                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20257            } else if ("permission".equals(cmd)) {
20258                if (opti >= args.length) {
20259                    pw.println("Error: permission requires permission name");
20260                    return;
20261                }
20262                permissionNames = new ArraySet<>();
20263                while (opti < args.length) {
20264                    permissionNames.add(args[opti]);
20265                    opti++;
20266                }
20267                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20268                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20269            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20270                dumpState.setDump(DumpState.DUMP_PREFERRED);
20271            } else if ("preferred-xml".equals(cmd)) {
20272                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20273                if (opti < args.length && "--full".equals(args[opti])) {
20274                    fullPreferred = true;
20275                    opti++;
20276                }
20277            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20278                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20279            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20280                dumpState.setDump(DumpState.DUMP_PACKAGES);
20281            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20282                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20283            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20284                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20285            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20286                dumpState.setDump(DumpState.DUMP_MESSAGES);
20287            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20288                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20289            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20290                    || "intent-filter-verifiers".equals(cmd)) {
20291                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20292            } else if ("version".equals(cmd)) {
20293                dumpState.setDump(DumpState.DUMP_VERSION);
20294            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20295                dumpState.setDump(DumpState.DUMP_KEYSETS);
20296            } else if ("installs".equals(cmd)) {
20297                dumpState.setDump(DumpState.DUMP_INSTALLS);
20298            } else if ("frozen".equals(cmd)) {
20299                dumpState.setDump(DumpState.DUMP_FROZEN);
20300            } else if ("dexopt".equals(cmd)) {
20301                dumpState.setDump(DumpState.DUMP_DEXOPT);
20302            } else if ("compiler-stats".equals(cmd)) {
20303                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20304            } else if ("write".equals(cmd)) {
20305                synchronized (mPackages) {
20306                    mSettings.writeLPr();
20307                    pw.println("Settings written.");
20308                    return;
20309                }
20310            }
20311        }
20312
20313        if (checkin) {
20314            pw.println("vers,1");
20315        }
20316
20317        // reader
20318        synchronized (mPackages) {
20319            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20320                if (!checkin) {
20321                    if (dumpState.onTitlePrinted())
20322                        pw.println();
20323                    pw.println("Database versions:");
20324                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20325                }
20326            }
20327
20328            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20329                if (!checkin) {
20330                    if (dumpState.onTitlePrinted())
20331                        pw.println();
20332                    pw.println("Verifiers:");
20333                    pw.print("  Required: ");
20334                    pw.print(mRequiredVerifierPackage);
20335                    pw.print(" (uid=");
20336                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20337                            UserHandle.USER_SYSTEM));
20338                    pw.println(")");
20339                } else if (mRequiredVerifierPackage != null) {
20340                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20341                    pw.print(",");
20342                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20343                            UserHandle.USER_SYSTEM));
20344                }
20345            }
20346
20347            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20348                    packageName == null) {
20349                if (mIntentFilterVerifierComponent != null) {
20350                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20351                    if (!checkin) {
20352                        if (dumpState.onTitlePrinted())
20353                            pw.println();
20354                        pw.println("Intent Filter Verifier:");
20355                        pw.print("  Using: ");
20356                        pw.print(verifierPackageName);
20357                        pw.print(" (uid=");
20358                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20359                                UserHandle.USER_SYSTEM));
20360                        pw.println(")");
20361                    } else if (verifierPackageName != null) {
20362                        pw.print("ifv,"); pw.print(verifierPackageName);
20363                        pw.print(",");
20364                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20365                                UserHandle.USER_SYSTEM));
20366                    }
20367                } else {
20368                    pw.println();
20369                    pw.println("No Intent Filter Verifier available!");
20370                }
20371            }
20372
20373            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20374                boolean printedHeader = false;
20375                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20376                while (it.hasNext()) {
20377                    String libName = it.next();
20378                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20379                    if (versionedLib == null) {
20380                        continue;
20381                    }
20382                    final int versionCount = versionedLib.size();
20383                    for (int i = 0; i < versionCount; i++) {
20384                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20385                        if (!checkin) {
20386                            if (!printedHeader) {
20387                                if (dumpState.onTitlePrinted())
20388                                    pw.println();
20389                                pw.println("Libraries:");
20390                                printedHeader = true;
20391                            }
20392                            pw.print("  ");
20393                        } else {
20394                            pw.print("lib,");
20395                        }
20396                        pw.print(libEntry.info.getName());
20397                        if (libEntry.info.isStatic()) {
20398                            pw.print(" version=" + libEntry.info.getVersion());
20399                        }
20400                        if (!checkin) {
20401                            pw.print(" -> ");
20402                        }
20403                        if (libEntry.path != null) {
20404                            pw.print(" (jar) ");
20405                            pw.print(libEntry.path);
20406                        } else {
20407                            pw.print(" (apk) ");
20408                            pw.print(libEntry.apk);
20409                        }
20410                        pw.println();
20411                    }
20412                }
20413            }
20414
20415            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20416                if (dumpState.onTitlePrinted())
20417                    pw.println();
20418                if (!checkin) {
20419                    pw.println("Features:");
20420                }
20421
20422                synchronized (mAvailableFeatures) {
20423                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20424                        if (checkin) {
20425                            pw.print("feat,");
20426                            pw.print(feat.name);
20427                            pw.print(",");
20428                            pw.println(feat.version);
20429                        } else {
20430                            pw.print("  ");
20431                            pw.print(feat.name);
20432                            if (feat.version > 0) {
20433                                pw.print(" version=");
20434                                pw.print(feat.version);
20435                            }
20436                            pw.println();
20437                        }
20438                    }
20439                }
20440            }
20441
20442            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20443                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20444                        : "Activity Resolver Table:", "  ", packageName,
20445                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20446                    dumpState.setTitlePrinted(true);
20447                }
20448            }
20449            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20450                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20451                        : "Receiver Resolver Table:", "  ", packageName,
20452                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20453                    dumpState.setTitlePrinted(true);
20454                }
20455            }
20456            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20457                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20458                        : "Service Resolver Table:", "  ", packageName,
20459                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20460                    dumpState.setTitlePrinted(true);
20461                }
20462            }
20463            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20464                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20465                        : "Provider Resolver Table:", "  ", packageName,
20466                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20467                    dumpState.setTitlePrinted(true);
20468                }
20469            }
20470
20471            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20472                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20473                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20474                    int user = mSettings.mPreferredActivities.keyAt(i);
20475                    if (pir.dump(pw,
20476                            dumpState.getTitlePrinted()
20477                                ? "\nPreferred Activities User " + user + ":"
20478                                : "Preferred Activities User " + user + ":", "  ",
20479                            packageName, true, false)) {
20480                        dumpState.setTitlePrinted(true);
20481                    }
20482                }
20483            }
20484
20485            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20486                pw.flush();
20487                FileOutputStream fout = new FileOutputStream(fd);
20488                BufferedOutputStream str = new BufferedOutputStream(fout);
20489                XmlSerializer serializer = new FastXmlSerializer();
20490                try {
20491                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20492                    serializer.startDocument(null, true);
20493                    serializer.setFeature(
20494                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20495                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20496                    serializer.endDocument();
20497                    serializer.flush();
20498                } catch (IllegalArgumentException e) {
20499                    pw.println("Failed writing: " + e);
20500                } catch (IllegalStateException e) {
20501                    pw.println("Failed writing: " + e);
20502                } catch (IOException e) {
20503                    pw.println("Failed writing: " + e);
20504                }
20505            }
20506
20507            if (!checkin
20508                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20509                    && packageName == null) {
20510                pw.println();
20511                int count = mSettings.mPackages.size();
20512                if (count == 0) {
20513                    pw.println("No applications!");
20514                    pw.println();
20515                } else {
20516                    final String prefix = "  ";
20517                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20518                    if (allPackageSettings.size() == 0) {
20519                        pw.println("No domain preferred apps!");
20520                        pw.println();
20521                    } else {
20522                        pw.println("App verification status:");
20523                        pw.println();
20524                        count = 0;
20525                        for (PackageSetting ps : allPackageSettings) {
20526                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20527                            if (ivi == null || ivi.getPackageName() == null) continue;
20528                            pw.println(prefix + "Package: " + ivi.getPackageName());
20529                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20530                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20531                            pw.println();
20532                            count++;
20533                        }
20534                        if (count == 0) {
20535                            pw.println(prefix + "No app verification established.");
20536                            pw.println();
20537                        }
20538                        for (int userId : sUserManager.getUserIds()) {
20539                            pw.println("App linkages for user " + userId + ":");
20540                            pw.println();
20541                            count = 0;
20542                            for (PackageSetting ps : allPackageSettings) {
20543                                final long status = ps.getDomainVerificationStatusForUser(userId);
20544                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20545                                        && !DEBUG_DOMAIN_VERIFICATION) {
20546                                    continue;
20547                                }
20548                                pw.println(prefix + "Package: " + ps.name);
20549                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20550                                String statusStr = IntentFilterVerificationInfo.
20551                                        getStatusStringFromValue(status);
20552                                pw.println(prefix + "Status:  " + statusStr);
20553                                pw.println();
20554                                count++;
20555                            }
20556                            if (count == 0) {
20557                                pw.println(prefix + "No configured app linkages.");
20558                                pw.println();
20559                            }
20560                        }
20561                    }
20562                }
20563            }
20564
20565            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20566                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20567                if (packageName == null && permissionNames == null) {
20568                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20569                        if (iperm == 0) {
20570                            if (dumpState.onTitlePrinted())
20571                                pw.println();
20572                            pw.println("AppOp Permissions:");
20573                        }
20574                        pw.print("  AppOp Permission ");
20575                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20576                        pw.println(":");
20577                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20578                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20579                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20580                        }
20581                    }
20582                }
20583            }
20584
20585            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20586                boolean printedSomething = false;
20587                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20588                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20589                        continue;
20590                    }
20591                    if (!printedSomething) {
20592                        if (dumpState.onTitlePrinted())
20593                            pw.println();
20594                        pw.println("Registered ContentProviders:");
20595                        printedSomething = true;
20596                    }
20597                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20598                    pw.print("    "); pw.println(p.toString());
20599                }
20600                printedSomething = false;
20601                for (Map.Entry<String, PackageParser.Provider> entry :
20602                        mProvidersByAuthority.entrySet()) {
20603                    PackageParser.Provider p = entry.getValue();
20604                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20605                        continue;
20606                    }
20607                    if (!printedSomething) {
20608                        if (dumpState.onTitlePrinted())
20609                            pw.println();
20610                        pw.println("ContentProvider Authorities:");
20611                        printedSomething = true;
20612                    }
20613                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20614                    pw.print("    "); pw.println(p.toString());
20615                    if (p.info != null && p.info.applicationInfo != null) {
20616                        final String appInfo = p.info.applicationInfo.toString();
20617                        pw.print("      applicationInfo="); pw.println(appInfo);
20618                    }
20619                }
20620            }
20621
20622            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20623                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20624            }
20625
20626            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20627                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20628            }
20629
20630            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20631                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20632            }
20633
20634            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20635                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20636            }
20637
20638            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20639                // XXX should handle packageName != null by dumping only install data that
20640                // the given package is involved with.
20641                if (dumpState.onTitlePrinted()) pw.println();
20642                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20643            }
20644
20645            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20646                // XXX should handle packageName != null by dumping only install data that
20647                // the given package is involved with.
20648                if (dumpState.onTitlePrinted()) pw.println();
20649
20650                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20651                ipw.println();
20652                ipw.println("Frozen packages:");
20653                ipw.increaseIndent();
20654                if (mFrozenPackages.size() == 0) {
20655                    ipw.println("(none)");
20656                } else {
20657                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20658                        ipw.println(mFrozenPackages.valueAt(i));
20659                    }
20660                }
20661                ipw.decreaseIndent();
20662            }
20663
20664            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20665                if (dumpState.onTitlePrinted()) pw.println();
20666                dumpDexoptStateLPr(pw, packageName);
20667            }
20668
20669            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20670                if (dumpState.onTitlePrinted()) pw.println();
20671                dumpCompilerStatsLPr(pw, packageName);
20672            }
20673
20674            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20675                if (dumpState.onTitlePrinted()) pw.println();
20676                mSettings.dumpReadMessagesLPr(pw, dumpState);
20677
20678                pw.println();
20679                pw.println("Package warning messages:");
20680                BufferedReader in = null;
20681                String line = null;
20682                try {
20683                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20684                    while ((line = in.readLine()) != null) {
20685                        if (line.contains("ignored: updated version")) continue;
20686                        pw.println(line);
20687                    }
20688                } catch (IOException ignored) {
20689                } finally {
20690                    IoUtils.closeQuietly(in);
20691                }
20692            }
20693
20694            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20695                BufferedReader in = null;
20696                String line = null;
20697                try {
20698                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20699                    while ((line = in.readLine()) != null) {
20700                        if (line.contains("ignored: updated version")) continue;
20701                        pw.print("msg,");
20702                        pw.println(line);
20703                    }
20704                } catch (IOException ignored) {
20705                } finally {
20706                    IoUtils.closeQuietly(in);
20707                }
20708            }
20709        }
20710    }
20711
20712    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20713        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20714        ipw.println();
20715        ipw.println("Dexopt state:");
20716        ipw.increaseIndent();
20717        Collection<PackageParser.Package> packages = null;
20718        if (packageName != null) {
20719            PackageParser.Package targetPackage = mPackages.get(packageName);
20720            if (targetPackage != null) {
20721                packages = Collections.singletonList(targetPackage);
20722            } else {
20723                ipw.println("Unable to find package: " + packageName);
20724                return;
20725            }
20726        } else {
20727            packages = mPackages.values();
20728        }
20729
20730        for (PackageParser.Package pkg : packages) {
20731            ipw.println("[" + pkg.packageName + "]");
20732            ipw.increaseIndent();
20733            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20734            ipw.decreaseIndent();
20735        }
20736    }
20737
20738    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20739        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20740        ipw.println();
20741        ipw.println("Compiler stats:");
20742        ipw.increaseIndent();
20743        Collection<PackageParser.Package> packages = null;
20744        if (packageName != null) {
20745            PackageParser.Package targetPackage = mPackages.get(packageName);
20746            if (targetPackage != null) {
20747                packages = Collections.singletonList(targetPackage);
20748            } else {
20749                ipw.println("Unable to find package: " + packageName);
20750                return;
20751            }
20752        } else {
20753            packages = mPackages.values();
20754        }
20755
20756        for (PackageParser.Package pkg : packages) {
20757            ipw.println("[" + pkg.packageName + "]");
20758            ipw.increaseIndent();
20759
20760            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20761            if (stats == null) {
20762                ipw.println("(No recorded stats)");
20763            } else {
20764                stats.dump(ipw);
20765            }
20766            ipw.decreaseIndent();
20767        }
20768    }
20769
20770    private String dumpDomainString(String packageName) {
20771        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20772                .getList();
20773        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20774
20775        ArraySet<String> result = new ArraySet<>();
20776        if (iviList.size() > 0) {
20777            for (IntentFilterVerificationInfo ivi : iviList) {
20778                for (String host : ivi.getDomains()) {
20779                    result.add(host);
20780                }
20781            }
20782        }
20783        if (filters != null && filters.size() > 0) {
20784            for (IntentFilter filter : filters) {
20785                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20786                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20787                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20788                    result.addAll(filter.getHostsList());
20789                }
20790            }
20791        }
20792
20793        StringBuilder sb = new StringBuilder(result.size() * 16);
20794        for (String domain : result) {
20795            if (sb.length() > 0) sb.append(" ");
20796            sb.append(domain);
20797        }
20798        return sb.toString();
20799    }
20800
20801    // ------- apps on sdcard specific code -------
20802    static final boolean DEBUG_SD_INSTALL = false;
20803
20804    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20805
20806    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20807
20808    private boolean mMediaMounted = false;
20809
20810    static String getEncryptKey() {
20811        try {
20812            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20813                    SD_ENCRYPTION_KEYSTORE_NAME);
20814            if (sdEncKey == null) {
20815                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20816                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20817                if (sdEncKey == null) {
20818                    Slog.e(TAG, "Failed to create encryption keys");
20819                    return null;
20820                }
20821            }
20822            return sdEncKey;
20823        } catch (NoSuchAlgorithmException nsae) {
20824            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20825            return null;
20826        } catch (IOException ioe) {
20827            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20828            return null;
20829        }
20830    }
20831
20832    /*
20833     * Update media status on PackageManager.
20834     */
20835    @Override
20836    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20837        int callingUid = Binder.getCallingUid();
20838        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20839            throw new SecurityException("Media status can only be updated by the system");
20840        }
20841        // reader; this apparently protects mMediaMounted, but should probably
20842        // be a different lock in that case.
20843        synchronized (mPackages) {
20844            Log.i(TAG, "Updating external media status from "
20845                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20846                    + (mediaStatus ? "mounted" : "unmounted"));
20847            if (DEBUG_SD_INSTALL)
20848                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20849                        + ", mMediaMounted=" + mMediaMounted);
20850            if (mediaStatus == mMediaMounted) {
20851                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20852                        : 0, -1);
20853                mHandler.sendMessage(msg);
20854                return;
20855            }
20856            mMediaMounted = mediaStatus;
20857        }
20858        // Queue up an async operation since the package installation may take a
20859        // little while.
20860        mHandler.post(new Runnable() {
20861            public void run() {
20862                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20863            }
20864        });
20865    }
20866
20867    /**
20868     * Called by StorageManagerService when the initial ASECs to scan are available.
20869     * Should block until all the ASEC containers are finished being scanned.
20870     */
20871    public void scanAvailableAsecs() {
20872        updateExternalMediaStatusInner(true, false, false);
20873    }
20874
20875    /*
20876     * Collect information of applications on external media, map them against
20877     * existing containers and update information based on current mount status.
20878     * Please note that we always have to report status if reportStatus has been
20879     * set to true especially when unloading packages.
20880     */
20881    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20882            boolean externalStorage) {
20883        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20884        int[] uidArr = EmptyArray.INT;
20885
20886        final String[] list = PackageHelper.getSecureContainerList();
20887        if (ArrayUtils.isEmpty(list)) {
20888            Log.i(TAG, "No secure containers found");
20889        } else {
20890            // Process list of secure containers and categorize them
20891            // as active or stale based on their package internal state.
20892
20893            // reader
20894            synchronized (mPackages) {
20895                for (String cid : list) {
20896                    // Leave stages untouched for now; installer service owns them
20897                    if (PackageInstallerService.isStageName(cid)) continue;
20898
20899                    if (DEBUG_SD_INSTALL)
20900                        Log.i(TAG, "Processing container " + cid);
20901                    String pkgName = getAsecPackageName(cid);
20902                    if (pkgName == null) {
20903                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20904                        continue;
20905                    }
20906                    if (DEBUG_SD_INSTALL)
20907                        Log.i(TAG, "Looking for pkg : " + pkgName);
20908
20909                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20910                    if (ps == null) {
20911                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20912                        continue;
20913                    }
20914
20915                    /*
20916                     * Skip packages that are not external if we're unmounting
20917                     * external storage.
20918                     */
20919                    if (externalStorage && !isMounted && !isExternal(ps)) {
20920                        continue;
20921                    }
20922
20923                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20924                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20925                    // The package status is changed only if the code path
20926                    // matches between settings and the container id.
20927                    if (ps.codePathString != null
20928                            && ps.codePathString.startsWith(args.getCodePath())) {
20929                        if (DEBUG_SD_INSTALL) {
20930                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20931                                    + " at code path: " + ps.codePathString);
20932                        }
20933
20934                        // We do have a valid package installed on sdcard
20935                        processCids.put(args, ps.codePathString);
20936                        final int uid = ps.appId;
20937                        if (uid != -1) {
20938                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20939                        }
20940                    } else {
20941                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20942                                + ps.codePathString);
20943                    }
20944                }
20945            }
20946
20947            Arrays.sort(uidArr);
20948        }
20949
20950        // Process packages with valid entries.
20951        if (isMounted) {
20952            if (DEBUG_SD_INSTALL)
20953                Log.i(TAG, "Loading packages");
20954            loadMediaPackages(processCids, uidArr, externalStorage);
20955            startCleaningPackages();
20956            mInstallerService.onSecureContainersAvailable();
20957        } else {
20958            if (DEBUG_SD_INSTALL)
20959                Log.i(TAG, "Unloading packages");
20960            unloadMediaPackages(processCids, uidArr, reportStatus);
20961        }
20962    }
20963
20964    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20965            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20966        final int size = infos.size();
20967        final String[] packageNames = new String[size];
20968        final int[] packageUids = new int[size];
20969        for (int i = 0; i < size; i++) {
20970            final ApplicationInfo info = infos.get(i);
20971            packageNames[i] = info.packageName;
20972            packageUids[i] = info.uid;
20973        }
20974        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20975                finishedReceiver);
20976    }
20977
20978    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20979            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20980        sendResourcesChangedBroadcast(mediaStatus, replacing,
20981                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20982    }
20983
20984    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20985            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20986        int size = pkgList.length;
20987        if (size > 0) {
20988            // Send broadcasts here
20989            Bundle extras = new Bundle();
20990            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20991            if (uidArr != null) {
20992                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20993            }
20994            if (replacing) {
20995                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20996            }
20997            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20998                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20999            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21000        }
21001    }
21002
21003   /*
21004     * Look at potentially valid container ids from processCids If package
21005     * information doesn't match the one on record or package scanning fails,
21006     * the cid is added to list of removeCids. We currently don't delete stale
21007     * containers.
21008     */
21009    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21010            boolean externalStorage) {
21011        ArrayList<String> pkgList = new ArrayList<String>();
21012        Set<AsecInstallArgs> keys = processCids.keySet();
21013
21014        for (AsecInstallArgs args : keys) {
21015            String codePath = processCids.get(args);
21016            if (DEBUG_SD_INSTALL)
21017                Log.i(TAG, "Loading container : " + args.cid);
21018            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21019            try {
21020                // Make sure there are no container errors first.
21021                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21022                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21023                            + " when installing from sdcard");
21024                    continue;
21025                }
21026                // Check code path here.
21027                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21028                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21029                            + " does not match one in settings " + codePath);
21030                    continue;
21031                }
21032                // Parse package
21033                int parseFlags = mDefParseFlags;
21034                if (args.isExternalAsec()) {
21035                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21036                }
21037                if (args.isFwdLocked()) {
21038                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21039                }
21040
21041                synchronized (mInstallLock) {
21042                    PackageParser.Package pkg = null;
21043                    try {
21044                        // Sadly we don't know the package name yet to freeze it
21045                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21046                                SCAN_IGNORE_FROZEN, 0, null);
21047                    } catch (PackageManagerException e) {
21048                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21049                    }
21050                    // Scan the package
21051                    if (pkg != null) {
21052                        /*
21053                         * TODO why is the lock being held? doPostInstall is
21054                         * called in other places without the lock. This needs
21055                         * to be straightened out.
21056                         */
21057                        // writer
21058                        synchronized (mPackages) {
21059                            retCode = PackageManager.INSTALL_SUCCEEDED;
21060                            pkgList.add(pkg.packageName);
21061                            // Post process args
21062                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21063                                    pkg.applicationInfo.uid);
21064                        }
21065                    } else {
21066                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21067                    }
21068                }
21069
21070            } finally {
21071                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21072                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21073                }
21074            }
21075        }
21076        // writer
21077        synchronized (mPackages) {
21078            // If the platform SDK has changed since the last time we booted,
21079            // we need to re-grant app permission to catch any new ones that
21080            // appear. This is really a hack, and means that apps can in some
21081            // cases get permissions that the user didn't initially explicitly
21082            // allow... it would be nice to have some better way to handle
21083            // this situation.
21084            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21085                    : mSettings.getInternalVersion();
21086            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21087                    : StorageManager.UUID_PRIVATE_INTERNAL;
21088
21089            int updateFlags = UPDATE_PERMISSIONS_ALL;
21090            if (ver.sdkVersion != mSdkVersion) {
21091                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21092                        + mSdkVersion + "; regranting permissions for external");
21093                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21094            }
21095            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21096
21097            // Yay, everything is now upgraded
21098            ver.forceCurrent();
21099
21100            // can downgrade to reader
21101            // Persist settings
21102            mSettings.writeLPr();
21103        }
21104        // Send a broadcast to let everyone know we are done processing
21105        if (pkgList.size() > 0) {
21106            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21107        }
21108    }
21109
21110   /*
21111     * Utility method to unload a list of specified containers
21112     */
21113    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21114        // Just unmount all valid containers.
21115        for (AsecInstallArgs arg : cidArgs) {
21116            synchronized (mInstallLock) {
21117                arg.doPostDeleteLI(false);
21118           }
21119       }
21120   }
21121
21122    /*
21123     * Unload packages mounted on external media. This involves deleting package
21124     * data from internal structures, sending broadcasts about disabled packages,
21125     * gc'ing to free up references, unmounting all secure containers
21126     * corresponding to packages on external media, and posting a
21127     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21128     * that we always have to post this message if status has been requested no
21129     * matter what.
21130     */
21131    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21132            final boolean reportStatus) {
21133        if (DEBUG_SD_INSTALL)
21134            Log.i(TAG, "unloading media packages");
21135        ArrayList<String> pkgList = new ArrayList<String>();
21136        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21137        final Set<AsecInstallArgs> keys = processCids.keySet();
21138        for (AsecInstallArgs args : keys) {
21139            String pkgName = args.getPackageName();
21140            if (DEBUG_SD_INSTALL)
21141                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21142            // Delete package internally
21143            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21144            synchronized (mInstallLock) {
21145                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21146                final boolean res;
21147                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21148                        "unloadMediaPackages")) {
21149                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21150                            null);
21151                }
21152                if (res) {
21153                    pkgList.add(pkgName);
21154                } else {
21155                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21156                    failedList.add(args);
21157                }
21158            }
21159        }
21160
21161        // reader
21162        synchronized (mPackages) {
21163            // We didn't update the settings after removing each package;
21164            // write them now for all packages.
21165            mSettings.writeLPr();
21166        }
21167
21168        // We have to absolutely send UPDATED_MEDIA_STATUS only
21169        // after confirming that all the receivers processed the ordered
21170        // broadcast when packages get disabled, force a gc to clean things up.
21171        // and unload all the containers.
21172        if (pkgList.size() > 0) {
21173            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21174                    new IIntentReceiver.Stub() {
21175                public void performReceive(Intent intent, int resultCode, String data,
21176                        Bundle extras, boolean ordered, boolean sticky,
21177                        int sendingUser) throws RemoteException {
21178                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21179                            reportStatus ? 1 : 0, 1, keys);
21180                    mHandler.sendMessage(msg);
21181                }
21182            });
21183        } else {
21184            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21185                    keys);
21186            mHandler.sendMessage(msg);
21187        }
21188    }
21189
21190    private void loadPrivatePackages(final VolumeInfo vol) {
21191        mHandler.post(new Runnable() {
21192            @Override
21193            public void run() {
21194                loadPrivatePackagesInner(vol);
21195            }
21196        });
21197    }
21198
21199    private void loadPrivatePackagesInner(VolumeInfo vol) {
21200        final String volumeUuid = vol.fsUuid;
21201        if (TextUtils.isEmpty(volumeUuid)) {
21202            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21203            return;
21204        }
21205
21206        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21207        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21208        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21209
21210        final VersionInfo ver;
21211        final List<PackageSetting> packages;
21212        synchronized (mPackages) {
21213            ver = mSettings.findOrCreateVersion(volumeUuid);
21214            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21215        }
21216
21217        for (PackageSetting ps : packages) {
21218            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21219            synchronized (mInstallLock) {
21220                final PackageParser.Package pkg;
21221                try {
21222                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21223                    loaded.add(pkg.applicationInfo);
21224
21225                } catch (PackageManagerException e) {
21226                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21227                }
21228
21229                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21230                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21231                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21232                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21233                }
21234            }
21235        }
21236
21237        // Reconcile app data for all started/unlocked users
21238        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21239        final UserManager um = mContext.getSystemService(UserManager.class);
21240        UserManagerInternal umInternal = getUserManagerInternal();
21241        for (UserInfo user : um.getUsers()) {
21242            final int flags;
21243            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21244                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21245            } else if (umInternal.isUserRunning(user.id)) {
21246                flags = StorageManager.FLAG_STORAGE_DE;
21247            } else {
21248                continue;
21249            }
21250
21251            try {
21252                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21253                synchronized (mInstallLock) {
21254                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21255                }
21256            } catch (IllegalStateException e) {
21257                // Device was probably ejected, and we'll process that event momentarily
21258                Slog.w(TAG, "Failed to prepare storage: " + e);
21259            }
21260        }
21261
21262        synchronized (mPackages) {
21263            int updateFlags = UPDATE_PERMISSIONS_ALL;
21264            if (ver.sdkVersion != mSdkVersion) {
21265                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21266                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21267                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21268            }
21269            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21270
21271            // Yay, everything is now upgraded
21272            ver.forceCurrent();
21273
21274            mSettings.writeLPr();
21275        }
21276
21277        for (PackageFreezer freezer : freezers) {
21278            freezer.close();
21279        }
21280
21281        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21282        sendResourcesChangedBroadcast(true, false, loaded, null);
21283    }
21284
21285    private void unloadPrivatePackages(final VolumeInfo vol) {
21286        mHandler.post(new Runnable() {
21287            @Override
21288            public void run() {
21289                unloadPrivatePackagesInner(vol);
21290            }
21291        });
21292    }
21293
21294    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21295        final String volumeUuid = vol.fsUuid;
21296        if (TextUtils.isEmpty(volumeUuid)) {
21297            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21298            return;
21299        }
21300
21301        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21302        synchronized (mInstallLock) {
21303        synchronized (mPackages) {
21304            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21305            for (PackageSetting ps : packages) {
21306                if (ps.pkg == null) continue;
21307
21308                final ApplicationInfo info = ps.pkg.applicationInfo;
21309                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21310                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21311
21312                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21313                        "unloadPrivatePackagesInner")) {
21314                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21315                            false, null)) {
21316                        unloaded.add(info);
21317                    } else {
21318                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21319                    }
21320                }
21321
21322                // Try very hard to release any references to this package
21323                // so we don't risk the system server being killed due to
21324                // open FDs
21325                AttributeCache.instance().removePackage(ps.name);
21326            }
21327
21328            mSettings.writeLPr();
21329        }
21330        }
21331
21332        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21333        sendResourcesChangedBroadcast(false, false, unloaded, null);
21334
21335        // Try very hard to release any references to this path so we don't risk
21336        // the system server being killed due to open FDs
21337        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21338
21339        for (int i = 0; i < 3; i++) {
21340            System.gc();
21341            System.runFinalization();
21342        }
21343    }
21344
21345    private void assertPackageKnown(String volumeUuid, String packageName)
21346            throws PackageManagerException {
21347        synchronized (mPackages) {
21348            // Normalize package name to handle renamed packages
21349            packageName = normalizePackageNameLPr(packageName);
21350
21351            final PackageSetting ps = mSettings.mPackages.get(packageName);
21352            if (ps == null) {
21353                throw new PackageManagerException("Package " + packageName + " is unknown");
21354            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21355                throw new PackageManagerException(
21356                        "Package " + packageName + " found on unknown volume " + volumeUuid
21357                                + "; expected volume " + ps.volumeUuid);
21358            }
21359        }
21360    }
21361
21362    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21363            throws PackageManagerException {
21364        synchronized (mPackages) {
21365            // Normalize package name to handle renamed packages
21366            packageName = normalizePackageNameLPr(packageName);
21367
21368            final PackageSetting ps = mSettings.mPackages.get(packageName);
21369            if (ps == null) {
21370                throw new PackageManagerException("Package " + packageName + " is unknown");
21371            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21372                throw new PackageManagerException(
21373                        "Package " + packageName + " found on unknown volume " + volumeUuid
21374                                + "; expected volume " + ps.volumeUuid);
21375            } else if (!ps.getInstalled(userId)) {
21376                throw new PackageManagerException(
21377                        "Package " + packageName + " not installed for user " + userId);
21378            }
21379        }
21380    }
21381
21382    private List<String> collectAbsoluteCodePaths() {
21383        synchronized (mPackages) {
21384            List<String> codePaths = new ArrayList<>();
21385            final int packageCount = mSettings.mPackages.size();
21386            for (int i = 0; i < packageCount; i++) {
21387                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21388                codePaths.add(ps.codePath.getAbsolutePath());
21389            }
21390            return codePaths;
21391        }
21392    }
21393
21394    /**
21395     * Examine all apps present on given mounted volume, and destroy apps that
21396     * aren't expected, either due to uninstallation or reinstallation on
21397     * another volume.
21398     */
21399    private void reconcileApps(String volumeUuid) {
21400        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21401        List<File> filesToDelete = null;
21402
21403        final File[] files = FileUtils.listFilesOrEmpty(
21404                Environment.getDataAppDirectory(volumeUuid));
21405        for (File file : files) {
21406            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21407                    && !PackageInstallerService.isStageName(file.getName());
21408            if (!isPackage) {
21409                // Ignore entries which are not packages
21410                continue;
21411            }
21412
21413            String absolutePath = file.getAbsolutePath();
21414
21415            boolean pathValid = false;
21416            final int absoluteCodePathCount = absoluteCodePaths.size();
21417            for (int i = 0; i < absoluteCodePathCount; i++) {
21418                String absoluteCodePath = absoluteCodePaths.get(i);
21419                if (absolutePath.startsWith(absoluteCodePath)) {
21420                    pathValid = true;
21421                    break;
21422                }
21423            }
21424
21425            if (!pathValid) {
21426                if (filesToDelete == null) {
21427                    filesToDelete = new ArrayList<>();
21428                }
21429                filesToDelete.add(file);
21430            }
21431        }
21432
21433        if (filesToDelete != null) {
21434            final int fileToDeleteCount = filesToDelete.size();
21435            for (int i = 0; i < fileToDeleteCount; i++) {
21436                File fileToDelete = filesToDelete.get(i);
21437                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21438                synchronized (mInstallLock) {
21439                    removeCodePathLI(fileToDelete);
21440                }
21441            }
21442        }
21443    }
21444
21445    /**
21446     * Reconcile all app data for the given user.
21447     * <p>
21448     * Verifies that directories exist and that ownership and labeling is
21449     * correct for all installed apps on all mounted volumes.
21450     */
21451    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21452        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21453        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21454            final String volumeUuid = vol.getFsUuid();
21455            synchronized (mInstallLock) {
21456                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21457            }
21458        }
21459    }
21460
21461    /**
21462     * Reconcile all app data on given mounted volume.
21463     * <p>
21464     * Destroys app data that isn't expected, either due to uninstallation or
21465     * reinstallation on another volume.
21466     * <p>
21467     * Verifies that directories exist and that ownership and labeling is
21468     * correct for all installed apps.
21469     */
21470    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21471            boolean migrateAppData) {
21472        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21473                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21474
21475        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21476        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21477
21478        // First look for stale data that doesn't belong, and check if things
21479        // have changed since we did our last restorecon
21480        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21481            if (StorageManager.isFileEncryptedNativeOrEmulated()
21482                    && !StorageManager.isUserKeyUnlocked(userId)) {
21483                throw new RuntimeException(
21484                        "Yikes, someone asked us to reconcile CE storage while " + userId
21485                                + " was still locked; this would have caused massive data loss!");
21486            }
21487
21488            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21489            for (File file : files) {
21490                final String packageName = file.getName();
21491                try {
21492                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21493                } catch (PackageManagerException e) {
21494                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21495                    try {
21496                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21497                                StorageManager.FLAG_STORAGE_CE, 0);
21498                    } catch (InstallerException e2) {
21499                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21500                    }
21501                }
21502            }
21503        }
21504        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21505            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21506            for (File file : files) {
21507                final String packageName = file.getName();
21508                try {
21509                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21510                } catch (PackageManagerException e) {
21511                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21512                    try {
21513                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21514                                StorageManager.FLAG_STORAGE_DE, 0);
21515                    } catch (InstallerException e2) {
21516                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21517                    }
21518                }
21519            }
21520        }
21521
21522        // Ensure that data directories are ready to roll for all packages
21523        // installed for this volume and user
21524        final List<PackageSetting> packages;
21525        synchronized (mPackages) {
21526            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21527        }
21528        int preparedCount = 0;
21529        for (PackageSetting ps : packages) {
21530            final String packageName = ps.name;
21531            if (ps.pkg == null) {
21532                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21533                // TODO: might be due to legacy ASEC apps; we should circle back
21534                // and reconcile again once they're scanned
21535                continue;
21536            }
21537
21538            if (ps.getInstalled(userId)) {
21539                prepareAppDataLIF(ps.pkg, userId, flags);
21540
21541                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21542                    // We may have just shuffled around app data directories, so
21543                    // prepare them one more time
21544                    prepareAppDataLIF(ps.pkg, userId, flags);
21545                }
21546
21547                preparedCount++;
21548            }
21549        }
21550
21551        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21552    }
21553
21554    /**
21555     * Prepare app data for the given app just after it was installed or
21556     * upgraded. This method carefully only touches users that it's installed
21557     * for, and it forces a restorecon to handle any seinfo changes.
21558     * <p>
21559     * Verifies that directories exist and that ownership and labeling is
21560     * correct for all installed apps. If there is an ownership mismatch, it
21561     * will try recovering system apps by wiping data; third-party app data is
21562     * left intact.
21563     * <p>
21564     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21565     */
21566    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21567        final PackageSetting ps;
21568        synchronized (mPackages) {
21569            ps = mSettings.mPackages.get(pkg.packageName);
21570            mSettings.writeKernelMappingLPr(ps);
21571        }
21572
21573        final UserManager um = mContext.getSystemService(UserManager.class);
21574        UserManagerInternal umInternal = getUserManagerInternal();
21575        for (UserInfo user : um.getUsers()) {
21576            final int flags;
21577            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21578                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21579            } else if (umInternal.isUserRunning(user.id)) {
21580                flags = StorageManager.FLAG_STORAGE_DE;
21581            } else {
21582                continue;
21583            }
21584
21585            if (ps.getInstalled(user.id)) {
21586                // TODO: when user data is locked, mark that we're still dirty
21587                prepareAppDataLIF(pkg, user.id, flags);
21588            }
21589        }
21590    }
21591
21592    /**
21593     * Prepare app data for the given app.
21594     * <p>
21595     * Verifies that directories exist and that ownership and labeling is
21596     * correct for all installed apps. If there is an ownership mismatch, this
21597     * will try recovering system apps by wiping data; third-party app data is
21598     * left intact.
21599     */
21600    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21601        if (pkg == null) {
21602            Slog.wtf(TAG, "Package was null!", new Throwable());
21603            return;
21604        }
21605        prepareAppDataLeafLIF(pkg, userId, flags);
21606        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21607        for (int i = 0; i < childCount; i++) {
21608            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21609        }
21610    }
21611
21612    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21613        if (DEBUG_APP_DATA) {
21614            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21615                    + Integer.toHexString(flags));
21616        }
21617
21618        final String volumeUuid = pkg.volumeUuid;
21619        final String packageName = pkg.packageName;
21620        final ApplicationInfo app = pkg.applicationInfo;
21621        final int appId = UserHandle.getAppId(app.uid);
21622
21623        Preconditions.checkNotNull(app.seinfo);
21624
21625        long ceDataInode = -1;
21626        try {
21627            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21628                    appId, app.seinfo, app.targetSdkVersion);
21629        } catch (InstallerException e) {
21630            if (app.isSystemApp()) {
21631                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21632                        + ", but trying to recover: " + e);
21633                destroyAppDataLeafLIF(pkg, userId, flags);
21634                try {
21635                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21636                            appId, app.seinfo, app.targetSdkVersion);
21637                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21638                } catch (InstallerException e2) {
21639                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21640                }
21641            } else {
21642                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21643            }
21644        }
21645
21646        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21647            // TODO: mark this structure as dirty so we persist it!
21648            synchronized (mPackages) {
21649                final PackageSetting ps = mSettings.mPackages.get(packageName);
21650                if (ps != null) {
21651                    ps.setCeDataInode(ceDataInode, userId);
21652                }
21653            }
21654        }
21655
21656        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21657    }
21658
21659    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21660        if (pkg == null) {
21661            Slog.wtf(TAG, "Package was null!", new Throwable());
21662            return;
21663        }
21664        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21665        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21666        for (int i = 0; i < childCount; i++) {
21667            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21668        }
21669    }
21670
21671    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21672        final String volumeUuid = pkg.volumeUuid;
21673        final String packageName = pkg.packageName;
21674        final ApplicationInfo app = pkg.applicationInfo;
21675
21676        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21677            // Create a native library symlink only if we have native libraries
21678            // and if the native libraries are 32 bit libraries. We do not provide
21679            // this symlink for 64 bit libraries.
21680            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21681                final String nativeLibPath = app.nativeLibraryDir;
21682                try {
21683                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21684                            nativeLibPath, userId);
21685                } catch (InstallerException e) {
21686                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21687                }
21688            }
21689        }
21690    }
21691
21692    /**
21693     * For system apps on non-FBE devices, this method migrates any existing
21694     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21695     * requested by the app.
21696     */
21697    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21698        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21699                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21700            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21701                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21702            try {
21703                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21704                        storageTarget);
21705            } catch (InstallerException e) {
21706                logCriticalInfo(Log.WARN,
21707                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21708            }
21709            return true;
21710        } else {
21711            return false;
21712        }
21713    }
21714
21715    public PackageFreezer freezePackage(String packageName, String killReason) {
21716        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21717    }
21718
21719    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21720        return new PackageFreezer(packageName, userId, killReason);
21721    }
21722
21723    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21724            String killReason) {
21725        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21726    }
21727
21728    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21729            String killReason) {
21730        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21731            return new PackageFreezer();
21732        } else {
21733            return freezePackage(packageName, userId, killReason);
21734        }
21735    }
21736
21737    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21738            String killReason) {
21739        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21740    }
21741
21742    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21743            String killReason) {
21744        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21745            return new PackageFreezer();
21746        } else {
21747            return freezePackage(packageName, userId, killReason);
21748        }
21749    }
21750
21751    /**
21752     * Class that freezes and kills the given package upon creation, and
21753     * unfreezes it upon closing. This is typically used when doing surgery on
21754     * app code/data to prevent the app from running while you're working.
21755     */
21756    private class PackageFreezer implements AutoCloseable {
21757        private final String mPackageName;
21758        private final PackageFreezer[] mChildren;
21759
21760        private final boolean mWeFroze;
21761
21762        private final AtomicBoolean mClosed = new AtomicBoolean();
21763        private final CloseGuard mCloseGuard = CloseGuard.get();
21764
21765        /**
21766         * Create and return a stub freezer that doesn't actually do anything,
21767         * typically used when someone requested
21768         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21769         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21770         */
21771        public PackageFreezer() {
21772            mPackageName = null;
21773            mChildren = null;
21774            mWeFroze = false;
21775            mCloseGuard.open("close");
21776        }
21777
21778        public PackageFreezer(String packageName, int userId, String killReason) {
21779            synchronized (mPackages) {
21780                mPackageName = packageName;
21781                mWeFroze = mFrozenPackages.add(mPackageName);
21782
21783                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21784                if (ps != null) {
21785                    killApplication(ps.name, ps.appId, userId, killReason);
21786                }
21787
21788                final PackageParser.Package p = mPackages.get(packageName);
21789                if (p != null && p.childPackages != null) {
21790                    final int N = p.childPackages.size();
21791                    mChildren = new PackageFreezer[N];
21792                    for (int i = 0; i < N; i++) {
21793                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21794                                userId, killReason);
21795                    }
21796                } else {
21797                    mChildren = null;
21798                }
21799            }
21800            mCloseGuard.open("close");
21801        }
21802
21803        @Override
21804        protected void finalize() throws Throwable {
21805            try {
21806                mCloseGuard.warnIfOpen();
21807                close();
21808            } finally {
21809                super.finalize();
21810            }
21811        }
21812
21813        @Override
21814        public void close() {
21815            mCloseGuard.close();
21816            if (mClosed.compareAndSet(false, true)) {
21817                synchronized (mPackages) {
21818                    if (mWeFroze) {
21819                        mFrozenPackages.remove(mPackageName);
21820                    }
21821
21822                    if (mChildren != null) {
21823                        for (PackageFreezer freezer : mChildren) {
21824                            freezer.close();
21825                        }
21826                    }
21827                }
21828            }
21829        }
21830    }
21831
21832    /**
21833     * Verify that given package is currently frozen.
21834     */
21835    private void checkPackageFrozen(String packageName) {
21836        synchronized (mPackages) {
21837            if (!mFrozenPackages.contains(packageName)) {
21838                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21839            }
21840        }
21841    }
21842
21843    @Override
21844    public int movePackage(final String packageName, final String volumeUuid) {
21845        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21846
21847        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21848        final int moveId = mNextMoveId.getAndIncrement();
21849        mHandler.post(new Runnable() {
21850            @Override
21851            public void run() {
21852                try {
21853                    movePackageInternal(packageName, volumeUuid, moveId, user);
21854                } catch (PackageManagerException e) {
21855                    Slog.w(TAG, "Failed to move " + packageName, e);
21856                    mMoveCallbacks.notifyStatusChanged(moveId,
21857                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21858                }
21859            }
21860        });
21861        return moveId;
21862    }
21863
21864    private void movePackageInternal(final String packageName, final String volumeUuid,
21865            final int moveId, UserHandle user) throws PackageManagerException {
21866        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21867        final PackageManager pm = mContext.getPackageManager();
21868
21869        final boolean currentAsec;
21870        final String currentVolumeUuid;
21871        final File codeFile;
21872        final String installerPackageName;
21873        final String packageAbiOverride;
21874        final int appId;
21875        final String seinfo;
21876        final String label;
21877        final int targetSdkVersion;
21878        final PackageFreezer freezer;
21879        final int[] installedUserIds;
21880
21881        // reader
21882        synchronized (mPackages) {
21883            final PackageParser.Package pkg = mPackages.get(packageName);
21884            final PackageSetting ps = mSettings.mPackages.get(packageName);
21885            if (pkg == null || ps == null) {
21886                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21887            }
21888
21889            if (pkg.applicationInfo.isSystemApp()) {
21890                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21891                        "Cannot move system application");
21892            }
21893
21894            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21895            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21896                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21897            if (isInternalStorage && !allow3rdPartyOnInternal) {
21898                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21899                        "3rd party apps are not allowed on internal storage");
21900            }
21901
21902            if (pkg.applicationInfo.isExternalAsec()) {
21903                currentAsec = true;
21904                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21905            } else if (pkg.applicationInfo.isForwardLocked()) {
21906                currentAsec = true;
21907                currentVolumeUuid = "forward_locked";
21908            } else {
21909                currentAsec = false;
21910                currentVolumeUuid = ps.volumeUuid;
21911
21912                final File probe = new File(pkg.codePath);
21913                final File probeOat = new File(probe, "oat");
21914                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21915                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21916                            "Move only supported for modern cluster style installs");
21917                }
21918            }
21919
21920            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21921                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21922                        "Package already moved to " + volumeUuid);
21923            }
21924            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21925                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21926                        "Device admin cannot be moved");
21927            }
21928
21929            if (mFrozenPackages.contains(packageName)) {
21930                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21931                        "Failed to move already frozen package");
21932            }
21933
21934            codeFile = new File(pkg.codePath);
21935            installerPackageName = ps.installerPackageName;
21936            packageAbiOverride = ps.cpuAbiOverrideString;
21937            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21938            seinfo = pkg.applicationInfo.seinfo;
21939            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21940            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21941            freezer = freezePackage(packageName, "movePackageInternal");
21942            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21943        }
21944
21945        final Bundle extras = new Bundle();
21946        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21947        extras.putString(Intent.EXTRA_TITLE, label);
21948        mMoveCallbacks.notifyCreated(moveId, extras);
21949
21950        int installFlags;
21951        final boolean moveCompleteApp;
21952        final File measurePath;
21953
21954        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21955            installFlags = INSTALL_INTERNAL;
21956            moveCompleteApp = !currentAsec;
21957            measurePath = Environment.getDataAppDirectory(volumeUuid);
21958        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21959            installFlags = INSTALL_EXTERNAL;
21960            moveCompleteApp = false;
21961            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21962        } else {
21963            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21964            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21965                    || !volume.isMountedWritable()) {
21966                freezer.close();
21967                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21968                        "Move location not mounted private volume");
21969            }
21970
21971            Preconditions.checkState(!currentAsec);
21972
21973            installFlags = INSTALL_INTERNAL;
21974            moveCompleteApp = true;
21975            measurePath = Environment.getDataAppDirectory(volumeUuid);
21976        }
21977
21978        final PackageStats stats = new PackageStats(null, -1);
21979        synchronized (mInstaller) {
21980            for (int userId : installedUserIds) {
21981                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21982                    freezer.close();
21983                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21984                            "Failed to measure package size");
21985                }
21986            }
21987        }
21988
21989        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21990                + stats.dataSize);
21991
21992        final long startFreeBytes = measurePath.getFreeSpace();
21993        final long sizeBytes;
21994        if (moveCompleteApp) {
21995            sizeBytes = stats.codeSize + stats.dataSize;
21996        } else {
21997            sizeBytes = stats.codeSize;
21998        }
21999
22000        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22001            freezer.close();
22002            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22003                    "Not enough free space to move");
22004        }
22005
22006        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22007
22008        final CountDownLatch installedLatch = new CountDownLatch(1);
22009        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22010            @Override
22011            public void onUserActionRequired(Intent intent) throws RemoteException {
22012                throw new IllegalStateException();
22013            }
22014
22015            @Override
22016            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22017                    Bundle extras) throws RemoteException {
22018                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22019                        + PackageManager.installStatusToString(returnCode, msg));
22020
22021                installedLatch.countDown();
22022                freezer.close();
22023
22024                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22025                switch (status) {
22026                    case PackageInstaller.STATUS_SUCCESS:
22027                        mMoveCallbacks.notifyStatusChanged(moveId,
22028                                PackageManager.MOVE_SUCCEEDED);
22029                        break;
22030                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22031                        mMoveCallbacks.notifyStatusChanged(moveId,
22032                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22033                        break;
22034                    default:
22035                        mMoveCallbacks.notifyStatusChanged(moveId,
22036                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22037                        break;
22038                }
22039            }
22040        };
22041
22042        final MoveInfo move;
22043        if (moveCompleteApp) {
22044            // Kick off a thread to report progress estimates
22045            new Thread() {
22046                @Override
22047                public void run() {
22048                    while (true) {
22049                        try {
22050                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22051                                break;
22052                            }
22053                        } catch (InterruptedException ignored) {
22054                        }
22055
22056                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22057                        final int progress = 10 + (int) MathUtils.constrain(
22058                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22059                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22060                    }
22061                }
22062            }.start();
22063
22064            final String dataAppName = codeFile.getName();
22065            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22066                    dataAppName, appId, seinfo, targetSdkVersion);
22067        } else {
22068            move = null;
22069        }
22070
22071        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22072
22073        final Message msg = mHandler.obtainMessage(INIT_COPY);
22074        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22075        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22076                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22077                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22078                PackageManager.INSTALL_REASON_UNKNOWN);
22079        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22080        msg.obj = params;
22081
22082        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22083                System.identityHashCode(msg.obj));
22084        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22085                System.identityHashCode(msg.obj));
22086
22087        mHandler.sendMessage(msg);
22088    }
22089
22090    @Override
22091    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22092        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22093
22094        final int realMoveId = mNextMoveId.getAndIncrement();
22095        final Bundle extras = new Bundle();
22096        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22097        mMoveCallbacks.notifyCreated(realMoveId, extras);
22098
22099        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22100            @Override
22101            public void onCreated(int moveId, Bundle extras) {
22102                // Ignored
22103            }
22104
22105            @Override
22106            public void onStatusChanged(int moveId, int status, long estMillis) {
22107                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22108            }
22109        };
22110
22111        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22112        storage.setPrimaryStorageUuid(volumeUuid, callback);
22113        return realMoveId;
22114    }
22115
22116    @Override
22117    public int getMoveStatus(int moveId) {
22118        mContext.enforceCallingOrSelfPermission(
22119                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22120        return mMoveCallbacks.mLastStatus.get(moveId);
22121    }
22122
22123    @Override
22124    public void registerMoveCallback(IPackageMoveObserver callback) {
22125        mContext.enforceCallingOrSelfPermission(
22126                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22127        mMoveCallbacks.register(callback);
22128    }
22129
22130    @Override
22131    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22132        mContext.enforceCallingOrSelfPermission(
22133                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22134        mMoveCallbacks.unregister(callback);
22135    }
22136
22137    @Override
22138    public boolean setInstallLocation(int loc) {
22139        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22140                null);
22141        if (getInstallLocation() == loc) {
22142            return true;
22143        }
22144        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22145                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22146            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22147                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22148            return true;
22149        }
22150        return false;
22151   }
22152
22153    @Override
22154    public int getInstallLocation() {
22155        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22156                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22157                PackageHelper.APP_INSTALL_AUTO);
22158    }
22159
22160    /** Called by UserManagerService */
22161    void cleanUpUser(UserManagerService userManager, int userHandle) {
22162        synchronized (mPackages) {
22163            mDirtyUsers.remove(userHandle);
22164            mUserNeedsBadging.delete(userHandle);
22165            mSettings.removeUserLPw(userHandle);
22166            mPendingBroadcasts.remove(userHandle);
22167            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22168            removeUnusedPackagesLPw(userManager, userHandle);
22169        }
22170    }
22171
22172    /**
22173     * We're removing userHandle and would like to remove any downloaded packages
22174     * that are no longer in use by any other user.
22175     * @param userHandle the user being removed
22176     */
22177    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22178        final boolean DEBUG_CLEAN_APKS = false;
22179        int [] users = userManager.getUserIds();
22180        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22181        while (psit.hasNext()) {
22182            PackageSetting ps = psit.next();
22183            if (ps.pkg == null) {
22184                continue;
22185            }
22186            final String packageName = ps.pkg.packageName;
22187            // Skip over if system app
22188            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22189                continue;
22190            }
22191            if (DEBUG_CLEAN_APKS) {
22192                Slog.i(TAG, "Checking package " + packageName);
22193            }
22194            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22195            if (keep) {
22196                if (DEBUG_CLEAN_APKS) {
22197                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22198                }
22199            } else {
22200                for (int i = 0; i < users.length; i++) {
22201                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22202                        keep = true;
22203                        if (DEBUG_CLEAN_APKS) {
22204                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22205                                    + users[i]);
22206                        }
22207                        break;
22208                    }
22209                }
22210            }
22211            if (!keep) {
22212                if (DEBUG_CLEAN_APKS) {
22213                    Slog.i(TAG, "  Removing package " + packageName);
22214                }
22215                mHandler.post(new Runnable() {
22216                    public void run() {
22217                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22218                                userHandle, 0);
22219                    } //end run
22220                });
22221            }
22222        }
22223    }
22224
22225    /** Called by UserManagerService */
22226    void createNewUser(int userId, String[] disallowedPackages) {
22227        synchronized (mInstallLock) {
22228            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22229        }
22230        synchronized (mPackages) {
22231            scheduleWritePackageRestrictionsLocked(userId);
22232            scheduleWritePackageListLocked(userId);
22233            applyFactoryDefaultBrowserLPw(userId);
22234            primeDomainVerificationsLPw(userId);
22235        }
22236    }
22237
22238    void onNewUserCreated(final int userId) {
22239        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22240        // If permission review for legacy apps is required, we represent
22241        // dagerous permissions for such apps as always granted runtime
22242        // permissions to keep per user flag state whether review is needed.
22243        // Hence, if a new user is added we have to propagate dangerous
22244        // permission grants for these legacy apps.
22245        if (mPermissionReviewRequired) {
22246            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22247                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22248        }
22249    }
22250
22251    @Override
22252    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22253        mContext.enforceCallingOrSelfPermission(
22254                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22255                "Only package verification agents can read the verifier device identity");
22256
22257        synchronized (mPackages) {
22258            return mSettings.getVerifierDeviceIdentityLPw();
22259        }
22260    }
22261
22262    @Override
22263    public void setPermissionEnforced(String permission, boolean enforced) {
22264        // TODO: Now that we no longer change GID for storage, this should to away.
22265        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22266                "setPermissionEnforced");
22267        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22268            synchronized (mPackages) {
22269                if (mSettings.mReadExternalStorageEnforced == null
22270                        || mSettings.mReadExternalStorageEnforced != enforced) {
22271                    mSettings.mReadExternalStorageEnforced = enforced;
22272                    mSettings.writeLPr();
22273                }
22274            }
22275            // kill any non-foreground processes so we restart them and
22276            // grant/revoke the GID.
22277            final IActivityManager am = ActivityManager.getService();
22278            if (am != null) {
22279                final long token = Binder.clearCallingIdentity();
22280                try {
22281                    am.killProcessesBelowForeground("setPermissionEnforcement");
22282                } catch (RemoteException e) {
22283                } finally {
22284                    Binder.restoreCallingIdentity(token);
22285                }
22286            }
22287        } else {
22288            throw new IllegalArgumentException("No selective enforcement for " + permission);
22289        }
22290    }
22291
22292    @Override
22293    @Deprecated
22294    public boolean isPermissionEnforced(String permission) {
22295        return true;
22296    }
22297
22298    @Override
22299    public boolean isStorageLow() {
22300        final long token = Binder.clearCallingIdentity();
22301        try {
22302            final DeviceStorageMonitorInternal
22303                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22304            if (dsm != null) {
22305                return dsm.isMemoryLow();
22306            } else {
22307                return false;
22308            }
22309        } finally {
22310            Binder.restoreCallingIdentity(token);
22311        }
22312    }
22313
22314    @Override
22315    public IPackageInstaller getPackageInstaller() {
22316        return mInstallerService;
22317    }
22318
22319    private boolean userNeedsBadging(int userId) {
22320        int index = mUserNeedsBadging.indexOfKey(userId);
22321        if (index < 0) {
22322            final UserInfo userInfo;
22323            final long token = Binder.clearCallingIdentity();
22324            try {
22325                userInfo = sUserManager.getUserInfo(userId);
22326            } finally {
22327                Binder.restoreCallingIdentity(token);
22328            }
22329            final boolean b;
22330            if (userInfo != null && userInfo.isManagedProfile()) {
22331                b = true;
22332            } else {
22333                b = false;
22334            }
22335            mUserNeedsBadging.put(userId, b);
22336            return b;
22337        }
22338        return mUserNeedsBadging.valueAt(index);
22339    }
22340
22341    @Override
22342    public KeySet getKeySetByAlias(String packageName, String alias) {
22343        if (packageName == null || alias == null) {
22344            return null;
22345        }
22346        synchronized(mPackages) {
22347            final PackageParser.Package pkg = mPackages.get(packageName);
22348            if (pkg == null) {
22349                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22350                throw new IllegalArgumentException("Unknown package: " + packageName);
22351            }
22352            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22353            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22354        }
22355    }
22356
22357    @Override
22358    public KeySet getSigningKeySet(String packageName) {
22359        if (packageName == null) {
22360            return null;
22361        }
22362        synchronized(mPackages) {
22363            final PackageParser.Package pkg = mPackages.get(packageName);
22364            if (pkg == null) {
22365                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22366                throw new IllegalArgumentException("Unknown package: " + packageName);
22367            }
22368            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22369                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22370                throw new SecurityException("May not access signing KeySet of other apps.");
22371            }
22372            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22373            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22374        }
22375    }
22376
22377    @Override
22378    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22379        if (packageName == null || ks == null) {
22380            return false;
22381        }
22382        synchronized(mPackages) {
22383            final PackageParser.Package pkg = mPackages.get(packageName);
22384            if (pkg == null) {
22385                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22386                throw new IllegalArgumentException("Unknown package: " + packageName);
22387            }
22388            IBinder ksh = ks.getToken();
22389            if (ksh instanceof KeySetHandle) {
22390                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22391                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22392            }
22393            return false;
22394        }
22395    }
22396
22397    @Override
22398    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22399        if (packageName == null || ks == null) {
22400            return false;
22401        }
22402        synchronized(mPackages) {
22403            final PackageParser.Package pkg = mPackages.get(packageName);
22404            if (pkg == null) {
22405                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22406                throw new IllegalArgumentException("Unknown package: " + packageName);
22407            }
22408            IBinder ksh = ks.getToken();
22409            if (ksh instanceof KeySetHandle) {
22410                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22411                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22412            }
22413            return false;
22414        }
22415    }
22416
22417    private void deletePackageIfUnusedLPr(final String packageName) {
22418        PackageSetting ps = mSettings.mPackages.get(packageName);
22419        if (ps == null) {
22420            return;
22421        }
22422        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22423            // TODO Implement atomic delete if package is unused
22424            // It is currently possible that the package will be deleted even if it is installed
22425            // after this method returns.
22426            mHandler.post(new Runnable() {
22427                public void run() {
22428                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22429                            0, PackageManager.DELETE_ALL_USERS);
22430                }
22431            });
22432        }
22433    }
22434
22435    /**
22436     * Check and throw if the given before/after packages would be considered a
22437     * downgrade.
22438     */
22439    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22440            throws PackageManagerException {
22441        if (after.versionCode < before.mVersionCode) {
22442            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22443                    "Update version code " + after.versionCode + " is older than current "
22444                    + before.mVersionCode);
22445        } else if (after.versionCode == before.mVersionCode) {
22446            if (after.baseRevisionCode < before.baseRevisionCode) {
22447                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22448                        "Update base revision code " + after.baseRevisionCode
22449                        + " is older than current " + before.baseRevisionCode);
22450            }
22451
22452            if (!ArrayUtils.isEmpty(after.splitNames)) {
22453                for (int i = 0; i < after.splitNames.length; i++) {
22454                    final String splitName = after.splitNames[i];
22455                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22456                    if (j != -1) {
22457                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22458                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22459                                    "Update split " + splitName + " revision code "
22460                                    + after.splitRevisionCodes[i] + " is older than current "
22461                                    + before.splitRevisionCodes[j]);
22462                        }
22463                    }
22464                }
22465            }
22466        }
22467    }
22468
22469    private static class MoveCallbacks extends Handler {
22470        private static final int MSG_CREATED = 1;
22471        private static final int MSG_STATUS_CHANGED = 2;
22472
22473        private final RemoteCallbackList<IPackageMoveObserver>
22474                mCallbacks = new RemoteCallbackList<>();
22475
22476        private final SparseIntArray mLastStatus = new SparseIntArray();
22477
22478        public MoveCallbacks(Looper looper) {
22479            super(looper);
22480        }
22481
22482        public void register(IPackageMoveObserver callback) {
22483            mCallbacks.register(callback);
22484        }
22485
22486        public void unregister(IPackageMoveObserver callback) {
22487            mCallbacks.unregister(callback);
22488        }
22489
22490        @Override
22491        public void handleMessage(Message msg) {
22492            final SomeArgs args = (SomeArgs) msg.obj;
22493            final int n = mCallbacks.beginBroadcast();
22494            for (int i = 0; i < n; i++) {
22495                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22496                try {
22497                    invokeCallback(callback, msg.what, args);
22498                } catch (RemoteException ignored) {
22499                }
22500            }
22501            mCallbacks.finishBroadcast();
22502            args.recycle();
22503        }
22504
22505        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22506                throws RemoteException {
22507            switch (what) {
22508                case MSG_CREATED: {
22509                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22510                    break;
22511                }
22512                case MSG_STATUS_CHANGED: {
22513                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22514                    break;
22515                }
22516            }
22517        }
22518
22519        private void notifyCreated(int moveId, Bundle extras) {
22520            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22521
22522            final SomeArgs args = SomeArgs.obtain();
22523            args.argi1 = moveId;
22524            args.arg2 = extras;
22525            obtainMessage(MSG_CREATED, args).sendToTarget();
22526        }
22527
22528        private void notifyStatusChanged(int moveId, int status) {
22529            notifyStatusChanged(moveId, status, -1);
22530        }
22531
22532        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22533            Slog.v(TAG, "Move " + moveId + " status " + status);
22534
22535            final SomeArgs args = SomeArgs.obtain();
22536            args.argi1 = moveId;
22537            args.argi2 = status;
22538            args.arg3 = estMillis;
22539            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22540
22541            synchronized (mLastStatus) {
22542                mLastStatus.put(moveId, status);
22543            }
22544        }
22545    }
22546
22547    private final static class OnPermissionChangeListeners extends Handler {
22548        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22549
22550        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22551                new RemoteCallbackList<>();
22552
22553        public OnPermissionChangeListeners(Looper looper) {
22554            super(looper);
22555        }
22556
22557        @Override
22558        public void handleMessage(Message msg) {
22559            switch (msg.what) {
22560                case MSG_ON_PERMISSIONS_CHANGED: {
22561                    final int uid = msg.arg1;
22562                    handleOnPermissionsChanged(uid);
22563                } break;
22564            }
22565        }
22566
22567        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22568            mPermissionListeners.register(listener);
22569
22570        }
22571
22572        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22573            mPermissionListeners.unregister(listener);
22574        }
22575
22576        public void onPermissionsChanged(int uid) {
22577            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22578                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22579            }
22580        }
22581
22582        private void handleOnPermissionsChanged(int uid) {
22583            final int count = mPermissionListeners.beginBroadcast();
22584            try {
22585                for (int i = 0; i < count; i++) {
22586                    IOnPermissionsChangeListener callback = mPermissionListeners
22587                            .getBroadcastItem(i);
22588                    try {
22589                        callback.onPermissionsChanged(uid);
22590                    } catch (RemoteException e) {
22591                        Log.e(TAG, "Permission listener is dead", e);
22592                    }
22593                }
22594            } finally {
22595                mPermissionListeners.finishBroadcast();
22596            }
22597        }
22598    }
22599
22600    private class PackageManagerInternalImpl extends PackageManagerInternal {
22601        @Override
22602        public void setLocationPackagesProvider(PackagesProvider provider) {
22603            synchronized (mPackages) {
22604                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22605            }
22606        }
22607
22608        @Override
22609        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22610            synchronized (mPackages) {
22611                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22612            }
22613        }
22614
22615        @Override
22616        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22617            synchronized (mPackages) {
22618                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22619            }
22620        }
22621
22622        @Override
22623        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22624            synchronized (mPackages) {
22625                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22626            }
22627        }
22628
22629        @Override
22630        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22631            synchronized (mPackages) {
22632                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22633            }
22634        }
22635
22636        @Override
22637        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22638            synchronized (mPackages) {
22639                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22640            }
22641        }
22642
22643        @Override
22644        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22645            synchronized (mPackages) {
22646                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22647                        packageName, userId);
22648            }
22649        }
22650
22651        @Override
22652        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22653            synchronized (mPackages) {
22654                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22655                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22656                        packageName, userId);
22657            }
22658        }
22659
22660        @Override
22661        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22662            synchronized (mPackages) {
22663                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22664                        packageName, userId);
22665            }
22666        }
22667
22668        @Override
22669        public void setKeepUninstalledPackages(final List<String> packageList) {
22670            Preconditions.checkNotNull(packageList);
22671            List<String> removedFromList = null;
22672            synchronized (mPackages) {
22673                if (mKeepUninstalledPackages != null) {
22674                    final int packagesCount = mKeepUninstalledPackages.size();
22675                    for (int i = 0; i < packagesCount; i++) {
22676                        String oldPackage = mKeepUninstalledPackages.get(i);
22677                        if (packageList != null && packageList.contains(oldPackage)) {
22678                            continue;
22679                        }
22680                        if (removedFromList == null) {
22681                            removedFromList = new ArrayList<>();
22682                        }
22683                        removedFromList.add(oldPackage);
22684                    }
22685                }
22686                mKeepUninstalledPackages = new ArrayList<>(packageList);
22687                if (removedFromList != null) {
22688                    final int removedCount = removedFromList.size();
22689                    for (int i = 0; i < removedCount; i++) {
22690                        deletePackageIfUnusedLPr(removedFromList.get(i));
22691                    }
22692                }
22693            }
22694        }
22695
22696        @Override
22697        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22698            synchronized (mPackages) {
22699                // If we do not support permission review, done.
22700                if (!mPermissionReviewRequired) {
22701                    return false;
22702                }
22703
22704                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22705                if (packageSetting == null) {
22706                    return false;
22707                }
22708
22709                // Permission review applies only to apps not supporting the new permission model.
22710                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22711                    return false;
22712                }
22713
22714                // Legacy apps have the permission and get user consent on launch.
22715                PermissionsState permissionsState = packageSetting.getPermissionsState();
22716                return permissionsState.isPermissionReviewRequired(userId);
22717            }
22718        }
22719
22720        @Override
22721        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22722            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22723        }
22724
22725        @Override
22726        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22727                int userId) {
22728            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22729        }
22730
22731        @Override
22732        public void setDeviceAndProfileOwnerPackages(
22733                int deviceOwnerUserId, String deviceOwnerPackage,
22734                SparseArray<String> profileOwnerPackages) {
22735            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22736                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22737        }
22738
22739        @Override
22740        public boolean isPackageDataProtected(int userId, String packageName) {
22741            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22742        }
22743
22744        @Override
22745        public boolean isPackageEphemeral(int userId, String packageName) {
22746            synchronized (mPackages) {
22747                PackageParser.Package p = mPackages.get(packageName);
22748                return p != null ? p.applicationInfo.isInstantApp() : false;
22749            }
22750        }
22751
22752        @Override
22753        public boolean wasPackageEverLaunched(String packageName, int userId) {
22754            synchronized (mPackages) {
22755                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22756            }
22757        }
22758
22759        @Override
22760        public void grantRuntimePermission(String packageName, String name, int userId,
22761                boolean overridePolicy) {
22762            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22763                    overridePolicy);
22764        }
22765
22766        @Override
22767        public void revokeRuntimePermission(String packageName, String name, int userId,
22768                boolean overridePolicy) {
22769            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22770                    overridePolicy);
22771        }
22772
22773        @Override
22774        public String getNameForUid(int uid) {
22775            return PackageManagerService.this.getNameForUid(uid);
22776        }
22777
22778        @Override
22779        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22780                Intent origIntent, String resolvedType, Intent launchIntent,
22781                String callingPackage, int userId) {
22782            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22783                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22784        }
22785
22786        @Override
22787        public void grantEphemeralAccess(int userId, Intent intent,
22788                int targetAppId, int ephemeralAppId) {
22789            synchronized (mPackages) {
22790                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22791                        targetAppId, ephemeralAppId);
22792            }
22793        }
22794
22795        @Override
22796        public void pruneInstantApps() {
22797            synchronized (mPackages) {
22798                mInstantAppRegistry.pruneInstantAppsLPw();
22799            }
22800        }
22801
22802        @Override
22803        public String getSetupWizardPackageName() {
22804            return mSetupWizardPackage;
22805        }
22806
22807        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22808            if (policy != null) {
22809                mExternalSourcesPolicy = policy;
22810            }
22811        }
22812
22813        @Override
22814        public boolean isPackagePersistent(String packageName) {
22815            synchronized (mPackages) {
22816                PackageParser.Package pkg = mPackages.get(packageName);
22817                return pkg != null
22818                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22819                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22820                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22821                        : false;
22822            }
22823        }
22824
22825        @Override
22826        public List<PackageInfo> getOverlayPackages(int userId) {
22827            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22828            synchronized (mPackages) {
22829                for (PackageParser.Package p : mPackages.values()) {
22830                    if (p.mOverlayTarget != null) {
22831                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22832                        if (pkg != null) {
22833                            overlayPackages.add(pkg);
22834                        }
22835                    }
22836                }
22837            }
22838            return overlayPackages;
22839        }
22840
22841        @Override
22842        public List<String> getTargetPackageNames(int userId) {
22843            List<String> targetPackages = new ArrayList<>();
22844            synchronized (mPackages) {
22845                for (PackageParser.Package p : mPackages.values()) {
22846                    if (p.mOverlayTarget == null) {
22847                        targetPackages.add(p.packageName);
22848                    }
22849                }
22850            }
22851            return targetPackages;
22852        }
22853
22854
22855        @Override
22856        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22857                List<String> overlayPackageNames) {
22858            // TODO: implement when we integrate OMS properly
22859            return false;
22860        }
22861    }
22862
22863    @Override
22864    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22865        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22866        synchronized (mPackages) {
22867            final long identity = Binder.clearCallingIdentity();
22868            try {
22869                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22870                        packageNames, userId);
22871            } finally {
22872                Binder.restoreCallingIdentity(identity);
22873            }
22874        }
22875    }
22876
22877    @Override
22878    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22879        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22880        synchronized (mPackages) {
22881            final long identity = Binder.clearCallingIdentity();
22882            try {
22883                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
22884                        packageNames, userId);
22885            } finally {
22886                Binder.restoreCallingIdentity(identity);
22887            }
22888        }
22889    }
22890
22891    private static void enforceSystemOrPhoneCaller(String tag) {
22892        int callingUid = Binder.getCallingUid();
22893        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22894            throw new SecurityException(
22895                    "Cannot call " + tag + " from UID " + callingUid);
22896        }
22897    }
22898
22899    boolean isHistoricalPackageUsageAvailable() {
22900        return mPackageUsage.isHistoricalPackageUsageAvailable();
22901    }
22902
22903    /**
22904     * Return a <b>copy</b> of the collection of packages known to the package manager.
22905     * @return A copy of the values of mPackages.
22906     */
22907    Collection<PackageParser.Package> getPackages() {
22908        synchronized (mPackages) {
22909            return new ArrayList<>(mPackages.values());
22910        }
22911    }
22912
22913    /**
22914     * Logs process start information (including base APK hash) to the security log.
22915     * @hide
22916     */
22917    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22918            String apkFile, int pid) {
22919        if (!SecurityLog.isLoggingEnabled()) {
22920            return;
22921        }
22922        Bundle data = new Bundle();
22923        data.putLong("startTimestamp", System.currentTimeMillis());
22924        data.putString("processName", processName);
22925        data.putInt("uid", uid);
22926        data.putString("seinfo", seinfo);
22927        data.putString("apkFile", apkFile);
22928        data.putInt("pid", pid);
22929        Message msg = mProcessLoggingHandler.obtainMessage(
22930                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22931        msg.setData(data);
22932        mProcessLoggingHandler.sendMessage(msg);
22933    }
22934
22935    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22936        return mCompilerStats.getPackageStats(pkgName);
22937    }
22938
22939    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22940        return getOrCreateCompilerPackageStats(pkg.packageName);
22941    }
22942
22943    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22944        return mCompilerStats.getOrCreatePackageStats(pkgName);
22945    }
22946
22947    public void deleteCompilerPackageStats(String pkgName) {
22948        mCompilerStats.deletePackageStats(pkgName);
22949    }
22950
22951    @Override
22952    public int getInstallReason(String packageName, int userId) {
22953        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22954                true /* requireFullPermission */, false /* checkShell */,
22955                "get install reason");
22956        synchronized (mPackages) {
22957            final PackageSetting ps = mSettings.mPackages.get(packageName);
22958            if (ps != null) {
22959                return ps.getInstallReason(userId);
22960            }
22961        }
22962        return PackageManager.INSTALL_REASON_UNKNOWN;
22963    }
22964
22965    @Override
22966    public boolean canRequestPackageInstalls(String packageName, int userId) {
22967        int callingUid = Binder.getCallingUid();
22968        int uid = getPackageUid(packageName, 0, userId);
22969        if (callingUid != uid && callingUid != Process.ROOT_UID
22970                && callingUid != Process.SYSTEM_UID) {
22971            throw new SecurityException(
22972                    "Caller uid " + callingUid + " does not own package " + packageName);
22973        }
22974        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
22975        if (info == null) {
22976            return false;
22977        }
22978        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
22979            throw new UnsupportedOperationException(
22980                    "Operation only supported on apps targeting Android O or higher");
22981        }
22982        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
22983        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
22984        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
22985            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
22986        }
22987        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
22988            return false;
22989        }
22990        if (mExternalSourcesPolicy != null) {
22991            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
22992            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
22993                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
22994            }
22995        }
22996        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
22997    }
22998}
22999