PackageManagerService.java revision 9106c64bf3ca60d0b867fa1f2d78d3b19c9e4178
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.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppInfo;
132import android.content.pm.EphemeralRequest;
133import android.content.pm.EphemeralResolveInfo;
134import android.content.pm.EphemeralResponse;
135import android.content.pm.FallbackCategoryProvider;
136import android.content.pm.FeatureInfo;
137import android.content.pm.IOnPermissionsChangeListener;
138import android.content.pm.IPackageDataObserver;
139import android.content.pm.IPackageDeleteObserver;
140import android.content.pm.IPackageDeleteObserver2;
141import android.content.pm.IPackageInstallObserver2;
142import android.content.pm.IPackageInstaller;
143import android.content.pm.IPackageManager;
144import android.content.pm.IPackageMoveObserver;
145import android.content.pm.IPackageStatsObserver;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.ServiceInfo;
168import android.content.pm.SharedLibraryInfo;
169import android.content.pm.Signature;
170import android.content.pm.UserInfo;
171import android.content.pm.VerifierDeviceIdentity;
172import android.content.pm.VerifierInfo;
173import android.content.pm.VersionedPackage;
174import android.content.res.Resources;
175import android.graphics.Bitmap;
176import android.hardware.display.DisplayManager;
177import android.net.Uri;
178import android.os.Binder;
179import android.os.Build;
180import android.os.Bundle;
181import android.os.Debug;
182import android.os.Environment;
183import android.os.Environment.UserEnvironment;
184import android.os.FileUtils;
185import android.os.Handler;
186import android.os.IBinder;
187import android.os.Looper;
188import android.os.Message;
189import android.os.Parcel;
190import android.os.ParcelFileDescriptor;
191import android.os.PatternMatcher;
192import android.os.Process;
193import android.os.RemoteCallbackList;
194import android.os.RemoteException;
195import android.os.ResultReceiver;
196import android.os.SELinux;
197import android.os.ServiceManager;
198import android.os.ShellCallback;
199import android.os.SystemClock;
200import android.os.SystemProperties;
201import android.os.Trace;
202import android.os.UserHandle;
203import android.os.UserManager;
204import android.os.UserManagerInternal;
205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManagerInternal;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.VolumeInfo;
210import android.os.storage.VolumeRecord;
211import android.provider.Settings.Global;
212import android.provider.Settings.Secure;
213import android.security.KeyStore;
214import android.security.SystemKeyStore;
215import android.system.ErrnoException;
216import android.system.Os;
217import android.text.TextUtils;
218import android.text.format.DateUtils;
219import android.util.ArrayMap;
220import android.util.ArraySet;
221import android.util.Base64;
222import android.util.DisplayMetrics;
223import android.util.EventLog;
224import android.util.ExceptionUtils;
225import android.util.Log;
226import android.util.LogPrinter;
227import android.util.MathUtils;
228import android.util.PackageUtils;
229import android.util.Pair;
230import android.util.PrintStreamPrinter;
231import android.util.Slog;
232import android.util.SparseArray;
233import android.util.SparseBooleanArray;
234import android.util.SparseIntArray;
235import android.util.Xml;
236import android.util.jar.StrictJarFile;
237import android.view.Display;
238
239import com.android.internal.R;
240import com.android.internal.annotations.GuardedBy;
241import com.android.internal.app.IMediaContainerService;
242import com.android.internal.app.ResolverActivity;
243import com.android.internal.content.NativeLibraryHelper;
244import com.android.internal.content.PackageHelper;
245import com.android.internal.logging.MetricsLogger;
246import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
247import com.android.internal.os.IParcelFileDescriptorFactory;
248import com.android.internal.os.RoSystemProperties;
249import com.android.internal.os.SomeArgs;
250import com.android.internal.os.Zygote;
251import com.android.internal.telephony.CarrierAppUtils;
252import com.android.internal.util.ArrayUtils;
253import com.android.internal.util.FastPrintWriter;
254import com.android.internal.util.FastXmlSerializer;
255import com.android.internal.util.IndentingPrintWriter;
256import com.android.internal.util.Preconditions;
257import com.android.internal.util.XmlUtils;
258import com.android.server.AttributeCache;
259import com.android.server.BackgroundDexOptJobService;
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    @GuardedBy("mPackages")
725    int mChangedPackagesSequenceNumber;
726    /**
727     * List of changed [installed, removed or updated] packages.
728     * mapping from user id -> sequence number -> package name
729     */
730    @GuardedBy("mPackages")
731    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
732    /**
733     * The sequence number of the last change to a package.
734     * mapping from user id -> package name -> sequence number
735     */
736    @GuardedBy("mPackages")
737    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
738
739    public static final class SharedLibraryEntry {
740        public final String path;
741        public final String apk;
742        public final SharedLibraryInfo info;
743
744        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
745                String declaringPackageName, int declaringPackageVersionCode) {
746            path = _path;
747            apk = _apk;
748            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
749                    declaringPackageName, declaringPackageVersionCode), null);
750        }
751    }
752
753    // Currently known shared libraries.
754    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
755    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
756            new ArrayMap<>();
757
758    // All available activities, for your resolving pleasure.
759    final ActivityIntentResolver mActivities =
760            new ActivityIntentResolver();
761
762    // All available receivers, for your resolving pleasure.
763    final ActivityIntentResolver mReceivers =
764            new ActivityIntentResolver();
765
766    // All available services, for your resolving pleasure.
767    final ServiceIntentResolver mServices = new ServiceIntentResolver();
768
769    // All available providers, for your resolving pleasure.
770    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
771
772    // Mapping from provider base names (first directory in content URI codePath)
773    // to the provider information.
774    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
775            new ArrayMap<String, PackageParser.Provider>();
776
777    // Mapping from instrumentation class names to info about them.
778    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
779            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
780
781    // Mapping from permission names to info about them.
782    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
783            new ArrayMap<String, PackageParser.PermissionGroup>();
784
785    // Packages whose data we have transfered into another package, thus
786    // should no longer exist.
787    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
788
789    // Broadcast actions that are only available to the system.
790    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
791
792    /** List of packages waiting for verification. */
793    final SparseArray<PackageVerificationState> mPendingVerification
794            = new SparseArray<PackageVerificationState>();
795
796    /** Set of packages associated with each app op permission. */
797    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
798
799    final PackageInstallerService mInstallerService;
800
801    private final PackageDexOptimizer mPackageDexOptimizer;
802    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
803    // is used by other apps).
804    private final DexManager mDexManager;
805
806    private AtomicInteger mNextMoveId = new AtomicInteger();
807    private final MoveCallbacks mMoveCallbacks;
808
809    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
810
811    // Cache of users who need badging.
812    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
813
814    /** Token for keys in mPendingVerification. */
815    private int mPendingVerificationToken = 0;
816
817    volatile boolean mSystemReady;
818    volatile boolean mSafeMode;
819    volatile boolean mHasSystemUidErrors;
820
821    ApplicationInfo mAndroidApplication;
822    final ActivityInfo mResolveActivity = new ActivityInfo();
823    final ResolveInfo mResolveInfo = new ResolveInfo();
824    ComponentName mResolveComponentName;
825    PackageParser.Package mPlatformPackage;
826    ComponentName mCustomResolverComponentName;
827
828    boolean mResolverReplaced = false;
829
830    private final @Nullable ComponentName mIntentFilterVerifierComponent;
831    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
832
833    private int mIntentFilterVerificationToken = 0;
834
835    /** The service connection to the ephemeral resolver */
836    final EphemeralResolverConnection mEphemeralResolverConnection;
837
838    /** Component used to install ephemeral applications */
839    ComponentName mEphemeralInstallerComponent;
840    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
841    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
842
843    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
844            = new SparseArray<IntentFilterVerificationState>();
845
846    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
847
848    // List of packages names to keep cached, even if they are uninstalled for all users
849    private List<String> mKeepUninstalledPackages;
850
851    private UserManagerInternal mUserManagerInternal;
852
853    private File mCacheDir;
854
855    private ArraySet<String> mPrivappPermissionsViolations;
856
857    private static class IFVerificationParams {
858        PackageParser.Package pkg;
859        boolean replacing;
860        int userId;
861        int verifierUid;
862
863        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
864                int _userId, int _verifierUid) {
865            pkg = _pkg;
866            replacing = _replacing;
867            userId = _userId;
868            replacing = _replacing;
869            verifierUid = _verifierUid;
870        }
871    }
872
873    private interface IntentFilterVerifier<T extends IntentFilter> {
874        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
875                                               T filter, String packageName);
876        void startVerifications(int userId);
877        void receiveVerificationResponse(int verificationId);
878    }
879
880    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
881        private Context mContext;
882        private ComponentName mIntentFilterVerifierComponent;
883        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
884
885        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
886            mContext = context;
887            mIntentFilterVerifierComponent = verifierComponent;
888        }
889
890        private String getDefaultScheme() {
891            return IntentFilter.SCHEME_HTTPS;
892        }
893
894        @Override
895        public void startVerifications(int userId) {
896            // Launch verifications requests
897            int count = mCurrentIntentFilterVerifications.size();
898            for (int n=0; n<count; n++) {
899                int verificationId = mCurrentIntentFilterVerifications.get(n);
900                final IntentFilterVerificationState ivs =
901                        mIntentFilterVerificationStates.get(verificationId);
902
903                String packageName = ivs.getPackageName();
904
905                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
906                final int filterCount = filters.size();
907                ArraySet<String> domainsSet = new ArraySet<>();
908                for (int m=0; m<filterCount; m++) {
909                    PackageParser.ActivityIntentInfo filter = filters.get(m);
910                    domainsSet.addAll(filter.getHostsList());
911                }
912                synchronized (mPackages) {
913                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
914                            packageName, domainsSet) != null) {
915                        scheduleWriteSettingsLocked();
916                    }
917                }
918                sendVerificationRequest(userId, verificationId, ivs);
919            }
920            mCurrentIntentFilterVerifications.clear();
921        }
922
923        private void sendVerificationRequest(int userId, int verificationId,
924                IntentFilterVerificationState ivs) {
925
926            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
927            verificationIntent.putExtra(
928                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
929                    verificationId);
930            verificationIntent.putExtra(
931                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
932                    getDefaultScheme());
933            verificationIntent.putExtra(
934                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
935                    ivs.getHostsString());
936            verificationIntent.putExtra(
937                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
938                    ivs.getPackageName());
939            verificationIntent.setComponent(mIntentFilterVerifierComponent);
940            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
941
942            UserHandle user = new UserHandle(userId);
943            mContext.sendBroadcastAsUser(verificationIntent, user);
944            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
945                    "Sending IntentFilter verification broadcast");
946        }
947
948        public void receiveVerificationResponse(int verificationId) {
949            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
950
951            final boolean verified = ivs.isVerified();
952
953            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
954            final int count = filters.size();
955            if (DEBUG_DOMAIN_VERIFICATION) {
956                Slog.i(TAG, "Received verification response " + verificationId
957                        + " for " + count + " filters, verified=" + verified);
958            }
959            for (int n=0; n<count; n++) {
960                PackageParser.ActivityIntentInfo filter = filters.get(n);
961                filter.setVerified(verified);
962
963                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
964                        + " verified with result:" + verified + " and hosts:"
965                        + ivs.getHostsString());
966            }
967
968            mIntentFilterVerificationStates.remove(verificationId);
969
970            final String packageName = ivs.getPackageName();
971            IntentFilterVerificationInfo ivi = null;
972
973            synchronized (mPackages) {
974                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
975            }
976            if (ivi == null) {
977                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
978                        + verificationId + " packageName:" + packageName);
979                return;
980            }
981            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
982                    "Updating IntentFilterVerificationInfo for package " + packageName
983                            +" verificationId:" + verificationId);
984
985            synchronized (mPackages) {
986                if (verified) {
987                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
988                } else {
989                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
990                }
991                scheduleWriteSettingsLocked();
992
993                final int userId = ivs.getUserId();
994                if (userId != UserHandle.USER_ALL) {
995                    final int userStatus =
996                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
997
998                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
999                    boolean needUpdate = false;
1000
1001                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1002                    // already been set by the User thru the Disambiguation dialog
1003                    switch (userStatus) {
1004                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1005                            if (verified) {
1006                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1007                            } else {
1008                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1009                            }
1010                            needUpdate = true;
1011                            break;
1012
1013                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1014                            if (verified) {
1015                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1016                                needUpdate = true;
1017                            }
1018                            break;
1019
1020                        default:
1021                            // Nothing to do
1022                    }
1023
1024                    if (needUpdate) {
1025                        mSettings.updateIntentFilterVerificationStatusLPw(
1026                                packageName, updatedStatus, userId);
1027                        scheduleWritePackageRestrictionsLocked(userId);
1028                    }
1029                }
1030            }
1031        }
1032
1033        @Override
1034        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1035                    ActivityIntentInfo filter, String packageName) {
1036            if (!hasValidDomains(filter)) {
1037                return false;
1038            }
1039            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1040            if (ivs == null) {
1041                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1042                        packageName);
1043            }
1044            if (DEBUG_DOMAIN_VERIFICATION) {
1045                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1046            }
1047            ivs.addFilter(filter);
1048            return true;
1049        }
1050
1051        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1052                int userId, int verificationId, String packageName) {
1053            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1054                    verifierUid, userId, packageName);
1055            ivs.setPendingState();
1056            synchronized (mPackages) {
1057                mIntentFilterVerificationStates.append(verificationId, ivs);
1058                mCurrentIntentFilterVerifications.add(verificationId);
1059            }
1060            return ivs;
1061        }
1062    }
1063
1064    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1065        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1066                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1067                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1068    }
1069
1070    // Set of pending broadcasts for aggregating enable/disable of components.
1071    static class PendingPackageBroadcasts {
1072        // for each user id, a map of <package name -> components within that package>
1073        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1074
1075        public PendingPackageBroadcasts() {
1076            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1077        }
1078
1079        public ArrayList<String> get(int userId, String packageName) {
1080            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1081            return packages.get(packageName);
1082        }
1083
1084        public void put(int userId, String packageName, ArrayList<String> components) {
1085            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1086            packages.put(packageName, components);
1087        }
1088
1089        public void remove(int userId, String packageName) {
1090            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1091            if (packages != null) {
1092                packages.remove(packageName);
1093            }
1094        }
1095
1096        public void remove(int userId) {
1097            mUidMap.remove(userId);
1098        }
1099
1100        public int userIdCount() {
1101            return mUidMap.size();
1102        }
1103
1104        public int userIdAt(int n) {
1105            return mUidMap.keyAt(n);
1106        }
1107
1108        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1109            return mUidMap.get(userId);
1110        }
1111
1112        public int size() {
1113            // total number of pending broadcast entries across all userIds
1114            int num = 0;
1115            for (int i = 0; i< mUidMap.size(); i++) {
1116                num += mUidMap.valueAt(i).size();
1117            }
1118            return num;
1119        }
1120
1121        public void clear() {
1122            mUidMap.clear();
1123        }
1124
1125        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1126            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1127            if (map == null) {
1128                map = new ArrayMap<String, ArrayList<String>>();
1129                mUidMap.put(userId, map);
1130            }
1131            return map;
1132        }
1133    }
1134    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1135
1136    // Service Connection to remote media container service to copy
1137    // package uri's from external media onto secure containers
1138    // or internal storage.
1139    private IMediaContainerService mContainerService = null;
1140
1141    static final int SEND_PENDING_BROADCAST = 1;
1142    static final int MCS_BOUND = 3;
1143    static final int END_COPY = 4;
1144    static final int INIT_COPY = 5;
1145    static final int MCS_UNBIND = 6;
1146    static final int START_CLEANING_PACKAGE = 7;
1147    static final int FIND_INSTALL_LOC = 8;
1148    static final int POST_INSTALL = 9;
1149    static final int MCS_RECONNECT = 10;
1150    static final int MCS_GIVE_UP = 11;
1151    static final int UPDATED_MEDIA_STATUS = 12;
1152    static final int WRITE_SETTINGS = 13;
1153    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1154    static final int PACKAGE_VERIFIED = 15;
1155    static final int CHECK_PENDING_VERIFICATION = 16;
1156    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1157    static final int INTENT_FILTER_VERIFIED = 18;
1158    static final int WRITE_PACKAGE_LIST = 19;
1159    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1160
1161    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1162
1163    // Delay time in millisecs
1164    static final int BROADCAST_DELAY = 10 * 1000;
1165
1166    static UserManagerService sUserManager;
1167
1168    // Stores a list of users whose package restrictions file needs to be updated
1169    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1170
1171    final private DefaultContainerConnection mDefContainerConn =
1172            new DefaultContainerConnection();
1173    class DefaultContainerConnection implements ServiceConnection {
1174        public void onServiceConnected(ComponentName name, IBinder service) {
1175            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1176            final IMediaContainerService imcs = IMediaContainerService.Stub
1177                    .asInterface(Binder.allowBlocking(service));
1178            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1179        }
1180
1181        public void onServiceDisconnected(ComponentName name) {
1182            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1183        }
1184    }
1185
1186    // Recordkeeping of restore-after-install operations that are currently in flight
1187    // between the Package Manager and the Backup Manager
1188    static class PostInstallData {
1189        public InstallArgs args;
1190        public PackageInstalledInfo res;
1191
1192        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1193            args = _a;
1194            res = _r;
1195        }
1196    }
1197
1198    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1199    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1200
1201    // XML tags for backup/restore of various bits of state
1202    private static final String TAG_PREFERRED_BACKUP = "pa";
1203    private static final String TAG_DEFAULT_APPS = "da";
1204    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1205
1206    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1207    private static final String TAG_ALL_GRANTS = "rt-grants";
1208    private static final String TAG_GRANT = "grant";
1209    private static final String ATTR_PACKAGE_NAME = "pkg";
1210
1211    private static final String TAG_PERMISSION = "perm";
1212    private static final String ATTR_PERMISSION_NAME = "name";
1213    private static final String ATTR_IS_GRANTED = "g";
1214    private static final String ATTR_USER_SET = "set";
1215    private static final String ATTR_USER_FIXED = "fixed";
1216    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1217
1218    // System/policy permission grants are not backed up
1219    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1220            FLAG_PERMISSION_POLICY_FIXED
1221            | FLAG_PERMISSION_SYSTEM_FIXED
1222            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1223
1224    // And we back up these user-adjusted states
1225    private static final int USER_RUNTIME_GRANT_MASK =
1226            FLAG_PERMISSION_USER_SET
1227            | FLAG_PERMISSION_USER_FIXED
1228            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1229
1230    final @Nullable String mRequiredVerifierPackage;
1231    final @NonNull String mRequiredInstallerPackage;
1232    final @NonNull String mRequiredUninstallerPackage;
1233    final @Nullable String mSetupWizardPackage;
1234    final @Nullable String mStorageManagerPackage;
1235    final @NonNull String mServicesSystemSharedLibraryPackageName;
1236    final @NonNull String mSharedSystemSharedLibraryPackageName;
1237
1238    final boolean mPermissionReviewRequired;
1239
1240    private final PackageUsage mPackageUsage = new PackageUsage();
1241    private final CompilerStats mCompilerStats = new CompilerStats();
1242
1243    class PackageHandler extends Handler {
1244        private boolean mBound = false;
1245        final ArrayList<HandlerParams> mPendingInstalls =
1246            new ArrayList<HandlerParams>();
1247
1248        private boolean connectToService() {
1249            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1250                    " DefaultContainerService");
1251            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1252            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1253            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1254                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1255                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1256                mBound = true;
1257                return true;
1258            }
1259            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1260            return false;
1261        }
1262
1263        private void disconnectService() {
1264            mContainerService = null;
1265            mBound = false;
1266            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1267            mContext.unbindService(mDefContainerConn);
1268            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1269        }
1270
1271        PackageHandler(Looper looper) {
1272            super(looper);
1273        }
1274
1275        public void handleMessage(Message msg) {
1276            try {
1277                doHandleMessage(msg);
1278            } finally {
1279                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1280            }
1281        }
1282
1283        void doHandleMessage(Message msg) {
1284            switch (msg.what) {
1285                case INIT_COPY: {
1286                    HandlerParams params = (HandlerParams) msg.obj;
1287                    int idx = mPendingInstalls.size();
1288                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1289                    // If a bind was already initiated we dont really
1290                    // need to do anything. The pending install
1291                    // will be processed later on.
1292                    if (!mBound) {
1293                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1294                                System.identityHashCode(mHandler));
1295                        // If this is the only one pending we might
1296                        // have to bind to the service again.
1297                        if (!connectToService()) {
1298                            Slog.e(TAG, "Failed to bind to media container service");
1299                            params.serviceError();
1300                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1301                                    System.identityHashCode(mHandler));
1302                            if (params.traceMethod != null) {
1303                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1304                                        params.traceCookie);
1305                            }
1306                            return;
1307                        } else {
1308                            // Once we bind to the service, the first
1309                            // pending request will be processed.
1310                            mPendingInstalls.add(idx, params);
1311                        }
1312                    } else {
1313                        mPendingInstalls.add(idx, params);
1314                        // Already bound to the service. Just make
1315                        // sure we trigger off processing the first request.
1316                        if (idx == 0) {
1317                            mHandler.sendEmptyMessage(MCS_BOUND);
1318                        }
1319                    }
1320                    break;
1321                }
1322                case MCS_BOUND: {
1323                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1324                    if (msg.obj != null) {
1325                        mContainerService = (IMediaContainerService) msg.obj;
1326                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1327                                System.identityHashCode(mHandler));
1328                    }
1329                    if (mContainerService == null) {
1330                        if (!mBound) {
1331                            // Something seriously wrong since we are not bound and we are not
1332                            // waiting for connection. Bail out.
1333                            Slog.e(TAG, "Cannot bind to media container service");
1334                            for (HandlerParams params : mPendingInstalls) {
1335                                // Indicate service bind error
1336                                params.serviceError();
1337                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1338                                        System.identityHashCode(params));
1339                                if (params.traceMethod != null) {
1340                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1341                                            params.traceMethod, params.traceCookie);
1342                                }
1343                                return;
1344                            }
1345                            mPendingInstalls.clear();
1346                        } else {
1347                            Slog.w(TAG, "Waiting to connect to media container service");
1348                        }
1349                    } else if (mPendingInstalls.size() > 0) {
1350                        HandlerParams params = mPendingInstalls.get(0);
1351                        if (params != null) {
1352                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1353                                    System.identityHashCode(params));
1354                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1355                            if (params.startCopy()) {
1356                                // We are done...  look for more work or to
1357                                // go idle.
1358                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1359                                        "Checking for more work or unbind...");
1360                                // Delete pending install
1361                                if (mPendingInstalls.size() > 0) {
1362                                    mPendingInstalls.remove(0);
1363                                }
1364                                if (mPendingInstalls.size() == 0) {
1365                                    if (mBound) {
1366                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1367                                                "Posting delayed MCS_UNBIND");
1368                                        removeMessages(MCS_UNBIND);
1369                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1370                                        // Unbind after a little delay, to avoid
1371                                        // continual thrashing.
1372                                        sendMessageDelayed(ubmsg, 10000);
1373                                    }
1374                                } else {
1375                                    // There are more pending requests in queue.
1376                                    // Just post MCS_BOUND message to trigger processing
1377                                    // of next pending install.
1378                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1379                                            "Posting MCS_BOUND for next work");
1380                                    mHandler.sendEmptyMessage(MCS_BOUND);
1381                                }
1382                            }
1383                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1384                        }
1385                    } else {
1386                        // Should never happen ideally.
1387                        Slog.w(TAG, "Empty queue");
1388                    }
1389                    break;
1390                }
1391                case MCS_RECONNECT: {
1392                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1393                    if (mPendingInstalls.size() > 0) {
1394                        if (mBound) {
1395                            disconnectService();
1396                        }
1397                        if (!connectToService()) {
1398                            Slog.e(TAG, "Failed to bind to media container service");
1399                            for (HandlerParams params : mPendingInstalls) {
1400                                // Indicate service bind error
1401                                params.serviceError();
1402                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1403                                        System.identityHashCode(params));
1404                            }
1405                            mPendingInstalls.clear();
1406                        }
1407                    }
1408                    break;
1409                }
1410                case MCS_UNBIND: {
1411                    // If there is no actual work left, then time to unbind.
1412                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1413
1414                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1415                        if (mBound) {
1416                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1417
1418                            disconnectService();
1419                        }
1420                    } else if (mPendingInstalls.size() > 0) {
1421                        // There are more pending requests in queue.
1422                        // Just post MCS_BOUND message to trigger processing
1423                        // of next pending install.
1424                        mHandler.sendEmptyMessage(MCS_BOUND);
1425                    }
1426
1427                    break;
1428                }
1429                case MCS_GIVE_UP: {
1430                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1431                    HandlerParams params = mPendingInstalls.remove(0);
1432                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1433                            System.identityHashCode(params));
1434                    break;
1435                }
1436                case SEND_PENDING_BROADCAST: {
1437                    String packages[];
1438                    ArrayList<String> components[];
1439                    int size = 0;
1440                    int uids[];
1441                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1442                    synchronized (mPackages) {
1443                        if (mPendingBroadcasts == null) {
1444                            return;
1445                        }
1446                        size = mPendingBroadcasts.size();
1447                        if (size <= 0) {
1448                            // Nothing to be done. Just return
1449                            return;
1450                        }
1451                        packages = new String[size];
1452                        components = new ArrayList[size];
1453                        uids = new int[size];
1454                        int i = 0;  // filling out the above arrays
1455
1456                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1457                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1458                            Iterator<Map.Entry<String, ArrayList<String>>> it
1459                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1460                                            .entrySet().iterator();
1461                            while (it.hasNext() && i < size) {
1462                                Map.Entry<String, ArrayList<String>> ent = it.next();
1463                                packages[i] = ent.getKey();
1464                                components[i] = ent.getValue();
1465                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1466                                uids[i] = (ps != null)
1467                                        ? UserHandle.getUid(packageUserId, ps.appId)
1468                                        : -1;
1469                                i++;
1470                            }
1471                        }
1472                        size = i;
1473                        mPendingBroadcasts.clear();
1474                    }
1475                    // Send broadcasts
1476                    for (int i = 0; i < size; i++) {
1477                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1478                    }
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1480                    break;
1481                }
1482                case START_CLEANING_PACKAGE: {
1483                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1484                    final String packageName = (String)msg.obj;
1485                    final int userId = msg.arg1;
1486                    final boolean andCode = msg.arg2 != 0;
1487                    synchronized (mPackages) {
1488                        if (userId == UserHandle.USER_ALL) {
1489                            int[] users = sUserManager.getUserIds();
1490                            for (int user : users) {
1491                                mSettings.addPackageToCleanLPw(
1492                                        new PackageCleanItem(user, packageName, andCode));
1493                            }
1494                        } else {
1495                            mSettings.addPackageToCleanLPw(
1496                                    new PackageCleanItem(userId, packageName, andCode));
1497                        }
1498                    }
1499                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1500                    startCleaningPackages();
1501                } break;
1502                case POST_INSTALL: {
1503                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1504
1505                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1506                    final boolean didRestore = (msg.arg2 != 0);
1507                    mRunningInstalls.delete(msg.arg1);
1508
1509                    if (data != null) {
1510                        InstallArgs args = data.args;
1511                        PackageInstalledInfo parentRes = data.res;
1512
1513                        final boolean grantPermissions = (args.installFlags
1514                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1515                        final boolean killApp = (args.installFlags
1516                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1517                        final String[] grantedPermissions = args.installGrantPermissions;
1518
1519                        // Handle the parent package
1520                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1521                                grantedPermissions, didRestore, args.installerPackageName,
1522                                args.observer);
1523
1524                        // Handle the child packages
1525                        final int childCount = (parentRes.addedChildPackages != null)
1526                                ? parentRes.addedChildPackages.size() : 0;
1527                        for (int i = 0; i < childCount; i++) {
1528                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1529                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1530                                    grantedPermissions, false, args.installerPackageName,
1531                                    args.observer);
1532                        }
1533
1534                        // Log tracing if needed
1535                        if (args.traceMethod != null) {
1536                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1537                                    args.traceCookie);
1538                        }
1539                    } else {
1540                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1541                    }
1542
1543                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1544                } break;
1545                case UPDATED_MEDIA_STATUS: {
1546                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1547                    boolean reportStatus = msg.arg1 == 1;
1548                    boolean doGc = msg.arg2 == 1;
1549                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1550                    if (doGc) {
1551                        // Force a gc to clear up stale containers.
1552                        Runtime.getRuntime().gc();
1553                    }
1554                    if (msg.obj != null) {
1555                        @SuppressWarnings("unchecked")
1556                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1557                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1558                        // Unload containers
1559                        unloadAllContainers(args);
1560                    }
1561                    if (reportStatus) {
1562                        try {
1563                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1564                                    "Invoking StorageManagerService call back");
1565                            PackageHelper.getStorageManager().finishMediaUpdate();
1566                        } catch (RemoteException e) {
1567                            Log.e(TAG, "StorageManagerService not running?");
1568                        }
1569                    }
1570                } break;
1571                case WRITE_SETTINGS: {
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1573                    synchronized (mPackages) {
1574                        removeMessages(WRITE_SETTINGS);
1575                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1576                        mSettings.writeLPr();
1577                        mDirtyUsers.clear();
1578                    }
1579                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1580                } break;
1581                case WRITE_PACKAGE_RESTRICTIONS: {
1582                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1583                    synchronized (mPackages) {
1584                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1585                        for (int userId : mDirtyUsers) {
1586                            mSettings.writePackageRestrictionsLPr(userId);
1587                        }
1588                        mDirtyUsers.clear();
1589                    }
1590                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1591                } break;
1592                case WRITE_PACKAGE_LIST: {
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1594                    synchronized (mPackages) {
1595                        removeMessages(WRITE_PACKAGE_LIST);
1596                        mSettings.writePackageListLPr(msg.arg1);
1597                    }
1598                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1599                } break;
1600                case CHECK_PENDING_VERIFICATION: {
1601                    final int verificationId = msg.arg1;
1602                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1603
1604                    if ((state != null) && !state.timeoutExtended()) {
1605                        final InstallArgs args = state.getInstallArgs();
1606                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1607
1608                        Slog.i(TAG, "Verification timed out for " + originUri);
1609                        mPendingVerification.remove(verificationId);
1610
1611                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1612
1613                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1614                            Slog.i(TAG, "Continuing with installation of " + originUri);
1615                            state.setVerifierResponse(Binder.getCallingUid(),
1616                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1617                            broadcastPackageVerified(verificationId, originUri,
1618                                    PackageManager.VERIFICATION_ALLOW,
1619                                    state.getInstallArgs().getUser());
1620                            try {
1621                                ret = args.copyApk(mContainerService, true);
1622                            } catch (RemoteException e) {
1623                                Slog.e(TAG, "Could not contact the ContainerService");
1624                            }
1625                        } else {
1626                            broadcastPackageVerified(verificationId, originUri,
1627                                    PackageManager.VERIFICATION_REJECT,
1628                                    state.getInstallArgs().getUser());
1629                        }
1630
1631                        Trace.asyncTraceEnd(
1632                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1633
1634                        processPendingInstall(args, ret);
1635                        mHandler.sendEmptyMessage(MCS_UNBIND);
1636                    }
1637                    break;
1638                }
1639                case PACKAGE_VERIFIED: {
1640                    final int verificationId = msg.arg1;
1641
1642                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1643                    if (state == null) {
1644                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1645                        break;
1646                    }
1647
1648                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1649
1650                    state.setVerifierResponse(response.callerUid, response.code);
1651
1652                    if (state.isVerificationComplete()) {
1653                        mPendingVerification.remove(verificationId);
1654
1655                        final InstallArgs args = state.getInstallArgs();
1656                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1657
1658                        int ret;
1659                        if (state.isInstallAllowed()) {
1660                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1661                            broadcastPackageVerified(verificationId, originUri,
1662                                    response.code, state.getInstallArgs().getUser());
1663                            try {
1664                                ret = args.copyApk(mContainerService, true);
1665                            } catch (RemoteException e) {
1666                                Slog.e(TAG, "Could not contact the ContainerService");
1667                            }
1668                        } else {
1669                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1670                        }
1671
1672                        Trace.asyncTraceEnd(
1673                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1674
1675                        processPendingInstall(args, ret);
1676                        mHandler.sendEmptyMessage(MCS_UNBIND);
1677                    }
1678
1679                    break;
1680                }
1681                case START_INTENT_FILTER_VERIFICATIONS: {
1682                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1683                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1684                            params.replacing, params.pkg);
1685                    break;
1686                }
1687                case INTENT_FILTER_VERIFIED: {
1688                    final int verificationId = msg.arg1;
1689
1690                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1691                            verificationId);
1692                    if (state == null) {
1693                        Slog.w(TAG, "Invalid IntentFilter verification token "
1694                                + verificationId + " received");
1695                        break;
1696                    }
1697
1698                    final int userId = state.getUserId();
1699
1700                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1701                            "Processing IntentFilter verification with token:"
1702                            + verificationId + " and userId:" + userId);
1703
1704                    final IntentFilterVerificationResponse response =
1705                            (IntentFilterVerificationResponse) msg.obj;
1706
1707                    state.setVerifierResponse(response.callerUid, response.code);
1708
1709                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1710                            "IntentFilter verification with token:" + verificationId
1711                            + " and userId:" + userId
1712                            + " is settings verifier response with response code:"
1713                            + response.code);
1714
1715                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1716                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1717                                + response.getFailedDomainsString());
1718                    }
1719
1720                    if (state.isVerificationComplete()) {
1721                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1722                    } else {
1723                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1724                                "IntentFilter verification with token:" + verificationId
1725                                + " was not said to be complete");
1726                    }
1727
1728                    break;
1729                }
1730                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1731                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1732                            mEphemeralResolverConnection,
1733                            (EphemeralRequest) msg.obj,
1734                            mEphemeralInstallerActivity,
1735                            mHandler);
1736                }
1737            }
1738        }
1739    }
1740
1741    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1742            boolean killApp, String[] grantedPermissions,
1743            boolean launchedForRestore, String installerPackage,
1744            IPackageInstallObserver2 installObserver) {
1745        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1746            // Send the removed broadcasts
1747            if (res.removedInfo != null) {
1748                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1749            }
1750
1751            // Now that we successfully installed the package, grant runtime
1752            // permissions if requested before broadcasting the install. Also
1753            // for legacy apps in permission review mode we clear the permission
1754            // review flag which is used to emulate runtime permissions for
1755            // legacy apps.
1756            if (grantPermissions) {
1757                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1758            }
1759
1760            final boolean update = res.removedInfo != null
1761                    && res.removedInfo.removedPackage != null;
1762
1763            // If this is the first time we have child packages for a disabled privileged
1764            // app that had no children, we grant requested runtime permissions to the new
1765            // children if the parent on the system image had them already granted.
1766            if (res.pkg.parentPackage != null) {
1767                synchronized (mPackages) {
1768                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1769                }
1770            }
1771
1772            synchronized (mPackages) {
1773                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1774            }
1775
1776            final String packageName = res.pkg.applicationInfo.packageName;
1777
1778            // Determine the set of users who are adding this package for
1779            // the first time vs. those who are seeing an update.
1780            int[] firstUsers = EMPTY_INT_ARRAY;
1781            int[] updateUsers = EMPTY_INT_ARRAY;
1782            if (res.origUsers == null || res.origUsers.length == 0) {
1783                firstUsers = res.newUsers;
1784            } else {
1785                for (int newUser : res.newUsers) {
1786                    boolean isNew = true;
1787                    for (int origUser : res.origUsers) {
1788                        if (origUser == newUser) {
1789                            isNew = false;
1790                            break;
1791                        }
1792                    }
1793                    if (isNew) {
1794                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1795                    } else {
1796                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1797                    }
1798                }
1799            }
1800
1801            // Send installed broadcasts if the install/update is not ephemeral
1802            // and the package is not a static shared lib.
1803            if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) {
1804                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1805
1806                // Send added for users that see the package for the first time
1807                // sendPackageAddedForNewUsers also deals with system apps
1808                int appId = UserHandle.getAppId(res.uid);
1809                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1810                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1811
1812                // Send added for users that don't see the package for the first time
1813                Bundle extras = new Bundle(1);
1814                extras.putInt(Intent.EXTRA_UID, res.uid);
1815                if (update) {
1816                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1817                }
1818                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1819                        extras, 0 /*flags*/, null /*targetPackage*/,
1820                        null /*finishedReceiver*/, updateUsers);
1821
1822                // Send replaced for users that don't see the package for the first time
1823                if (update) {
1824                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1825                            packageName, extras, 0 /*flags*/,
1826                            null /*targetPackage*/, null /*finishedReceiver*/,
1827                            updateUsers);
1828                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1829                            null /*package*/, null /*extras*/, 0 /*flags*/,
1830                            packageName /*targetPackage*/,
1831                            null /*finishedReceiver*/, updateUsers);
1832                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1833                    // First-install and we did a restore, so we're responsible for the
1834                    // first-launch broadcast.
1835                    if (DEBUG_BACKUP) {
1836                        Slog.i(TAG, "Post-restore of " + packageName
1837                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1838                    }
1839                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1840                }
1841
1842                // Send broadcast package appeared if forward locked/external for all users
1843                // treat asec-hosted packages like removable media on upgrade
1844                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1845                    if (DEBUG_INSTALL) {
1846                        Slog.i(TAG, "upgrading pkg " + res.pkg
1847                                + " is ASEC-hosted -> AVAILABLE");
1848                    }
1849                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1850                    ArrayList<String> pkgList = new ArrayList<>(1);
1851                    pkgList.add(packageName);
1852                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1853                }
1854            }
1855
1856            // Work that needs to happen on first install within each user
1857            if (firstUsers != null && firstUsers.length > 0) {
1858                synchronized (mPackages) {
1859                    for (int userId : firstUsers) {
1860                        // If this app is a browser and it's newly-installed for some
1861                        // users, clear any default-browser state in those users. The
1862                        // app's nature doesn't depend on the user, so we can just check
1863                        // its browser nature in any user and generalize.
1864                        if (packageIsBrowser(packageName, userId)) {
1865                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1866                        }
1867
1868                        // We may also need to apply pending (restored) runtime
1869                        // permission grants within these users.
1870                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1871                    }
1872                }
1873            }
1874
1875            // Log current value of "unknown sources" setting
1876            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1877                    getUnknownSourcesSettings());
1878
1879            // Force a gc to clear up things
1880            Runtime.getRuntime().gc();
1881
1882            // Remove the replaced package's older resources safely now
1883            // We delete after a gc for applications  on sdcard.
1884            if (res.removedInfo != null && res.removedInfo.args != null) {
1885                synchronized (mInstallLock) {
1886                    res.removedInfo.args.doPostDeleteLI(true);
1887                }
1888            }
1889
1890            if (!isEphemeral(res.pkg)) {
1891                // Notify DexManager that the package was installed for new users.
1892                // The updated users should already be indexed and the package code paths
1893                // should not change.
1894                // Don't notify the manager for ephemeral apps as they are not expected to
1895                // survive long enough to benefit of background optimizations.
1896                for (int userId : firstUsers) {
1897                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1898                    mDexManager.notifyPackageInstalled(info, userId);
1899                }
1900            }
1901        }
1902
1903        // If someone is watching installs - notify them
1904        if (installObserver != null) {
1905            try {
1906                Bundle extras = extrasForInstallResult(res);
1907                installObserver.onPackageInstalled(res.name, res.returnCode,
1908                        res.returnMsg, extras);
1909            } catch (RemoteException e) {
1910                Slog.i(TAG, "Observer no longer exists.");
1911            }
1912        }
1913    }
1914
1915    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1916            PackageParser.Package pkg) {
1917        if (pkg.parentPackage == null) {
1918            return;
1919        }
1920        if (pkg.requestedPermissions == null) {
1921            return;
1922        }
1923        final PackageSetting disabledSysParentPs = mSettings
1924                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1925        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1926                || !disabledSysParentPs.isPrivileged()
1927                || (disabledSysParentPs.childPackageNames != null
1928                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1929            return;
1930        }
1931        final int[] allUserIds = sUserManager.getUserIds();
1932        final int permCount = pkg.requestedPermissions.size();
1933        for (int i = 0; i < permCount; i++) {
1934            String permission = pkg.requestedPermissions.get(i);
1935            BasePermission bp = mSettings.mPermissions.get(permission);
1936            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1937                continue;
1938            }
1939            for (int userId : allUserIds) {
1940                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1941                        permission, userId)) {
1942                    grantRuntimePermission(pkg.packageName, permission, userId);
1943                }
1944            }
1945        }
1946    }
1947
1948    private StorageEventListener mStorageListener = new StorageEventListener() {
1949        @Override
1950        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1951            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1952                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1953                    final String volumeUuid = vol.getFsUuid();
1954
1955                    // Clean up any users or apps that were removed or recreated
1956                    // while this volume was missing
1957                    sUserManager.reconcileUsers(volumeUuid);
1958                    reconcileApps(volumeUuid);
1959
1960                    // Clean up any install sessions that expired or were
1961                    // cancelled while this volume was missing
1962                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1963
1964                    loadPrivatePackages(vol);
1965
1966                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1967                    unloadPrivatePackages(vol);
1968                }
1969            }
1970
1971            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1972                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1973                    updateExternalMediaStatus(true, false);
1974                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1975                    updateExternalMediaStatus(false, false);
1976                }
1977            }
1978        }
1979
1980        @Override
1981        public void onVolumeForgotten(String fsUuid) {
1982            if (TextUtils.isEmpty(fsUuid)) {
1983                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1984                return;
1985            }
1986
1987            // Remove any apps installed on the forgotten volume
1988            synchronized (mPackages) {
1989                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1990                for (PackageSetting ps : packages) {
1991                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1992                    deletePackageVersioned(new VersionedPackage(ps.name,
1993                            PackageManager.VERSION_CODE_HIGHEST),
1994                            new LegacyPackageDeleteObserver(null).getBinder(),
1995                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1996                    // Try very hard to release any references to this package
1997                    // so we don't risk the system server being killed due to
1998                    // open FDs
1999                    AttributeCache.instance().removePackage(ps.name);
2000                }
2001
2002                mSettings.onVolumeForgotten(fsUuid);
2003                mSettings.writeLPr();
2004            }
2005        }
2006    };
2007
2008    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2009            String[] grantedPermissions) {
2010        for (int userId : userIds) {
2011            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2012        }
2013    }
2014
2015    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2016            String[] grantedPermissions) {
2017        SettingBase sb = (SettingBase) pkg.mExtras;
2018        if (sb == null) {
2019            return;
2020        }
2021
2022        PermissionsState permissionsState = sb.getPermissionsState();
2023
2024        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2025                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2026
2027        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2028                >= Build.VERSION_CODES.M;
2029
2030        for (String permission : pkg.requestedPermissions) {
2031            final BasePermission bp;
2032            synchronized (mPackages) {
2033                bp = mSettings.mPermissions.get(permission);
2034            }
2035            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2036                    && (grantedPermissions == null
2037                           || ArrayUtils.contains(grantedPermissions, permission))) {
2038                final int flags = permissionsState.getPermissionFlags(permission, userId);
2039                if (supportsRuntimePermissions) {
2040                    // Installer cannot change immutable permissions.
2041                    if ((flags & immutableFlags) == 0) {
2042                        grantRuntimePermission(pkg.packageName, permission, userId);
2043                    }
2044                } else if (mPermissionReviewRequired) {
2045                    // In permission review mode we clear the review flag when we
2046                    // are asked to install the app with all permissions granted.
2047                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2048                        updatePermissionFlags(permission, pkg.packageName,
2049                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2050                    }
2051                }
2052            }
2053        }
2054    }
2055
2056    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2057        Bundle extras = null;
2058        switch (res.returnCode) {
2059            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2060                extras = new Bundle();
2061                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2062                        res.origPermission);
2063                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2064                        res.origPackage);
2065                break;
2066            }
2067            case PackageManager.INSTALL_SUCCEEDED: {
2068                extras = new Bundle();
2069                extras.putBoolean(Intent.EXTRA_REPLACING,
2070                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2071                break;
2072            }
2073        }
2074        return extras;
2075    }
2076
2077    void scheduleWriteSettingsLocked() {
2078        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2079            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2080        }
2081    }
2082
2083    void scheduleWritePackageListLocked(int userId) {
2084        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2085            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2086            msg.arg1 = userId;
2087            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2088        }
2089    }
2090
2091    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2092        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2093        scheduleWritePackageRestrictionsLocked(userId);
2094    }
2095
2096    void scheduleWritePackageRestrictionsLocked(int userId) {
2097        final int[] userIds = (userId == UserHandle.USER_ALL)
2098                ? sUserManager.getUserIds() : new int[]{userId};
2099        for (int nextUserId : userIds) {
2100            if (!sUserManager.exists(nextUserId)) return;
2101            mDirtyUsers.add(nextUserId);
2102            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2103                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2104            }
2105        }
2106    }
2107
2108    public static PackageManagerService main(Context context, Installer installer,
2109            boolean factoryTest, boolean onlyCore) {
2110        // Self-check for initial settings.
2111        PackageManagerServiceCompilerMapping.checkProperties();
2112
2113        PackageManagerService m = new PackageManagerService(context, installer,
2114                factoryTest, onlyCore);
2115        m.enableSystemUserPackages();
2116        ServiceManager.addService("package", m);
2117        return m;
2118    }
2119
2120    private void enableSystemUserPackages() {
2121        if (!UserManager.isSplitSystemUser()) {
2122            return;
2123        }
2124        // For system user, enable apps based on the following conditions:
2125        // - app is whitelisted or belong to one of these groups:
2126        //   -- system app which has no launcher icons
2127        //   -- system app which has INTERACT_ACROSS_USERS permission
2128        //   -- system IME app
2129        // - app is not in the blacklist
2130        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2131        Set<String> enableApps = new ArraySet<>();
2132        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2133                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2134                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2135        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2136        enableApps.addAll(wlApps);
2137        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2138                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2139        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2140        enableApps.removeAll(blApps);
2141        Log.i(TAG, "Applications installed for system user: " + enableApps);
2142        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2143                UserHandle.SYSTEM);
2144        final int allAppsSize = allAps.size();
2145        synchronized (mPackages) {
2146            for (int i = 0; i < allAppsSize; i++) {
2147                String pName = allAps.get(i);
2148                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2149                // Should not happen, but we shouldn't be failing if it does
2150                if (pkgSetting == null) {
2151                    continue;
2152                }
2153                boolean install = enableApps.contains(pName);
2154                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2155                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2156                            + " for system user");
2157                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2158                }
2159            }
2160        }
2161    }
2162
2163    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2164        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2165                Context.DISPLAY_SERVICE);
2166        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2167    }
2168
2169    /**
2170     * Requests that files preopted on a secondary system partition be copied to the data partition
2171     * if possible.  Note that the actual copying of the files is accomplished by init for security
2172     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2173     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2174     */
2175    private static void requestCopyPreoptedFiles() {
2176        final int WAIT_TIME_MS = 100;
2177        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2178        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2179            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2180            // We will wait for up to 100 seconds.
2181            final long timeStart = SystemClock.uptimeMillis();
2182            final long timeEnd = timeStart + 100 * 1000;
2183            long timeNow = timeStart;
2184            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2185                try {
2186                    Thread.sleep(WAIT_TIME_MS);
2187                } catch (InterruptedException e) {
2188                    // Do nothing
2189                }
2190                timeNow = SystemClock.uptimeMillis();
2191                if (timeNow > timeEnd) {
2192                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2193                    Slog.wtf(TAG, "cppreopt did not finish!");
2194                    break;
2195                }
2196            }
2197
2198            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2199        }
2200    }
2201
2202    public PackageManagerService(Context context, Installer installer,
2203            boolean factoryTest, boolean onlyCore) {
2204        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2205        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2206                SystemClock.uptimeMillis());
2207
2208        if (mSdkVersion <= 0) {
2209            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2210        }
2211
2212        mContext = context;
2213
2214        mPermissionReviewRequired = context.getResources().getBoolean(
2215                R.bool.config_permissionReviewRequired);
2216
2217        mFactoryTest = factoryTest;
2218        mOnlyCore = onlyCore;
2219        mMetrics = new DisplayMetrics();
2220        mSettings = new Settings(mPackages);
2221        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2222                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2223        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2224                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2225        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2226                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2227        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2228                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2229        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2230                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2231        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2232                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2233
2234        String separateProcesses = SystemProperties.get("debug.separate_processes");
2235        if (separateProcesses != null && separateProcesses.length() > 0) {
2236            if ("*".equals(separateProcesses)) {
2237                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2238                mSeparateProcesses = null;
2239                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2240            } else {
2241                mDefParseFlags = 0;
2242                mSeparateProcesses = separateProcesses.split(",");
2243                Slog.w(TAG, "Running with debug.separate_processes: "
2244                        + separateProcesses);
2245            }
2246        } else {
2247            mDefParseFlags = 0;
2248            mSeparateProcesses = null;
2249        }
2250
2251        mInstaller = installer;
2252        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2253                "*dexopt*");
2254        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2255        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2256
2257        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2258                FgThread.get().getLooper());
2259
2260        getDefaultDisplayMetrics(context, mMetrics);
2261
2262        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2263        SystemConfig systemConfig = SystemConfig.getInstance();
2264        mGlobalGids = systemConfig.getGlobalGids();
2265        mSystemPermissions = systemConfig.getSystemPermissions();
2266        mAvailableFeatures = systemConfig.getAvailableFeatures();
2267        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2268
2269        mProtectedPackages = new ProtectedPackages(mContext);
2270
2271        synchronized (mInstallLock) {
2272        // writer
2273        synchronized (mPackages) {
2274            mHandlerThread = new ServiceThread(TAG,
2275                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2276            mHandlerThread.start();
2277            mHandler = new PackageHandler(mHandlerThread.getLooper());
2278            mProcessLoggingHandler = new ProcessLoggingHandler();
2279            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2280
2281            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2282            mInstantAppRegistry = new InstantAppRegistry(this);
2283
2284            File dataDir = Environment.getDataDirectory();
2285            mAppInstallDir = new File(dataDir, "app");
2286            mAppLib32InstallDir = new File(dataDir, "app-lib");
2287            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2288            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2289            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2290            sUserManager = new UserManagerService(context, this,
2291                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2292
2293            // Propagate permission configuration in to package manager.
2294            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2295                    = systemConfig.getPermissions();
2296            for (int i=0; i<permConfig.size(); i++) {
2297                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2298                BasePermission bp = mSettings.mPermissions.get(perm.name);
2299                if (bp == null) {
2300                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2301                    mSettings.mPermissions.put(perm.name, bp);
2302                }
2303                if (perm.gids != null) {
2304                    bp.setGids(perm.gids, perm.perUser);
2305                }
2306            }
2307
2308            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2309            final int builtInLibCount = libConfig.size();
2310            for (int i = 0; i < builtInLibCount; i++) {
2311                String name = libConfig.keyAt(i);
2312                String path = libConfig.valueAt(i);
2313                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2314                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2315            }
2316
2317            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2318
2319            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2320            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2321            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2322
2323            // Clean up orphaned packages for which the code path doesn't exist
2324            // and they are an update to a system app - caused by bug/32321269
2325            final int packageSettingCount = mSettings.mPackages.size();
2326            for (int i = packageSettingCount - 1; i >= 0; i--) {
2327                PackageSetting ps = mSettings.mPackages.valueAt(i);
2328                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2329                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2330                    mSettings.mPackages.removeAt(i);
2331                    mSettings.enableSystemPackageLPw(ps.name);
2332                }
2333            }
2334
2335            if (mFirstBoot) {
2336                requestCopyPreoptedFiles();
2337            }
2338
2339            String customResolverActivity = Resources.getSystem().getString(
2340                    R.string.config_customResolverActivity);
2341            if (TextUtils.isEmpty(customResolverActivity)) {
2342                customResolverActivity = null;
2343            } else {
2344                mCustomResolverComponentName = ComponentName.unflattenFromString(
2345                        customResolverActivity);
2346            }
2347
2348            long startTime = SystemClock.uptimeMillis();
2349
2350            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2351                    startTime);
2352
2353            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2354            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2355
2356            if (bootClassPath == null) {
2357                Slog.w(TAG, "No BOOTCLASSPATH found!");
2358            }
2359
2360            if (systemServerClassPath == null) {
2361                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2362            }
2363
2364            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2365            final String[] dexCodeInstructionSets =
2366                    getDexCodeInstructionSets(
2367                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2368
2369            /**
2370             * Ensure all external libraries have had dexopt run on them.
2371             */
2372            if (mSharedLibraries.size() > 0) {
2373                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2374                // NOTE: For now, we're compiling these system "shared libraries"
2375                // (and framework jars) into all available architectures. It's possible
2376                // to compile them only when we come across an app that uses them (there's
2377                // already logic for that in scanPackageLI) but that adds some complexity.
2378                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2379                    final int libCount = mSharedLibraries.size();
2380                    for (int i = 0; i < libCount; i++) {
2381                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2382                        final int versionCount = versionedLib.size();
2383                        for (int j = 0; j < versionCount; j++) {
2384                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2385                            final String libPath = libEntry.path != null
2386                                    ? libEntry.path : libEntry.apk;
2387                            if (libPath == null) {
2388                                continue;
2389                            }
2390                            try {
2391                                // Shared libraries do not have profiles so we perform a full
2392                                // AOT compilation (if needed).
2393                                int dexoptNeeded = DexFile.getDexOptNeeded(
2394                                        libPath, dexCodeInstructionSet,
2395                                        getCompilerFilterForReason(REASON_SHARED_APK),
2396                                        false /* newProfile */);
2397                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2398                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2399                                            dexCodeInstructionSet, dexoptNeeded, null,
2400                                            DEXOPT_PUBLIC,
2401                                            getCompilerFilterForReason(REASON_SHARED_APK),
2402                                            StorageManager.UUID_PRIVATE_INTERNAL,
2403                                            SKIP_SHARED_LIBRARY_CHECK);
2404                                }
2405                            } catch (FileNotFoundException e) {
2406                                Slog.w(TAG, "Library not found: " + libPath);
2407                            } catch (IOException | InstallerException e) {
2408                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2409                                        + e.getMessage());
2410                            }
2411                        }
2412                    }
2413                }
2414                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2415            }
2416
2417            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2418
2419            final VersionInfo ver = mSettings.getInternalVersion();
2420            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2421
2422            // when upgrading from pre-M, promote system app permissions from install to runtime
2423            mPromoteSystemApps =
2424                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2425
2426            // When upgrading from pre-N, we need to handle package extraction like first boot,
2427            // as there is no profiling data available.
2428            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2429
2430            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2431
2432            // save off the names of pre-existing system packages prior to scanning; we don't
2433            // want to automatically grant runtime permissions for new system apps
2434            if (mPromoteSystemApps) {
2435                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2436                while (pkgSettingIter.hasNext()) {
2437                    PackageSetting ps = pkgSettingIter.next();
2438                    if (isSystemApp(ps)) {
2439                        mExistingSystemPackages.add(ps.name);
2440                    }
2441                }
2442            }
2443
2444            mCacheDir = preparePackageParserCache(mIsUpgrade);
2445
2446            // Set flag to monitor and not change apk file paths when
2447            // scanning install directories.
2448            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2449
2450            if (mIsUpgrade || mFirstBoot) {
2451                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2452            }
2453
2454            // Collect vendor overlay packages. (Do this before scanning any apps.)
2455            // For security and version matching reason, only consider
2456            // overlay packages if they reside in the right directory.
2457            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2458            if (overlayThemeDir.isEmpty()) {
2459                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2460            }
2461            if (!overlayThemeDir.isEmpty()) {
2462                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2463                        | PackageParser.PARSE_IS_SYSTEM
2464                        | PackageParser.PARSE_IS_SYSTEM_DIR
2465                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2466            }
2467            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2468                    | PackageParser.PARSE_IS_SYSTEM
2469                    | PackageParser.PARSE_IS_SYSTEM_DIR
2470                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2471
2472            // Find base frameworks (resource packages without code).
2473            scanDirTracedLI(frameworkDir, mDefParseFlags
2474                    | PackageParser.PARSE_IS_SYSTEM
2475                    | PackageParser.PARSE_IS_SYSTEM_DIR
2476                    | PackageParser.PARSE_IS_PRIVILEGED,
2477                    scanFlags | SCAN_NO_DEX, 0);
2478
2479            // Collected privileged system packages.
2480            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2481            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2482                    | PackageParser.PARSE_IS_SYSTEM
2483                    | PackageParser.PARSE_IS_SYSTEM_DIR
2484                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2485
2486            // Collect ordinary system packages.
2487            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2488            scanDirTracedLI(systemAppDir, mDefParseFlags
2489                    | PackageParser.PARSE_IS_SYSTEM
2490                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2491
2492            // Collect all vendor packages.
2493            File vendorAppDir = new File("/vendor/app");
2494            try {
2495                vendorAppDir = vendorAppDir.getCanonicalFile();
2496            } catch (IOException e) {
2497                // failed to look up canonical path, continue with original one
2498            }
2499            scanDirTracedLI(vendorAppDir, mDefParseFlags
2500                    | PackageParser.PARSE_IS_SYSTEM
2501                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2502
2503            // Collect all OEM packages.
2504            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2505            scanDirTracedLI(oemAppDir, mDefParseFlags
2506                    | PackageParser.PARSE_IS_SYSTEM
2507                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2508
2509            // Prune any system packages that no longer exist.
2510            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2511            if (!mOnlyCore) {
2512                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2513                while (psit.hasNext()) {
2514                    PackageSetting ps = psit.next();
2515
2516                    /*
2517                     * If this is not a system app, it can't be a
2518                     * disable system app.
2519                     */
2520                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2521                        continue;
2522                    }
2523
2524                    /*
2525                     * If the package is scanned, it's not erased.
2526                     */
2527                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2528                    if (scannedPkg != null) {
2529                        /*
2530                         * If the system app is both scanned and in the
2531                         * disabled packages list, then it must have been
2532                         * added via OTA. Remove it from the currently
2533                         * scanned package so the previously user-installed
2534                         * application can be scanned.
2535                         */
2536                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2537                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2538                                    + ps.name + "; removing system app.  Last known codePath="
2539                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2540                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2541                                    + scannedPkg.mVersionCode);
2542                            removePackageLI(scannedPkg, true);
2543                            mExpectingBetter.put(ps.name, ps.codePath);
2544                        }
2545
2546                        continue;
2547                    }
2548
2549                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2550                        psit.remove();
2551                        logCriticalInfo(Log.WARN, "System package " + ps.name
2552                                + " no longer exists; it's data will be wiped");
2553                        // Actual deletion of code and data will be handled by later
2554                        // reconciliation step
2555                    } else {
2556                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2557                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2558                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2559                        }
2560                    }
2561                }
2562            }
2563
2564            //look for any incomplete package installations
2565            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2566            for (int i = 0; i < deletePkgsList.size(); i++) {
2567                // Actual deletion of code and data will be handled by later
2568                // reconciliation step
2569                final String packageName = deletePkgsList.get(i).name;
2570                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2571                synchronized (mPackages) {
2572                    mSettings.removePackageLPw(packageName);
2573                }
2574            }
2575
2576            //delete tmp files
2577            deleteTempPackageFiles();
2578
2579            // Remove any shared userIDs that have no associated packages
2580            mSettings.pruneSharedUsersLPw();
2581
2582            if (!mOnlyCore) {
2583                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2584                        SystemClock.uptimeMillis());
2585                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2586
2587                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2588                        | PackageParser.PARSE_FORWARD_LOCK,
2589                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2590
2591                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2592                        | PackageParser.PARSE_IS_EPHEMERAL,
2593                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2594
2595                /**
2596                 * Remove disable package settings for any updated system
2597                 * apps that were removed via an OTA. If they're not a
2598                 * previously-updated app, remove them completely.
2599                 * Otherwise, just revoke their system-level permissions.
2600                 */
2601                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2602                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2603                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2604
2605                    String msg;
2606                    if (deletedPkg == null) {
2607                        msg = "Updated system package " + deletedAppName
2608                                + " no longer exists; it's data will be wiped";
2609                        // Actual deletion of code and data will be handled by later
2610                        // reconciliation step
2611                    } else {
2612                        msg = "Updated system app + " + deletedAppName
2613                                + " no longer present; removing system privileges for "
2614                                + deletedAppName;
2615
2616                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2617
2618                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2619                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2620                    }
2621                    logCriticalInfo(Log.WARN, msg);
2622                }
2623
2624                /**
2625                 * Make sure all system apps that we expected to appear on
2626                 * the userdata partition actually showed up. If they never
2627                 * appeared, crawl back and revive the system version.
2628                 */
2629                for (int i = 0; i < mExpectingBetter.size(); i++) {
2630                    final String packageName = mExpectingBetter.keyAt(i);
2631                    if (!mPackages.containsKey(packageName)) {
2632                        final File scanFile = mExpectingBetter.valueAt(i);
2633
2634                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2635                                + " but never showed up; reverting to system");
2636
2637                        int reparseFlags = mDefParseFlags;
2638                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2639                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2640                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2641                                    | PackageParser.PARSE_IS_PRIVILEGED;
2642                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2643                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2644                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2645                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2646                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2647                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2648                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2649                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2650                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2651                        } else {
2652                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2653                            continue;
2654                        }
2655
2656                        mSettings.enableSystemPackageLPw(packageName);
2657
2658                        try {
2659                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2660                        } catch (PackageManagerException e) {
2661                            Slog.e(TAG, "Failed to parse original system package: "
2662                                    + e.getMessage());
2663                        }
2664                    }
2665                }
2666            }
2667            mExpectingBetter.clear();
2668
2669            // Resolve the storage manager.
2670            mStorageManagerPackage = getStorageManagerPackageName();
2671
2672            // Resolve protected action filters. Only the setup wizard is allowed to
2673            // have a high priority filter for these actions.
2674            mSetupWizardPackage = getSetupWizardPackageName();
2675            if (mProtectedFilters.size() > 0) {
2676                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2677                    Slog.i(TAG, "No setup wizard;"
2678                        + " All protected intents capped to priority 0");
2679                }
2680                for (ActivityIntentInfo filter : mProtectedFilters) {
2681                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2682                        if (DEBUG_FILTERS) {
2683                            Slog.i(TAG, "Found setup wizard;"
2684                                + " allow priority " + filter.getPriority() + ";"
2685                                + " package: " + filter.activity.info.packageName
2686                                + " activity: " + filter.activity.className
2687                                + " priority: " + filter.getPriority());
2688                        }
2689                        // skip setup wizard; allow it to keep the high priority filter
2690                        continue;
2691                    }
2692                    Slog.w(TAG, "Protected action; cap priority to 0;"
2693                            + " package: " + filter.activity.info.packageName
2694                            + " activity: " + filter.activity.className
2695                            + " origPrio: " + filter.getPriority());
2696                    filter.setPriority(0);
2697                }
2698            }
2699            mDeferProtectedFilters = false;
2700            mProtectedFilters.clear();
2701
2702            // Now that we know all of the shared libraries, update all clients to have
2703            // the correct library paths.
2704            updateAllSharedLibrariesLPw(null);
2705
2706            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2707                // NOTE: We ignore potential failures here during a system scan (like
2708                // the rest of the commands above) because there's precious little we
2709                // can do about it. A settings error is reported, though.
2710                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2711            }
2712
2713            // Now that we know all the packages we are keeping,
2714            // read and update their last usage times.
2715            mPackageUsage.read(mPackages);
2716            mCompilerStats.read();
2717
2718            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2719                    SystemClock.uptimeMillis());
2720            Slog.i(TAG, "Time to scan packages: "
2721                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2722                    + " seconds");
2723
2724            // If the platform SDK has changed since the last time we booted,
2725            // we need to re-grant app permission to catch any new ones that
2726            // appear.  This is really a hack, and means that apps can in some
2727            // cases get permissions that the user didn't initially explicitly
2728            // allow...  it would be nice to have some better way to handle
2729            // this situation.
2730            int updateFlags = UPDATE_PERMISSIONS_ALL;
2731            if (ver.sdkVersion != mSdkVersion) {
2732                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2733                        + mSdkVersion + "; regranting permissions for internal storage");
2734                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2735            }
2736            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2737            ver.sdkVersion = mSdkVersion;
2738
2739            // If this is the first boot or an update from pre-M, and it is a normal
2740            // boot, then we need to initialize the default preferred apps across
2741            // all defined users.
2742            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2743                for (UserInfo user : sUserManager.getUsers(true)) {
2744                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2745                    applyFactoryDefaultBrowserLPw(user.id);
2746                    primeDomainVerificationsLPw(user.id);
2747                }
2748            }
2749
2750            // Prepare storage for system user really early during boot,
2751            // since core system apps like SettingsProvider and SystemUI
2752            // can't wait for user to start
2753            final int storageFlags;
2754            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2755                storageFlags = StorageManager.FLAG_STORAGE_DE;
2756            } else {
2757                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2758            }
2759            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2760                    storageFlags, true /* migrateAppData */);
2761
2762            // If this is first boot after an OTA, and a normal boot, then
2763            // we need to clear code cache directories.
2764            // Note that we do *not* clear the application profiles. These remain valid
2765            // across OTAs and are used to drive profile verification (post OTA) and
2766            // profile compilation (without waiting to collect a fresh set of profiles).
2767            if (mIsUpgrade && !onlyCore) {
2768                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2769                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2770                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2771                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2772                        // No apps are running this early, so no need to freeze
2773                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2774                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2775                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2776                    }
2777                }
2778                ver.fingerprint = Build.FINGERPRINT;
2779            }
2780
2781            checkDefaultBrowser();
2782
2783            // clear only after permissions and other defaults have been updated
2784            mExistingSystemPackages.clear();
2785            mPromoteSystemApps = false;
2786
2787            // All the changes are done during package scanning.
2788            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2789
2790            // can downgrade to reader
2791            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2792            mSettings.writeLPr();
2793            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2794
2795            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2796            // early on (before the package manager declares itself as early) because other
2797            // components in the system server might ask for package contexts for these apps.
2798            //
2799            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2800            // (i.e, that the data partition is unavailable).
2801            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2802                long start = System.nanoTime();
2803                List<PackageParser.Package> coreApps = new ArrayList<>();
2804                for (PackageParser.Package pkg : mPackages.values()) {
2805                    if (pkg.coreApp) {
2806                        coreApps.add(pkg);
2807                    }
2808                }
2809
2810                int[] stats = performDexOptUpgrade(coreApps, false,
2811                        getCompilerFilterForReason(REASON_CORE_APP));
2812
2813                final int elapsedTimeSeconds =
2814                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2815                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2816
2817                if (DEBUG_DEXOPT) {
2818                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2819                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2820                }
2821
2822
2823                // TODO: Should we log these stats to tron too ?
2824                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2825                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2826                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2827                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2828            }
2829
2830            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2831                    SystemClock.uptimeMillis());
2832
2833            if (!mOnlyCore) {
2834                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2835                mRequiredInstallerPackage = getRequiredInstallerLPr();
2836                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2837                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2838                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2839                        mIntentFilterVerifierComponent);
2840                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2841                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2842                        SharedLibraryInfo.VERSION_UNDEFINED);
2843                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2844                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2845                        SharedLibraryInfo.VERSION_UNDEFINED);
2846            } else {
2847                mRequiredVerifierPackage = null;
2848                mRequiredInstallerPackage = null;
2849                mRequiredUninstallerPackage = null;
2850                mIntentFilterVerifierComponent = null;
2851                mIntentFilterVerifier = null;
2852                mServicesSystemSharedLibraryPackageName = null;
2853                mSharedSystemSharedLibraryPackageName = null;
2854            }
2855
2856            mInstallerService = new PackageInstallerService(context, this);
2857
2858            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2859            if (ephemeralResolverComponent != null) {
2860                if (DEBUG_EPHEMERAL) {
2861                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2862                }
2863                mEphemeralResolverConnection =
2864                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2865            } else {
2866                mEphemeralResolverConnection = null;
2867            }
2868            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2869            if (mEphemeralInstallerComponent != null) {
2870                if (DEBUG_EPHEMERAL) {
2871                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2872                }
2873                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2874            }
2875
2876            // Read and update the usage of dex files.
2877            // Do this at the end of PM init so that all the packages have their
2878            // data directory reconciled.
2879            // At this point we know the code paths of the packages, so we can validate
2880            // the disk file and build the internal cache.
2881            // The usage file is expected to be small so loading and verifying it
2882            // should take a fairly small time compare to the other activities (e.g. package
2883            // scanning).
2884            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2885            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2886            for (int userId : currentUserIds) {
2887                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2888            }
2889            mDexManager.load(userPackages);
2890        } // synchronized (mPackages)
2891        } // synchronized (mInstallLock)
2892
2893        // Now after opening every single application zip, make sure they
2894        // are all flushed.  Not really needed, but keeps things nice and
2895        // tidy.
2896        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2897        Runtime.getRuntime().gc();
2898        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2899
2900        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2901        FallbackCategoryProvider.loadFallbacks();
2902        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2903
2904        // The initial scanning above does many calls into installd while
2905        // holding the mPackages lock, but we're mostly interested in yelling
2906        // once we have a booted system.
2907        mInstaller.setWarnIfHeld(mPackages);
2908
2909        // Expose private service for system components to use.
2910        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2911        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2912    }
2913
2914    private static File preparePackageParserCache(boolean isUpgrade) {
2915        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2916            return null;
2917        }
2918
2919        // Disable package parsing on eng builds to allow for faster incremental development.
2920        if ("eng".equals(Build.TYPE)) {
2921            return null;
2922        }
2923
2924        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2925            Slog.i(TAG, "Disabling package parser cache due to system property.");
2926            return null;
2927        }
2928
2929        // The base directory for the package parser cache lives under /data/system/.
2930        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2931                "package_cache");
2932        if (cacheBaseDir == null) {
2933            return null;
2934        }
2935
2936        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2937        // This also serves to "GC" unused entries when the package cache version changes (which
2938        // can only happen during upgrades).
2939        if (isUpgrade) {
2940            FileUtils.deleteContents(cacheBaseDir);
2941        }
2942
2943
2944        // Return the versioned package cache directory. This is something like
2945        // "/data/system/package_cache/1"
2946        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2947
2948        // The following is a workaround to aid development on non-numbered userdebug
2949        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2950        // the system partition is newer.
2951        //
2952        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2953        // that starts with "eng." to signify that this is an engineering build and not
2954        // destined for release.
2955        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2956            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2957
2958            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2959            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2960            // in general and should not be used for production changes. In this specific case,
2961            // we know that they will work.
2962            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2963            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2964                FileUtils.deleteContents(cacheBaseDir);
2965                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2966            }
2967        }
2968
2969        return cacheDir;
2970    }
2971
2972    @Override
2973    public boolean isFirstBoot() {
2974        return mFirstBoot;
2975    }
2976
2977    @Override
2978    public boolean isOnlyCoreApps() {
2979        return mOnlyCore;
2980    }
2981
2982    @Override
2983    public boolean isUpgrade() {
2984        return mIsUpgrade;
2985    }
2986
2987    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2988        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2989
2990        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2991                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2992                UserHandle.USER_SYSTEM);
2993        if (matches.size() == 1) {
2994            return matches.get(0).getComponentInfo().packageName;
2995        } else if (matches.size() == 0) {
2996            Log.e(TAG, "There should probably be a verifier, but, none were found");
2997            return null;
2998        }
2999        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3000    }
3001
3002    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3003        synchronized (mPackages) {
3004            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3005            if (libraryEntry == null) {
3006                throw new IllegalStateException("Missing required shared library:" + name);
3007            }
3008            return libraryEntry.apk;
3009        }
3010    }
3011
3012    private @NonNull String getRequiredInstallerLPr() {
3013        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3014        intent.addCategory(Intent.CATEGORY_DEFAULT);
3015        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3016
3017        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3018                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3019                UserHandle.USER_SYSTEM);
3020        if (matches.size() == 1) {
3021            ResolveInfo resolveInfo = matches.get(0);
3022            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3023                throw new RuntimeException("The installer must be a privileged app");
3024            }
3025            return matches.get(0).getComponentInfo().packageName;
3026        } else {
3027            throw new RuntimeException("There must be exactly one installer; found " + matches);
3028        }
3029    }
3030
3031    private @NonNull String getRequiredUninstallerLPr() {
3032        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3033        intent.addCategory(Intent.CATEGORY_DEFAULT);
3034        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3035
3036        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3037                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3038                UserHandle.USER_SYSTEM);
3039        if (resolveInfo == null ||
3040                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3041            throw new RuntimeException("There must be exactly one uninstaller; found "
3042                    + resolveInfo);
3043        }
3044        return resolveInfo.getComponentInfo().packageName;
3045    }
3046
3047    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3048        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3049
3050        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3051                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3052                UserHandle.USER_SYSTEM);
3053        ResolveInfo best = null;
3054        final int N = matches.size();
3055        for (int i = 0; i < N; i++) {
3056            final ResolveInfo cur = matches.get(i);
3057            final String packageName = cur.getComponentInfo().packageName;
3058            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3059                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3060                continue;
3061            }
3062
3063            if (best == null || cur.priority > best.priority) {
3064                best = cur;
3065            }
3066        }
3067
3068        if (best != null) {
3069            return best.getComponentInfo().getComponentName();
3070        } else {
3071            throw new RuntimeException("There must be at least one intent filter verifier");
3072        }
3073    }
3074
3075    private @Nullable ComponentName getEphemeralResolverLPr() {
3076        final String[] packageArray =
3077                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3078        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3079            if (DEBUG_EPHEMERAL) {
3080                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3081            }
3082            return null;
3083        }
3084
3085        final int resolveFlags =
3086                MATCH_DIRECT_BOOT_AWARE
3087                | MATCH_DIRECT_BOOT_UNAWARE
3088                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3089        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3090        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3091                resolveFlags, UserHandle.USER_SYSTEM);
3092
3093        final int N = resolvers.size();
3094        if (N == 0) {
3095            if (DEBUG_EPHEMERAL) {
3096                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3097            }
3098            return null;
3099        }
3100
3101        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3102        for (int i = 0; i < N; i++) {
3103            final ResolveInfo info = resolvers.get(i);
3104
3105            if (info.serviceInfo == null) {
3106                continue;
3107            }
3108
3109            final String packageName = info.serviceInfo.packageName;
3110            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3111                if (DEBUG_EPHEMERAL) {
3112                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3113                            + " pkg: " + packageName + ", info:" + info);
3114                }
3115                continue;
3116            }
3117
3118            if (DEBUG_EPHEMERAL) {
3119                Slog.v(TAG, "Ephemeral resolver found;"
3120                        + " pkg: " + packageName + ", info:" + info);
3121            }
3122            return new ComponentName(packageName, info.serviceInfo.name);
3123        }
3124        if (DEBUG_EPHEMERAL) {
3125            Slog.v(TAG, "Ephemeral resolver NOT found");
3126        }
3127        return null;
3128    }
3129
3130    private @Nullable ComponentName getEphemeralInstallerLPr() {
3131        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3132        intent.addCategory(Intent.CATEGORY_DEFAULT);
3133        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3134
3135        final int resolveFlags =
3136                MATCH_DIRECT_BOOT_AWARE
3137                | MATCH_DIRECT_BOOT_UNAWARE
3138                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3139        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3140                resolveFlags, UserHandle.USER_SYSTEM);
3141        Iterator<ResolveInfo> iter = matches.iterator();
3142        while (iter.hasNext()) {
3143            final ResolveInfo rInfo = iter.next();
3144            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3145            if (ps != null) {
3146                final PermissionsState permissionsState = ps.getPermissionsState();
3147                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3148                    continue;
3149                }
3150            }
3151            iter.remove();
3152        }
3153        if (matches.size() == 0) {
3154            return null;
3155        } else if (matches.size() == 1) {
3156            return matches.get(0).getComponentInfo().getComponentName();
3157        } else {
3158            throw new RuntimeException(
3159                    "There must be at most one ephemeral installer; found " + matches);
3160        }
3161    }
3162
3163    private void primeDomainVerificationsLPw(int userId) {
3164        if (DEBUG_DOMAIN_VERIFICATION) {
3165            Slog.d(TAG, "Priming domain verifications in user " + userId);
3166        }
3167
3168        SystemConfig systemConfig = SystemConfig.getInstance();
3169        ArraySet<String> packages = systemConfig.getLinkedApps();
3170
3171        for (String packageName : packages) {
3172            PackageParser.Package pkg = mPackages.get(packageName);
3173            if (pkg != null) {
3174                if (!pkg.isSystemApp()) {
3175                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3176                    continue;
3177                }
3178
3179                ArraySet<String> domains = null;
3180                for (PackageParser.Activity a : pkg.activities) {
3181                    for (ActivityIntentInfo filter : a.intents) {
3182                        if (hasValidDomains(filter)) {
3183                            if (domains == null) {
3184                                domains = new ArraySet<String>();
3185                            }
3186                            domains.addAll(filter.getHostsList());
3187                        }
3188                    }
3189                }
3190
3191                if (domains != null && domains.size() > 0) {
3192                    if (DEBUG_DOMAIN_VERIFICATION) {
3193                        Slog.v(TAG, "      + " + packageName);
3194                    }
3195                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3196                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3197                    // and then 'always' in the per-user state actually used for intent resolution.
3198                    final IntentFilterVerificationInfo ivi;
3199                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3200                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3201                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3202                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3203                } else {
3204                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3205                            + "' does not handle web links");
3206                }
3207            } else {
3208                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3209            }
3210        }
3211
3212        scheduleWritePackageRestrictionsLocked(userId);
3213        scheduleWriteSettingsLocked();
3214    }
3215
3216    private void applyFactoryDefaultBrowserLPw(int userId) {
3217        // The default browser app's package name is stored in a string resource,
3218        // with a product-specific overlay used for vendor customization.
3219        String browserPkg = mContext.getResources().getString(
3220                com.android.internal.R.string.default_browser);
3221        if (!TextUtils.isEmpty(browserPkg)) {
3222            // non-empty string => required to be a known package
3223            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3224            if (ps == null) {
3225                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3226                browserPkg = null;
3227            } else {
3228                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3229            }
3230        }
3231
3232        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3233        // default.  If there's more than one, just leave everything alone.
3234        if (browserPkg == null) {
3235            calculateDefaultBrowserLPw(userId);
3236        }
3237    }
3238
3239    private void calculateDefaultBrowserLPw(int userId) {
3240        List<String> allBrowsers = resolveAllBrowserApps(userId);
3241        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3242        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3243    }
3244
3245    private List<String> resolveAllBrowserApps(int userId) {
3246        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3247        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3248                PackageManager.MATCH_ALL, userId);
3249
3250        final int count = list.size();
3251        List<String> result = new ArrayList<String>(count);
3252        for (int i=0; i<count; i++) {
3253            ResolveInfo info = list.get(i);
3254            if (info.activityInfo == null
3255                    || !info.handleAllWebDataURI
3256                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3257                    || result.contains(info.activityInfo.packageName)) {
3258                continue;
3259            }
3260            result.add(info.activityInfo.packageName);
3261        }
3262
3263        return result;
3264    }
3265
3266    private boolean packageIsBrowser(String packageName, int userId) {
3267        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3268                PackageManager.MATCH_ALL, userId);
3269        final int N = list.size();
3270        for (int i = 0; i < N; i++) {
3271            ResolveInfo info = list.get(i);
3272            if (packageName.equals(info.activityInfo.packageName)) {
3273                return true;
3274            }
3275        }
3276        return false;
3277    }
3278
3279    private void checkDefaultBrowser() {
3280        final int myUserId = UserHandle.myUserId();
3281        final String packageName = getDefaultBrowserPackageName(myUserId);
3282        if (packageName != null) {
3283            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3284            if (info == null) {
3285                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3286                synchronized (mPackages) {
3287                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3288                }
3289            }
3290        }
3291    }
3292
3293    @Override
3294    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3295            throws RemoteException {
3296        try {
3297            return super.onTransact(code, data, reply, flags);
3298        } catch (RuntimeException e) {
3299            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3300                Slog.wtf(TAG, "Package Manager Crash", e);
3301            }
3302            throw e;
3303        }
3304    }
3305
3306    static int[] appendInts(int[] cur, int[] add) {
3307        if (add == null) return cur;
3308        if (cur == null) return add;
3309        final int N = add.length;
3310        for (int i=0; i<N; i++) {
3311            cur = appendInt(cur, add[i]);
3312        }
3313        return cur;
3314    }
3315
3316    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3317        if (!sUserManager.exists(userId)) return null;
3318        if (ps == null) {
3319            return null;
3320        }
3321        final PackageParser.Package p = ps.pkg;
3322        if (p == null) {
3323            return null;
3324        }
3325        // Filter out ephemeral app metadata:
3326        //   * The system/shell/root can see metadata for any app
3327        //   * An installed app can see metadata for 1) other installed apps
3328        //     and 2) ephemeral apps that have explicitly interacted with it
3329        //   * Ephemeral apps can only see their own metadata
3330        //   * Holding a signature permission allows seeing instant apps
3331        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3332        if (callingAppId != Process.SYSTEM_UID
3333                && callingAppId != Process.SHELL_UID
3334                && callingAppId != Process.ROOT_UID
3335                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3336                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3337            final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid());
3338            if (ephemeralPackageName != null) {
3339                // ephemeral apps can only get information on themselves
3340                if (!ephemeralPackageName.equals(p.packageName)) {
3341                    return null;
3342                }
3343            } else {
3344                if (p.applicationInfo.isInstantApp()) {
3345                    // only get access to the ephemeral app if we've been granted access
3346                    if (!mInstantAppRegistry.isInstantAccessGranted(
3347                            userId, callingAppId, ps.appId)) {
3348                        return null;
3349                    }
3350                }
3351            }
3352        }
3353
3354        final PermissionsState permissionsState = ps.getPermissionsState();
3355
3356        // Compute GIDs only if requested
3357        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3358                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3359        // Compute granted permissions only if package has requested permissions
3360        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3361                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3362        final PackageUserState state = ps.readUserState(userId);
3363
3364        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3365                && ps.isSystem()) {
3366            flags |= MATCH_ANY_USER;
3367        }
3368
3369        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3370                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3371
3372        if (packageInfo == null) {
3373            return null;
3374        }
3375
3376        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3377                resolveExternalPackageNameLPr(p);
3378
3379        return packageInfo;
3380    }
3381
3382    @Override
3383    public void checkPackageStartable(String packageName, int userId) {
3384        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3385
3386        synchronized (mPackages) {
3387            final PackageSetting ps = mSettings.mPackages.get(packageName);
3388            if (ps == null) {
3389                throw new SecurityException("Package " + packageName + " was not found!");
3390            }
3391
3392            if (!ps.getInstalled(userId)) {
3393                throw new SecurityException(
3394                        "Package " + packageName + " was not installed for user " + userId + "!");
3395            }
3396
3397            if (mSafeMode && !ps.isSystem()) {
3398                throw new SecurityException("Package " + packageName + " not a system app!");
3399            }
3400
3401            if (mFrozenPackages.contains(packageName)) {
3402                throw new SecurityException("Package " + packageName + " is currently frozen!");
3403            }
3404
3405            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3406                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3407                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3408            }
3409        }
3410    }
3411
3412    @Override
3413    public boolean isPackageAvailable(String packageName, int userId) {
3414        if (!sUserManager.exists(userId)) return false;
3415        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3416                false /* requireFullPermission */, false /* checkShell */, "is package available");
3417        synchronized (mPackages) {
3418            PackageParser.Package p = mPackages.get(packageName);
3419            if (p != null) {
3420                final PackageSetting ps = (PackageSetting) p.mExtras;
3421                if (ps != null) {
3422                    final PackageUserState state = ps.readUserState(userId);
3423                    if (state != null) {
3424                        return PackageParser.isAvailable(state);
3425                    }
3426                }
3427            }
3428        }
3429        return false;
3430    }
3431
3432    @Override
3433    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3434        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3435                flags, userId);
3436    }
3437
3438    @Override
3439    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3440            int flags, int userId) {
3441        return getPackageInfoInternal(versionedPackage.getPackageName(),
3442                // TODO: We will change version code to long, so in the new API it is long
3443                (int) versionedPackage.getVersionCode(), flags, userId);
3444    }
3445
3446    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3447            int flags, int userId) {
3448        if (!sUserManager.exists(userId)) return null;
3449        flags = updateFlagsForPackage(flags, userId, packageName);
3450        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3451                false /* requireFullPermission */, false /* checkShell */, "get package info");
3452
3453        // reader
3454        synchronized (mPackages) {
3455            // Normalize package name to handle renamed packages and static libs
3456            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3457
3458            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3459            if (matchFactoryOnly) {
3460                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3461                if (ps != null) {
3462                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3463                        return null;
3464                    }
3465                    return generatePackageInfo(ps, flags, userId);
3466                }
3467            }
3468
3469            PackageParser.Package p = mPackages.get(packageName);
3470            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3471                return null;
3472            }
3473            if (DEBUG_PACKAGE_INFO)
3474                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3475            if (p != null) {
3476                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3477                        Binder.getCallingUid(), userId)) {
3478                    return null;
3479                }
3480                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3481            }
3482            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3483                final PackageSetting ps = mSettings.mPackages.get(packageName);
3484                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3485                    return null;
3486                }
3487                return generatePackageInfo(ps, flags, userId);
3488            }
3489        }
3490        return null;
3491    }
3492
3493
3494    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3495        // System/shell/root get to see all static libs
3496        final int appId = UserHandle.getAppId(uid);
3497        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3498                || appId == Process.ROOT_UID) {
3499            return false;
3500        }
3501
3502        // No package means no static lib as it is always on internal storage
3503        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3504            return false;
3505        }
3506
3507        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3508                ps.pkg.staticSharedLibVersion);
3509        if (libEntry == null) {
3510            return false;
3511        }
3512
3513        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3514        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3515        if (uidPackageNames == null) {
3516            return true;
3517        }
3518
3519        for (String uidPackageName : uidPackageNames) {
3520            if (ps.name.equals(uidPackageName)) {
3521                return false;
3522            }
3523            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3524            if (uidPs != null) {
3525                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3526                        libEntry.info.getName());
3527                if (index < 0) {
3528                    continue;
3529                }
3530                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3531                    return false;
3532                }
3533            }
3534        }
3535        return true;
3536    }
3537
3538    @Override
3539    public String[] currentToCanonicalPackageNames(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                PackageSetting ps = mSettings.mPackages.get(names[i]);
3545                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3546            }
3547        }
3548        return out;
3549    }
3550
3551    @Override
3552    public String[] canonicalToCurrentPackageNames(String[] names) {
3553        String[] out = new String[names.length];
3554        // reader
3555        synchronized (mPackages) {
3556            for (int i=names.length-1; i>=0; i--) {
3557                String cur = mSettings.getRenamedPackageLPr(names[i]);
3558                out[i] = cur != null ? cur : names[i];
3559            }
3560        }
3561        return out;
3562    }
3563
3564    @Override
3565    public int getPackageUid(String packageName, int flags, int userId) {
3566        if (!sUserManager.exists(userId)) return -1;
3567        flags = updateFlagsForPackage(flags, userId, packageName);
3568        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3569                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3570
3571        // reader
3572        synchronized (mPackages) {
3573            final PackageParser.Package p = mPackages.get(packageName);
3574            if (p != null && p.isMatch(flags)) {
3575                return UserHandle.getUid(userId, p.applicationInfo.uid);
3576            }
3577            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3578                final PackageSetting ps = mSettings.mPackages.get(packageName);
3579                if (ps != null && ps.isMatch(flags)) {
3580                    return UserHandle.getUid(userId, ps.appId);
3581                }
3582            }
3583        }
3584
3585        return -1;
3586    }
3587
3588    @Override
3589    public int[] getPackageGids(String packageName, int flags, int userId) {
3590        if (!sUserManager.exists(userId)) return null;
3591        flags = updateFlagsForPackage(flags, userId, packageName);
3592        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3593                false /* requireFullPermission */, false /* checkShell */,
3594                "getPackageGids");
3595
3596        // reader
3597        synchronized (mPackages) {
3598            final PackageParser.Package p = mPackages.get(packageName);
3599            if (p != null && p.isMatch(flags)) {
3600                PackageSetting ps = (PackageSetting) p.mExtras;
3601                // TODO: Shouldn't this be checking for package installed state for userId and
3602                // return null?
3603                return ps.getPermissionsState().computeGids(userId);
3604            }
3605            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3606                final PackageSetting ps = mSettings.mPackages.get(packageName);
3607                if (ps != null && ps.isMatch(flags)) {
3608                    return ps.getPermissionsState().computeGids(userId);
3609                }
3610            }
3611        }
3612
3613        return null;
3614    }
3615
3616    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3617        if (bp.perm != null) {
3618            return PackageParser.generatePermissionInfo(bp.perm, flags);
3619        }
3620        PermissionInfo pi = new PermissionInfo();
3621        pi.name = bp.name;
3622        pi.packageName = bp.sourcePackage;
3623        pi.nonLocalizedLabel = bp.name;
3624        pi.protectionLevel = bp.protectionLevel;
3625        return pi;
3626    }
3627
3628    @Override
3629    public PermissionInfo getPermissionInfo(String name, int flags) {
3630        // reader
3631        synchronized (mPackages) {
3632            final BasePermission p = mSettings.mPermissions.get(name);
3633            if (p != null) {
3634                return generatePermissionInfo(p, flags);
3635            }
3636            return null;
3637        }
3638    }
3639
3640    @Override
3641    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3642            int flags) {
3643        // reader
3644        synchronized (mPackages) {
3645            if (group != null && !mPermissionGroups.containsKey(group)) {
3646                // This is thrown as NameNotFoundException
3647                return null;
3648            }
3649
3650            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3651            for (BasePermission p : mSettings.mPermissions.values()) {
3652                if (group == null) {
3653                    if (p.perm == null || p.perm.info.group == null) {
3654                        out.add(generatePermissionInfo(p, flags));
3655                    }
3656                } else {
3657                    if (p.perm != null && group.equals(p.perm.info.group)) {
3658                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3659                    }
3660                }
3661            }
3662            return new ParceledListSlice<>(out);
3663        }
3664    }
3665
3666    @Override
3667    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3668        // reader
3669        synchronized (mPackages) {
3670            return PackageParser.generatePermissionGroupInfo(
3671                    mPermissionGroups.get(name), flags);
3672        }
3673    }
3674
3675    @Override
3676    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3677        // reader
3678        synchronized (mPackages) {
3679            final int N = mPermissionGroups.size();
3680            ArrayList<PermissionGroupInfo> out
3681                    = new ArrayList<PermissionGroupInfo>(N);
3682            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3683                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3684            }
3685            return new ParceledListSlice<>(out);
3686        }
3687    }
3688
3689    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3690            int uid, int userId) {
3691        if (!sUserManager.exists(userId)) return null;
3692        PackageSetting ps = mSettings.mPackages.get(packageName);
3693        if (ps != null) {
3694            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3695                return null;
3696            }
3697            if (ps.pkg == null) {
3698                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3699                if (pInfo != null) {
3700                    return pInfo.applicationInfo;
3701                }
3702                return null;
3703            }
3704            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3705                    ps.readUserState(userId), userId);
3706            if (ai != null) {
3707                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3708            }
3709            return ai;
3710        }
3711        return null;
3712    }
3713
3714    @Override
3715    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3716        if (!sUserManager.exists(userId)) return null;
3717        flags = updateFlagsForApplication(flags, userId, packageName);
3718        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3719                false /* requireFullPermission */, false /* checkShell */, "get application info");
3720
3721        // writer
3722        synchronized (mPackages) {
3723            // Normalize package name to handle renamed packages and static libs
3724            packageName = resolveInternalPackageNameLPr(packageName,
3725                    PackageManager.VERSION_CODE_HIGHEST);
3726
3727            PackageParser.Package p = mPackages.get(packageName);
3728            if (DEBUG_PACKAGE_INFO) Log.v(
3729                    TAG, "getApplicationInfo " + packageName
3730                    + ": " + p);
3731            if (p != null) {
3732                PackageSetting ps = mSettings.mPackages.get(packageName);
3733                if (ps == null) return null;
3734                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3735                    return null;
3736                }
3737                // Note: isEnabledLP() does not apply here - always return info
3738                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3739                        p, flags, ps.readUserState(userId), userId);
3740                if (ai != null) {
3741                    ai.packageName = resolveExternalPackageNameLPr(p);
3742                }
3743                return ai;
3744            }
3745            if ("android".equals(packageName)||"system".equals(packageName)) {
3746                return mAndroidApplication;
3747            }
3748            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3749                // Already generates the external package name
3750                return generateApplicationInfoFromSettingsLPw(packageName,
3751                        Binder.getCallingUid(), flags, userId);
3752            }
3753        }
3754        return null;
3755    }
3756
3757    private String normalizePackageNameLPr(String packageName) {
3758        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3759        return normalizedPackageName != null ? normalizedPackageName : packageName;
3760    }
3761
3762    @Override
3763    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3764            final IPackageDataObserver observer) {
3765        mContext.enforceCallingOrSelfPermission(
3766                android.Manifest.permission.CLEAR_APP_CACHE, null);
3767        // Queue up an async operation since clearing cache may take a little while.
3768        mHandler.post(new Runnable() {
3769            public void run() {
3770                mHandler.removeCallbacks(this);
3771                boolean success = true;
3772                synchronized (mInstallLock) {
3773                    try {
3774                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3775                    } catch (InstallerException e) {
3776                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3777                        success = false;
3778                    }
3779                }
3780                if (observer != null) {
3781                    try {
3782                        observer.onRemoveCompleted(null, success);
3783                    } catch (RemoteException e) {
3784                        Slog.w(TAG, "RemoveException when invoking call back");
3785                    }
3786                }
3787            }
3788        });
3789    }
3790
3791    @Override
3792    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3793            final IntentSender pi) {
3794        mContext.enforceCallingOrSelfPermission(
3795                android.Manifest.permission.CLEAR_APP_CACHE, null);
3796        // Queue up an async operation since clearing cache may take a little while.
3797        mHandler.post(new Runnable() {
3798            public void run() {
3799                mHandler.removeCallbacks(this);
3800                boolean success = true;
3801                synchronized (mInstallLock) {
3802                    try {
3803                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3804                    } catch (InstallerException e) {
3805                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3806                        success = false;
3807                    }
3808                }
3809                if(pi != null) {
3810                    try {
3811                        // Callback via pending intent
3812                        int code = success ? 1 : 0;
3813                        pi.sendIntent(null, code, null,
3814                                null, null);
3815                    } catch (SendIntentException e1) {
3816                        Slog.i(TAG, "Failed to send pending intent");
3817                    }
3818                }
3819            }
3820        });
3821    }
3822
3823    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3824        synchronized (mInstallLock) {
3825            try {
3826                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3827            } catch (InstallerException e) {
3828                throw new IOException("Failed to free enough space", e);
3829            }
3830        }
3831    }
3832
3833    /**
3834     * Update given flags based on encryption status of current user.
3835     */
3836    private int updateFlags(int flags, int userId) {
3837        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3838                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3839            // Caller expressed an explicit opinion about what encryption
3840            // aware/unaware components they want to see, so fall through and
3841            // give them what they want
3842        } else {
3843            // Caller expressed no opinion, so match based on user state
3844            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3845                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3846            } else {
3847                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3848            }
3849        }
3850        return flags;
3851    }
3852
3853    private UserManagerInternal getUserManagerInternal() {
3854        if (mUserManagerInternal == null) {
3855            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3856        }
3857        return mUserManagerInternal;
3858    }
3859
3860    /**
3861     * Update given flags when being used to request {@link PackageInfo}.
3862     */
3863    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3864        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3865        boolean triaged = true;
3866        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3867                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3868            // Caller is asking for component details, so they'd better be
3869            // asking for specific encryption matching behavior, or be triaged
3870            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3871                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3872                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3873                triaged = false;
3874            }
3875        }
3876        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3877                | PackageManager.MATCH_SYSTEM_ONLY
3878                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3879            triaged = false;
3880        }
3881        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3882            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3883                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3884                    + Debug.getCallers(5));
3885        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3886                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3887            // If the caller wants all packages and has a restricted profile associated with it,
3888            // then match all users. This is to make sure that launchers that need to access work
3889            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3890            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3891            flags |= PackageManager.MATCH_ANY_USER;
3892        }
3893        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3894            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3895                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3896        }
3897        return updateFlags(flags, userId);
3898    }
3899
3900    /**
3901     * Update given flags when being used to request {@link ApplicationInfo}.
3902     */
3903    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3904        return updateFlagsForPackage(flags, userId, cookie);
3905    }
3906
3907    /**
3908     * Update given flags when being used to request {@link ComponentInfo}.
3909     */
3910    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3911        if (cookie instanceof Intent) {
3912            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3913                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3914            }
3915        }
3916
3917        boolean triaged = true;
3918        // Caller is asking for component details, so they'd better be
3919        // asking for specific encryption matching behavior, or be triaged
3920        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3921                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3922                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3923            triaged = false;
3924        }
3925        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3926            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3927                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3928        }
3929
3930        return updateFlags(flags, userId);
3931    }
3932
3933    /**
3934     * Update given intent when being used to request {@link ResolveInfo}.
3935     */
3936    private Intent updateIntentForResolve(Intent intent) {
3937        if (intent.getSelector() != null) {
3938            intent = intent.getSelector();
3939        }
3940        if (DEBUG_PREFERRED) {
3941            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3942        }
3943        return intent;
3944    }
3945
3946    /**
3947     * Update given flags when being used to request {@link ResolveInfo}.
3948     */
3949    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3950        // Safe mode means we shouldn't match any third-party components
3951        if (mSafeMode) {
3952            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3953        }
3954        final int callingUid = Binder.getCallingUid();
3955        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3956            // The system sees all components
3957            flags |= PackageManager.MATCH_EPHEMERAL;
3958        } else if (getEphemeralPackageName(callingUid) != null) {
3959            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3960            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3961            flags |= PackageManager.MATCH_EPHEMERAL;
3962        } else {
3963            // Otherwise, prevent leaking ephemeral components
3964            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3965            flags &= ~PackageManager.MATCH_EPHEMERAL;
3966        }
3967        return updateFlagsForComponent(flags, userId, cookie);
3968    }
3969
3970    @Override
3971    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3972        if (!sUserManager.exists(userId)) return null;
3973        flags = updateFlagsForComponent(flags, userId, component);
3974        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3975                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3976        synchronized (mPackages) {
3977            PackageParser.Activity a = mActivities.mActivities.get(component);
3978
3979            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3980            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3981                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3982                if (ps == null) return null;
3983                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3984                        userId);
3985            }
3986            if (mResolveComponentName.equals(component)) {
3987                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3988                        new PackageUserState(), userId);
3989            }
3990        }
3991        return null;
3992    }
3993
3994    @Override
3995    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3996            String resolvedType) {
3997        synchronized (mPackages) {
3998            if (component.equals(mResolveComponentName)) {
3999                // The resolver supports EVERYTHING!
4000                return true;
4001            }
4002            PackageParser.Activity a = mActivities.mActivities.get(component);
4003            if (a == null) {
4004                return false;
4005            }
4006            for (int i=0; i<a.intents.size(); i++) {
4007                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4008                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4009                    return true;
4010                }
4011            }
4012            return false;
4013        }
4014    }
4015
4016    @Override
4017    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4018        if (!sUserManager.exists(userId)) return null;
4019        flags = updateFlagsForComponent(flags, userId, component);
4020        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4021                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4022        synchronized (mPackages) {
4023            PackageParser.Activity a = mReceivers.mActivities.get(component);
4024            if (DEBUG_PACKAGE_INFO) Log.v(
4025                TAG, "getReceiverInfo " + component + ": " + a);
4026            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4027                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4028                if (ps == null) return null;
4029                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4030                        userId);
4031            }
4032        }
4033        return null;
4034    }
4035
4036    @Override
4037    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4038        if (!sUserManager.exists(userId)) return null;
4039        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4040
4041        flags = updateFlagsForPackage(flags, userId, null);
4042
4043        final boolean canSeeStaticLibraries =
4044                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4045                        == PERMISSION_GRANTED
4046                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4047                        == PERMISSION_GRANTED
4048                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4049                        == PERMISSION_GRANTED
4050                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4051                        == PERMISSION_GRANTED;
4052
4053        synchronized (mPackages) {
4054            List<SharedLibraryInfo> result = null;
4055
4056            final int libCount = mSharedLibraries.size();
4057            for (int i = 0; i < libCount; i++) {
4058                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4059                if (versionedLib == null) {
4060                    continue;
4061                }
4062
4063                final int versionCount = versionedLib.size();
4064                for (int j = 0; j < versionCount; j++) {
4065                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4066                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4067                        break;
4068                    }
4069                    final long identity = Binder.clearCallingIdentity();
4070                    try {
4071                        // TODO: We will change version code to long, so in the new API it is long
4072                        PackageInfo packageInfo = getPackageInfoVersioned(
4073                                libInfo.getDeclaringPackage(), flags, userId);
4074                        if (packageInfo == null) {
4075                            continue;
4076                        }
4077                    } finally {
4078                        Binder.restoreCallingIdentity(identity);
4079                    }
4080
4081                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4082                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4083                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4084
4085                    if (result == null) {
4086                        result = new ArrayList<>();
4087                    }
4088                    result.add(resLibInfo);
4089                }
4090            }
4091
4092            return result != null ? new ParceledListSlice<>(result) : null;
4093        }
4094    }
4095
4096    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4097            SharedLibraryInfo libInfo, int flags, int userId) {
4098        List<VersionedPackage> versionedPackages = null;
4099        final int packageCount = mSettings.mPackages.size();
4100        for (int i = 0; i < packageCount; i++) {
4101            PackageSetting ps = mSettings.mPackages.valueAt(i);
4102
4103            if (ps == null) {
4104                continue;
4105            }
4106
4107            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4108                continue;
4109            }
4110
4111            final String libName = libInfo.getName();
4112            if (libInfo.isStatic()) {
4113                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4114                if (libIdx < 0) {
4115                    continue;
4116                }
4117                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4118                    continue;
4119                }
4120                if (versionedPackages == null) {
4121                    versionedPackages = new ArrayList<>();
4122                }
4123                // If the dependent is a static shared lib, use the public package name
4124                String dependentPackageName = ps.name;
4125                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4126                    dependentPackageName = ps.pkg.manifestPackageName;
4127                }
4128                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4129            } else if (ps.pkg != null) {
4130                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4131                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4132                    if (versionedPackages == null) {
4133                        versionedPackages = new ArrayList<>();
4134                    }
4135                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4136                }
4137            }
4138        }
4139
4140        return versionedPackages;
4141    }
4142
4143    @Override
4144    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4145        if (!sUserManager.exists(userId)) return null;
4146        flags = updateFlagsForComponent(flags, userId, component);
4147        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4148                false /* requireFullPermission */, false /* checkShell */, "get service info");
4149        synchronized (mPackages) {
4150            PackageParser.Service s = mServices.mServices.get(component);
4151            if (DEBUG_PACKAGE_INFO) Log.v(
4152                TAG, "getServiceInfo " + component + ": " + s);
4153            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4154                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4155                if (ps == null) return null;
4156                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4157                        userId);
4158            }
4159        }
4160        return null;
4161    }
4162
4163    @Override
4164    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4165        if (!sUserManager.exists(userId)) return null;
4166        flags = updateFlagsForComponent(flags, userId, component);
4167        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4168                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4169        synchronized (mPackages) {
4170            PackageParser.Provider p = mProviders.mProviders.get(component);
4171            if (DEBUG_PACKAGE_INFO) Log.v(
4172                TAG, "getProviderInfo " + component + ": " + p);
4173            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4174                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4175                if (ps == null) return null;
4176                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4177                        userId);
4178            }
4179        }
4180        return null;
4181    }
4182
4183    @Override
4184    public String[] getSystemSharedLibraryNames() {
4185        synchronized (mPackages) {
4186            Set<String> libs = null;
4187            final int libCount = mSharedLibraries.size();
4188            for (int i = 0; i < libCount; i++) {
4189                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4190                if (versionedLib == null) {
4191                    continue;
4192                }
4193                final int versionCount = versionedLib.size();
4194                for (int j = 0; j < versionCount; j++) {
4195                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4196                    if (!libEntry.info.isStatic()) {
4197                        if (libs == null) {
4198                            libs = new ArraySet<>();
4199                        }
4200                        libs.add(libEntry.info.getName());
4201                        break;
4202                    }
4203                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4204                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4205                            UserHandle.getUserId(Binder.getCallingUid()))) {
4206                        if (libs == null) {
4207                            libs = new ArraySet<>();
4208                        }
4209                        libs.add(libEntry.info.getName());
4210                        break;
4211                    }
4212                }
4213            }
4214
4215            if (libs != null) {
4216                String[] libsArray = new String[libs.size()];
4217                libs.toArray(libsArray);
4218                return libsArray;
4219            }
4220
4221            return null;
4222        }
4223    }
4224
4225    @Override
4226    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4227        synchronized (mPackages) {
4228            return mServicesSystemSharedLibraryPackageName;
4229        }
4230    }
4231
4232    @Override
4233    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4234        synchronized (mPackages) {
4235            return mSharedSystemSharedLibraryPackageName;
4236        }
4237    }
4238
4239    private void updateSequenceNumberLP(String packageName, int[] userList) {
4240        for (int i = userList.length - 1; i >= 0; --i) {
4241            final int userId = userList[i];
4242            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4243            if (changedPackages == null) {
4244                changedPackages = new SparseArray<>();
4245                mChangedPackages.put(userId, changedPackages);
4246            }
4247            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4248            if (sequenceNumbers == null) {
4249                sequenceNumbers = new HashMap<>();
4250                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4251            }
4252            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4253            if (sequenceNumber != null) {
4254                changedPackages.remove(sequenceNumber);
4255            }
4256            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4257            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4258        }
4259        mChangedPackagesSequenceNumber++;
4260    }
4261
4262    @Override
4263    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4264        synchronized (mPackages) {
4265            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4266                return null;
4267            }
4268            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4269            if (changedPackages == null) {
4270                return null;
4271            }
4272            final List<String> packageNames =
4273                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4274            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4275                final String packageName = changedPackages.get(i);
4276                if (packageName != null) {
4277                    packageNames.add(packageName);
4278                }
4279            }
4280            return packageNames.isEmpty()
4281                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4282        }
4283    }
4284
4285    @Override
4286    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4287        ArrayList<FeatureInfo> res;
4288        synchronized (mAvailableFeatures) {
4289            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4290            res.addAll(mAvailableFeatures.values());
4291        }
4292        final FeatureInfo fi = new FeatureInfo();
4293        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4294                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4295        res.add(fi);
4296
4297        return new ParceledListSlice<>(res);
4298    }
4299
4300    @Override
4301    public boolean hasSystemFeature(String name, int version) {
4302        synchronized (mAvailableFeatures) {
4303            final FeatureInfo feat = mAvailableFeatures.get(name);
4304            if (feat == null) {
4305                return false;
4306            } else {
4307                return feat.version >= version;
4308            }
4309        }
4310    }
4311
4312    @Override
4313    public int checkPermission(String permName, String pkgName, int userId) {
4314        if (!sUserManager.exists(userId)) {
4315            return PackageManager.PERMISSION_DENIED;
4316        }
4317
4318        synchronized (mPackages) {
4319            final PackageParser.Package p = mPackages.get(pkgName);
4320            if (p != null && p.mExtras != null) {
4321                final PackageSetting ps = (PackageSetting) p.mExtras;
4322                final PermissionsState permissionsState = ps.getPermissionsState();
4323                if (permissionsState.hasPermission(permName, userId)) {
4324                    return PackageManager.PERMISSION_GRANTED;
4325                }
4326                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4327                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4328                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4329                    return PackageManager.PERMISSION_GRANTED;
4330                }
4331            }
4332        }
4333
4334        return PackageManager.PERMISSION_DENIED;
4335    }
4336
4337    @Override
4338    public int checkUidPermission(String permName, int uid) {
4339        final int userId = UserHandle.getUserId(uid);
4340
4341        if (!sUserManager.exists(userId)) {
4342            return PackageManager.PERMISSION_DENIED;
4343        }
4344
4345        synchronized (mPackages) {
4346            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4347            if (obj != null) {
4348                final SettingBase ps = (SettingBase) obj;
4349                final PermissionsState permissionsState = ps.getPermissionsState();
4350                if (permissionsState.hasPermission(permName, userId)) {
4351                    return PackageManager.PERMISSION_GRANTED;
4352                }
4353                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4354                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4355                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4356                    return PackageManager.PERMISSION_GRANTED;
4357                }
4358            } else {
4359                ArraySet<String> perms = mSystemPermissions.get(uid);
4360                if (perms != null) {
4361                    if (perms.contains(permName)) {
4362                        return PackageManager.PERMISSION_GRANTED;
4363                    }
4364                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4365                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4366                        return PackageManager.PERMISSION_GRANTED;
4367                    }
4368                }
4369            }
4370        }
4371
4372        return PackageManager.PERMISSION_DENIED;
4373    }
4374
4375    @Override
4376    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4377        if (UserHandle.getCallingUserId() != userId) {
4378            mContext.enforceCallingPermission(
4379                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4380                    "isPermissionRevokedByPolicy for user " + userId);
4381        }
4382
4383        if (checkPermission(permission, packageName, userId)
4384                == PackageManager.PERMISSION_GRANTED) {
4385            return false;
4386        }
4387
4388        final long identity = Binder.clearCallingIdentity();
4389        try {
4390            final int flags = getPermissionFlags(permission, packageName, userId);
4391            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4392        } finally {
4393            Binder.restoreCallingIdentity(identity);
4394        }
4395    }
4396
4397    @Override
4398    public String getPermissionControllerPackageName() {
4399        synchronized (mPackages) {
4400            return mRequiredInstallerPackage;
4401        }
4402    }
4403
4404    /**
4405     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4406     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4407     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4408     * @param message the message to log on security exception
4409     */
4410    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4411            boolean checkShell, String message) {
4412        if (userId < 0) {
4413            throw new IllegalArgumentException("Invalid userId " + userId);
4414        }
4415        if (checkShell) {
4416            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4417        }
4418        if (userId == UserHandle.getUserId(callingUid)) return;
4419        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4420            if (requireFullPermission) {
4421                mContext.enforceCallingOrSelfPermission(
4422                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4423            } else {
4424                try {
4425                    mContext.enforceCallingOrSelfPermission(
4426                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4427                } catch (SecurityException se) {
4428                    mContext.enforceCallingOrSelfPermission(
4429                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4430                }
4431            }
4432        }
4433    }
4434
4435    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4436        if (callingUid == Process.SHELL_UID) {
4437            if (userHandle >= 0
4438                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4439                throw new SecurityException("Shell does not have permission to access user "
4440                        + userHandle);
4441            } else if (userHandle < 0) {
4442                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4443                        + Debug.getCallers(3));
4444            }
4445        }
4446    }
4447
4448    private BasePermission findPermissionTreeLP(String permName) {
4449        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4450            if (permName.startsWith(bp.name) &&
4451                    permName.length() > bp.name.length() &&
4452                    permName.charAt(bp.name.length()) == '.') {
4453                return bp;
4454            }
4455        }
4456        return null;
4457    }
4458
4459    private BasePermission checkPermissionTreeLP(String permName) {
4460        if (permName != null) {
4461            BasePermission bp = findPermissionTreeLP(permName);
4462            if (bp != null) {
4463                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4464                    return bp;
4465                }
4466                throw new SecurityException("Calling uid "
4467                        + Binder.getCallingUid()
4468                        + " is not allowed to add to permission tree "
4469                        + bp.name + " owned by uid " + bp.uid);
4470            }
4471        }
4472        throw new SecurityException("No permission tree found for " + permName);
4473    }
4474
4475    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4476        if (s1 == null) {
4477            return s2 == null;
4478        }
4479        if (s2 == null) {
4480            return false;
4481        }
4482        if (s1.getClass() != s2.getClass()) {
4483            return false;
4484        }
4485        return s1.equals(s2);
4486    }
4487
4488    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4489        if (pi1.icon != pi2.icon) return false;
4490        if (pi1.logo != pi2.logo) return false;
4491        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4492        if (!compareStrings(pi1.name, pi2.name)) return false;
4493        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4494        // We'll take care of setting this one.
4495        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4496        // These are not currently stored in settings.
4497        //if (!compareStrings(pi1.group, pi2.group)) return false;
4498        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4499        //if (pi1.labelRes != pi2.labelRes) return false;
4500        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4501        return true;
4502    }
4503
4504    int permissionInfoFootprint(PermissionInfo info) {
4505        int size = info.name.length();
4506        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4507        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4508        return size;
4509    }
4510
4511    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4512        int size = 0;
4513        for (BasePermission perm : mSettings.mPermissions.values()) {
4514            if (perm.uid == tree.uid) {
4515                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4516            }
4517        }
4518        return size;
4519    }
4520
4521    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4522        // We calculate the max size of permissions defined by this uid and throw
4523        // if that plus the size of 'info' would exceed our stated maximum.
4524        if (tree.uid != Process.SYSTEM_UID) {
4525            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4526            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4527                throw new SecurityException("Permission tree size cap exceeded");
4528            }
4529        }
4530    }
4531
4532    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4533        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4534            throw new SecurityException("Label must be specified in permission");
4535        }
4536        BasePermission tree = checkPermissionTreeLP(info.name);
4537        BasePermission bp = mSettings.mPermissions.get(info.name);
4538        boolean added = bp == null;
4539        boolean changed = true;
4540        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4541        if (added) {
4542            enforcePermissionCapLocked(info, tree);
4543            bp = new BasePermission(info.name, tree.sourcePackage,
4544                    BasePermission.TYPE_DYNAMIC);
4545        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4546            throw new SecurityException(
4547                    "Not allowed to modify non-dynamic permission "
4548                    + info.name);
4549        } else {
4550            if (bp.protectionLevel == fixedLevel
4551                    && bp.perm.owner.equals(tree.perm.owner)
4552                    && bp.uid == tree.uid
4553                    && comparePermissionInfos(bp.perm.info, info)) {
4554                changed = false;
4555            }
4556        }
4557        bp.protectionLevel = fixedLevel;
4558        info = new PermissionInfo(info);
4559        info.protectionLevel = fixedLevel;
4560        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4561        bp.perm.info.packageName = tree.perm.info.packageName;
4562        bp.uid = tree.uid;
4563        if (added) {
4564            mSettings.mPermissions.put(info.name, bp);
4565        }
4566        if (changed) {
4567            if (!async) {
4568                mSettings.writeLPr();
4569            } else {
4570                scheduleWriteSettingsLocked();
4571            }
4572        }
4573        return added;
4574    }
4575
4576    @Override
4577    public boolean addPermission(PermissionInfo info) {
4578        synchronized (mPackages) {
4579            return addPermissionLocked(info, false);
4580        }
4581    }
4582
4583    @Override
4584    public boolean addPermissionAsync(PermissionInfo info) {
4585        synchronized (mPackages) {
4586            return addPermissionLocked(info, true);
4587        }
4588    }
4589
4590    @Override
4591    public void removePermission(String name) {
4592        synchronized (mPackages) {
4593            checkPermissionTreeLP(name);
4594            BasePermission bp = mSettings.mPermissions.get(name);
4595            if (bp != null) {
4596                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4597                    throw new SecurityException(
4598                            "Not allowed to modify non-dynamic permission "
4599                            + name);
4600                }
4601                mSettings.mPermissions.remove(name);
4602                mSettings.writeLPr();
4603            }
4604        }
4605    }
4606
4607    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4608            BasePermission bp) {
4609        int index = pkg.requestedPermissions.indexOf(bp.name);
4610        if (index == -1) {
4611            throw new SecurityException("Package " + pkg.packageName
4612                    + " has not requested permission " + bp.name);
4613        }
4614        if (!bp.isRuntime() && !bp.isDevelopment()) {
4615            throw new SecurityException("Permission " + bp.name
4616                    + " is not a changeable permission type");
4617        }
4618    }
4619
4620    @Override
4621    public void grantRuntimePermission(String packageName, String name, final int userId) {
4622        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4623    }
4624
4625    private void grantRuntimePermission(String packageName, String name, final int userId,
4626            boolean overridePolicy) {
4627        if (!sUserManager.exists(userId)) {
4628            Log.e(TAG, "No such user:" + userId);
4629            return;
4630        }
4631
4632        mContext.enforceCallingOrSelfPermission(
4633                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4634                "grantRuntimePermission");
4635
4636        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4637                true /* requireFullPermission */, true /* checkShell */,
4638                "grantRuntimePermission");
4639
4640        final int uid;
4641        final SettingBase sb;
4642
4643        synchronized (mPackages) {
4644            final PackageParser.Package pkg = mPackages.get(packageName);
4645            if (pkg == null) {
4646                throw new IllegalArgumentException("Unknown package: " + packageName);
4647            }
4648
4649            final BasePermission bp = mSettings.mPermissions.get(name);
4650            if (bp == null) {
4651                throw new IllegalArgumentException("Unknown permission: " + name);
4652            }
4653
4654            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4655
4656            // If a permission review is required for legacy apps we represent
4657            // their permissions as always granted runtime ones since we need
4658            // to keep the review required permission flag per user while an
4659            // install permission's state is shared across all users.
4660            if (mPermissionReviewRequired
4661                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4662                    && bp.isRuntime()) {
4663                return;
4664            }
4665
4666            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4667            sb = (SettingBase) pkg.mExtras;
4668            if (sb == null) {
4669                throw new IllegalArgumentException("Unknown package: " + packageName);
4670            }
4671
4672            final PermissionsState permissionsState = sb.getPermissionsState();
4673
4674            final int flags = permissionsState.getPermissionFlags(name, userId);
4675            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4676                throw new SecurityException("Cannot grant system fixed permission "
4677                        + name + " for package " + packageName);
4678            }
4679            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4680                throw new SecurityException("Cannot grant policy fixed permission "
4681                        + name + " for package " + packageName);
4682            }
4683
4684            if (bp.isDevelopment()) {
4685                // Development permissions must be handled specially, since they are not
4686                // normal runtime permissions.  For now they apply to all users.
4687                if (permissionsState.grantInstallPermission(bp) !=
4688                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4689                    scheduleWriteSettingsLocked();
4690                }
4691                return;
4692            }
4693
4694            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
4695                throw new SecurityException("Cannot grant non-ephemeral permission"
4696                        + name + " for package " + packageName);
4697            }
4698
4699            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4700                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4701                return;
4702            }
4703
4704            final int result = permissionsState.grantRuntimePermission(bp, userId);
4705            switch (result) {
4706                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4707                    return;
4708                }
4709
4710                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4711                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4712                    mHandler.post(new Runnable() {
4713                        @Override
4714                        public void run() {
4715                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4716                        }
4717                    });
4718                }
4719                break;
4720            }
4721
4722            if (bp.isRuntime()) {
4723                logPermissionGranted(mContext, name, packageName);
4724            }
4725
4726            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4727
4728            // Not critical if that is lost - app has to request again.
4729            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4730        }
4731
4732        // Only need to do this if user is initialized. Otherwise it's a new user
4733        // and there are no processes running as the user yet and there's no need
4734        // to make an expensive call to remount processes for the changed permissions.
4735        if (READ_EXTERNAL_STORAGE.equals(name)
4736                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4737            final long token = Binder.clearCallingIdentity();
4738            try {
4739                if (sUserManager.isInitialized(userId)) {
4740                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4741                            StorageManagerInternal.class);
4742                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4743                }
4744            } finally {
4745                Binder.restoreCallingIdentity(token);
4746            }
4747        }
4748    }
4749
4750    @Override
4751    public void revokeRuntimePermission(String packageName, String name, int userId) {
4752        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4753    }
4754
4755    private void revokeRuntimePermission(String packageName, String name, int userId,
4756            boolean overridePolicy) {
4757        if (!sUserManager.exists(userId)) {
4758            Log.e(TAG, "No such user:" + userId);
4759            return;
4760        }
4761
4762        mContext.enforceCallingOrSelfPermission(
4763                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4764                "revokeRuntimePermission");
4765
4766        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4767                true /* requireFullPermission */, true /* checkShell */,
4768                "revokeRuntimePermission");
4769
4770        final int appId;
4771
4772        synchronized (mPackages) {
4773            final PackageParser.Package pkg = mPackages.get(packageName);
4774            if (pkg == null) {
4775                throw new IllegalArgumentException("Unknown package: " + packageName);
4776            }
4777
4778            final BasePermission bp = mSettings.mPermissions.get(name);
4779            if (bp == null) {
4780                throw new IllegalArgumentException("Unknown permission: " + name);
4781            }
4782
4783            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4784
4785            // If a permission review is required for legacy apps we represent
4786            // their permissions as always granted runtime ones since we need
4787            // to keep the review required permission flag per user while an
4788            // install permission's state is shared across all users.
4789            if (mPermissionReviewRequired
4790                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4791                    && bp.isRuntime()) {
4792                return;
4793            }
4794
4795            SettingBase sb = (SettingBase) pkg.mExtras;
4796            if (sb == null) {
4797                throw new IllegalArgumentException("Unknown package: " + packageName);
4798            }
4799
4800            final PermissionsState permissionsState = sb.getPermissionsState();
4801
4802            final int flags = permissionsState.getPermissionFlags(name, userId);
4803            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4804                throw new SecurityException("Cannot revoke system fixed permission "
4805                        + name + " for package " + packageName);
4806            }
4807            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4808                throw new SecurityException("Cannot revoke policy fixed permission "
4809                        + name + " for package " + packageName);
4810            }
4811
4812            if (bp.isDevelopment()) {
4813                // Development permissions must be handled specially, since they are not
4814                // normal runtime permissions.  For now they apply to all users.
4815                if (permissionsState.revokeInstallPermission(bp) !=
4816                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4817                    scheduleWriteSettingsLocked();
4818                }
4819                return;
4820            }
4821
4822            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4823                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4824                return;
4825            }
4826
4827            if (bp.isRuntime()) {
4828                logPermissionRevoked(mContext, name, packageName);
4829            }
4830
4831            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4832
4833            // Critical, after this call app should never have the permission.
4834            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4835
4836            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4837        }
4838
4839        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4840    }
4841
4842    /**
4843     * Get the first event id for the permission.
4844     *
4845     * <p>There are four events for each permission: <ul>
4846     *     <li>Request permission: first id + 0</li>
4847     *     <li>Grant permission: first id + 1</li>
4848     *     <li>Request for permission denied: first id + 2</li>
4849     *     <li>Revoke permission: first id + 3</li>
4850     * </ul></p>
4851     *
4852     * @param name name of the permission
4853     *
4854     * @return The first event id for the permission
4855     */
4856    private static int getBaseEventId(@NonNull String name) {
4857        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4858
4859        if (eventIdIndex == -1) {
4860            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4861                    || "user".equals(Build.TYPE)) {
4862                Log.i(TAG, "Unknown permission " + name);
4863
4864                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4865            } else {
4866                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4867                //
4868                // Also update
4869                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4870                // - metrics_constants.proto
4871                throw new IllegalStateException("Unknown permission " + name);
4872            }
4873        }
4874
4875        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4876    }
4877
4878    /**
4879     * Log that a permission was revoked.
4880     *
4881     * @param context Context of the caller
4882     * @param name name of the permission
4883     * @param packageName package permission if for
4884     */
4885    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4886            @NonNull String packageName) {
4887        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4888    }
4889
4890    /**
4891     * Log that a permission request was granted.
4892     *
4893     * @param context Context of the caller
4894     * @param name name of the permission
4895     * @param packageName package permission if for
4896     */
4897    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4898            @NonNull String packageName) {
4899        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4900    }
4901
4902    @Override
4903    public void resetRuntimePermissions() {
4904        mContext.enforceCallingOrSelfPermission(
4905                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4906                "revokeRuntimePermission");
4907
4908        int callingUid = Binder.getCallingUid();
4909        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4910            mContext.enforceCallingOrSelfPermission(
4911                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4912                    "resetRuntimePermissions");
4913        }
4914
4915        synchronized (mPackages) {
4916            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4917            for (int userId : UserManagerService.getInstance().getUserIds()) {
4918                final int packageCount = mPackages.size();
4919                for (int i = 0; i < packageCount; i++) {
4920                    PackageParser.Package pkg = mPackages.valueAt(i);
4921                    if (!(pkg.mExtras instanceof PackageSetting)) {
4922                        continue;
4923                    }
4924                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4925                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4926                }
4927            }
4928        }
4929    }
4930
4931    @Override
4932    public int getPermissionFlags(String name, String packageName, int userId) {
4933        if (!sUserManager.exists(userId)) {
4934            return 0;
4935        }
4936
4937        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4938
4939        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4940                true /* requireFullPermission */, false /* checkShell */,
4941                "getPermissionFlags");
4942
4943        synchronized (mPackages) {
4944            final PackageParser.Package pkg = mPackages.get(packageName);
4945            if (pkg == null) {
4946                return 0;
4947            }
4948
4949            final BasePermission bp = mSettings.mPermissions.get(name);
4950            if (bp == null) {
4951                return 0;
4952            }
4953
4954            SettingBase sb = (SettingBase) pkg.mExtras;
4955            if (sb == null) {
4956                return 0;
4957            }
4958
4959            PermissionsState permissionsState = sb.getPermissionsState();
4960            return permissionsState.getPermissionFlags(name, userId);
4961        }
4962    }
4963
4964    @Override
4965    public void updatePermissionFlags(String name, String packageName, int flagMask,
4966            int flagValues, int userId) {
4967        if (!sUserManager.exists(userId)) {
4968            return;
4969        }
4970
4971        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4972
4973        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4974                true /* requireFullPermission */, true /* checkShell */,
4975                "updatePermissionFlags");
4976
4977        // Only the system can change these flags and nothing else.
4978        if (getCallingUid() != Process.SYSTEM_UID) {
4979            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4980            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4981            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4982            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4983            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4984        }
4985
4986        synchronized (mPackages) {
4987            final PackageParser.Package pkg = mPackages.get(packageName);
4988            if (pkg == null) {
4989                throw new IllegalArgumentException("Unknown package: " + packageName);
4990            }
4991
4992            final BasePermission bp = mSettings.mPermissions.get(name);
4993            if (bp == null) {
4994                throw new IllegalArgumentException("Unknown permission: " + name);
4995            }
4996
4997            SettingBase sb = (SettingBase) pkg.mExtras;
4998            if (sb == null) {
4999                throw new IllegalArgumentException("Unknown package: " + packageName);
5000            }
5001
5002            PermissionsState permissionsState = sb.getPermissionsState();
5003
5004            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5005
5006            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5007                // Install and runtime permissions are stored in different places,
5008                // so figure out what permission changed and persist the change.
5009                if (permissionsState.getInstallPermissionState(name) != null) {
5010                    scheduleWriteSettingsLocked();
5011                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5012                        || hadState) {
5013                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5014                }
5015            }
5016        }
5017    }
5018
5019    /**
5020     * Update the permission flags for all packages and runtime permissions of a user in order
5021     * to allow device or profile owner to remove POLICY_FIXED.
5022     */
5023    @Override
5024    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5025        if (!sUserManager.exists(userId)) {
5026            return;
5027        }
5028
5029        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5030
5031        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5032                true /* requireFullPermission */, true /* checkShell */,
5033                "updatePermissionFlagsForAllApps");
5034
5035        // Only the system can change system fixed flags.
5036        if (getCallingUid() != Process.SYSTEM_UID) {
5037            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5038            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5039        }
5040
5041        synchronized (mPackages) {
5042            boolean changed = false;
5043            final int packageCount = mPackages.size();
5044            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5045                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5046                SettingBase sb = (SettingBase) pkg.mExtras;
5047                if (sb == null) {
5048                    continue;
5049                }
5050                PermissionsState permissionsState = sb.getPermissionsState();
5051                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5052                        userId, flagMask, flagValues);
5053            }
5054            if (changed) {
5055                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5056            }
5057        }
5058    }
5059
5060    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5061        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5062                != PackageManager.PERMISSION_GRANTED
5063            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5064                != PackageManager.PERMISSION_GRANTED) {
5065            throw new SecurityException(message + " requires "
5066                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5067                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5068        }
5069    }
5070
5071    @Override
5072    public boolean shouldShowRequestPermissionRationale(String permissionName,
5073            String packageName, int userId) {
5074        if (UserHandle.getCallingUserId() != userId) {
5075            mContext.enforceCallingPermission(
5076                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5077                    "canShowRequestPermissionRationale for user " + userId);
5078        }
5079
5080        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5081        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5082            return false;
5083        }
5084
5085        if (checkPermission(permissionName, packageName, userId)
5086                == PackageManager.PERMISSION_GRANTED) {
5087            return false;
5088        }
5089
5090        final int flags;
5091
5092        final long identity = Binder.clearCallingIdentity();
5093        try {
5094            flags = getPermissionFlags(permissionName,
5095                    packageName, userId);
5096        } finally {
5097            Binder.restoreCallingIdentity(identity);
5098        }
5099
5100        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5101                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5102                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5103
5104        if ((flags & fixedFlags) != 0) {
5105            return false;
5106        }
5107
5108        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5109    }
5110
5111    @Override
5112    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5113        mContext.enforceCallingOrSelfPermission(
5114                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5115                "addOnPermissionsChangeListener");
5116
5117        synchronized (mPackages) {
5118            mOnPermissionChangeListeners.addListenerLocked(listener);
5119        }
5120    }
5121
5122    @Override
5123    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5124        synchronized (mPackages) {
5125            mOnPermissionChangeListeners.removeListenerLocked(listener);
5126        }
5127    }
5128
5129    @Override
5130    public boolean isProtectedBroadcast(String actionName) {
5131        synchronized (mPackages) {
5132            if (mProtectedBroadcasts.contains(actionName)) {
5133                return true;
5134            } else if (actionName != null) {
5135                // TODO: remove these terrible hacks
5136                if (actionName.startsWith("android.net.netmon.lingerExpired")
5137                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5138                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5139                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5140                    return true;
5141                }
5142            }
5143        }
5144        return false;
5145    }
5146
5147    @Override
5148    public int checkSignatures(String pkg1, String pkg2) {
5149        synchronized (mPackages) {
5150            final PackageParser.Package p1 = mPackages.get(pkg1);
5151            final PackageParser.Package p2 = mPackages.get(pkg2);
5152            if (p1 == null || p1.mExtras == null
5153                    || p2 == null || p2.mExtras == null) {
5154                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5155            }
5156            return compareSignatures(p1.mSignatures, p2.mSignatures);
5157        }
5158    }
5159
5160    @Override
5161    public int checkUidSignatures(int uid1, int uid2) {
5162        // Map to base uids.
5163        uid1 = UserHandle.getAppId(uid1);
5164        uid2 = UserHandle.getAppId(uid2);
5165        // reader
5166        synchronized (mPackages) {
5167            Signature[] s1;
5168            Signature[] s2;
5169            Object obj = mSettings.getUserIdLPr(uid1);
5170            if (obj != null) {
5171                if (obj instanceof SharedUserSetting) {
5172                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5173                } else if (obj instanceof PackageSetting) {
5174                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5175                } else {
5176                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5177                }
5178            } else {
5179                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5180            }
5181            obj = mSettings.getUserIdLPr(uid2);
5182            if (obj != null) {
5183                if (obj instanceof SharedUserSetting) {
5184                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5185                } else if (obj instanceof PackageSetting) {
5186                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5187                } else {
5188                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5189                }
5190            } else {
5191                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5192            }
5193            return compareSignatures(s1, s2);
5194        }
5195    }
5196
5197    /**
5198     * This method should typically only be used when granting or revoking
5199     * permissions, since the app may immediately restart after this call.
5200     * <p>
5201     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5202     * guard your work against the app being relaunched.
5203     */
5204    private void killUid(int appId, int userId, String reason) {
5205        final long identity = Binder.clearCallingIdentity();
5206        try {
5207            IActivityManager am = ActivityManager.getService();
5208            if (am != null) {
5209                try {
5210                    am.killUid(appId, userId, reason);
5211                } catch (RemoteException e) {
5212                    /* ignore - same process */
5213                }
5214            }
5215        } finally {
5216            Binder.restoreCallingIdentity(identity);
5217        }
5218    }
5219
5220    /**
5221     * Compares two sets of signatures. Returns:
5222     * <br />
5223     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5224     * <br />
5225     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5226     * <br />
5227     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5228     * <br />
5229     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5230     * <br />
5231     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5232     */
5233    static int compareSignatures(Signature[] s1, Signature[] s2) {
5234        if (s1 == null) {
5235            return s2 == null
5236                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5237                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5238        }
5239
5240        if (s2 == null) {
5241            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5242        }
5243
5244        if (s1.length != s2.length) {
5245            return PackageManager.SIGNATURE_NO_MATCH;
5246        }
5247
5248        // Since both signature sets are of size 1, we can compare without HashSets.
5249        if (s1.length == 1) {
5250            return s1[0].equals(s2[0]) ?
5251                    PackageManager.SIGNATURE_MATCH :
5252                    PackageManager.SIGNATURE_NO_MATCH;
5253        }
5254
5255        ArraySet<Signature> set1 = new ArraySet<Signature>();
5256        for (Signature sig : s1) {
5257            set1.add(sig);
5258        }
5259        ArraySet<Signature> set2 = new ArraySet<Signature>();
5260        for (Signature sig : s2) {
5261            set2.add(sig);
5262        }
5263        // Make sure s2 contains all signatures in s1.
5264        if (set1.equals(set2)) {
5265            return PackageManager.SIGNATURE_MATCH;
5266        }
5267        return PackageManager.SIGNATURE_NO_MATCH;
5268    }
5269
5270    /**
5271     * If the database version for this type of package (internal storage or
5272     * external storage) is less than the version where package signatures
5273     * were updated, return true.
5274     */
5275    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5276        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5277        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5278    }
5279
5280    /**
5281     * Used for backward compatibility to make sure any packages with
5282     * certificate chains get upgraded to the new style. {@code existingSigs}
5283     * will be in the old format (since they were stored on disk from before the
5284     * system upgrade) and {@code scannedSigs} will be in the newer format.
5285     */
5286    private int compareSignaturesCompat(PackageSignatures existingSigs,
5287            PackageParser.Package scannedPkg) {
5288        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5289            return PackageManager.SIGNATURE_NO_MATCH;
5290        }
5291
5292        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5293        for (Signature sig : existingSigs.mSignatures) {
5294            existingSet.add(sig);
5295        }
5296        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5297        for (Signature sig : scannedPkg.mSignatures) {
5298            try {
5299                Signature[] chainSignatures = sig.getChainSignatures();
5300                for (Signature chainSig : chainSignatures) {
5301                    scannedCompatSet.add(chainSig);
5302                }
5303            } catch (CertificateEncodingException e) {
5304                scannedCompatSet.add(sig);
5305            }
5306        }
5307        /*
5308         * Make sure the expanded scanned set contains all signatures in the
5309         * existing one.
5310         */
5311        if (scannedCompatSet.equals(existingSet)) {
5312            // Migrate the old signatures to the new scheme.
5313            existingSigs.assignSignatures(scannedPkg.mSignatures);
5314            // The new KeySets will be re-added later in the scanning process.
5315            synchronized (mPackages) {
5316                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5317            }
5318            return PackageManager.SIGNATURE_MATCH;
5319        }
5320        return PackageManager.SIGNATURE_NO_MATCH;
5321    }
5322
5323    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5324        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5325        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5326    }
5327
5328    private int compareSignaturesRecover(PackageSignatures existingSigs,
5329            PackageParser.Package scannedPkg) {
5330        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5331            return PackageManager.SIGNATURE_NO_MATCH;
5332        }
5333
5334        String msg = null;
5335        try {
5336            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5337                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5338                        + scannedPkg.packageName);
5339                return PackageManager.SIGNATURE_MATCH;
5340            }
5341        } catch (CertificateException e) {
5342            msg = e.getMessage();
5343        }
5344
5345        logCriticalInfo(Log.INFO,
5346                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5347        return PackageManager.SIGNATURE_NO_MATCH;
5348    }
5349
5350    @Override
5351    public List<String> getAllPackages() {
5352        synchronized (mPackages) {
5353            return new ArrayList<String>(mPackages.keySet());
5354        }
5355    }
5356
5357    @Override
5358    public String[] getPackagesForUid(int uid) {
5359        final int userId = UserHandle.getUserId(uid);
5360        uid = UserHandle.getAppId(uid);
5361        // reader
5362        synchronized (mPackages) {
5363            Object obj = mSettings.getUserIdLPr(uid);
5364            if (obj instanceof SharedUserSetting) {
5365                final SharedUserSetting sus = (SharedUserSetting) obj;
5366                final int N = sus.packages.size();
5367                String[] res = new String[N];
5368                final Iterator<PackageSetting> it = sus.packages.iterator();
5369                int i = 0;
5370                while (it.hasNext()) {
5371                    PackageSetting ps = it.next();
5372                    if (ps.getInstalled(userId)) {
5373                        res[i++] = ps.name;
5374                    } else {
5375                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5376                    }
5377                }
5378                return res;
5379            } else if (obj instanceof PackageSetting) {
5380                final PackageSetting ps = (PackageSetting) obj;
5381                if (ps.getInstalled(userId)) {
5382                    return new String[]{ps.name};
5383                }
5384            }
5385        }
5386        return null;
5387    }
5388
5389    @Override
5390    public String getNameForUid(int uid) {
5391        // reader
5392        synchronized (mPackages) {
5393            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5394            if (obj instanceof SharedUserSetting) {
5395                final SharedUserSetting sus = (SharedUserSetting) obj;
5396                return sus.name + ":" + sus.userId;
5397            } else if (obj instanceof PackageSetting) {
5398                final PackageSetting ps = (PackageSetting) obj;
5399                return ps.name;
5400            }
5401        }
5402        return null;
5403    }
5404
5405    @Override
5406    public int getUidForSharedUser(String sharedUserName) {
5407        if(sharedUserName == null) {
5408            return -1;
5409        }
5410        // reader
5411        synchronized (mPackages) {
5412            SharedUserSetting suid;
5413            try {
5414                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5415                if (suid != null) {
5416                    return suid.userId;
5417                }
5418            } catch (PackageManagerException ignore) {
5419                // can't happen, but, still need to catch it
5420            }
5421            return -1;
5422        }
5423    }
5424
5425    @Override
5426    public int getFlagsForUid(int uid) {
5427        synchronized (mPackages) {
5428            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5429            if (obj instanceof SharedUserSetting) {
5430                final SharedUserSetting sus = (SharedUserSetting) obj;
5431                return sus.pkgFlags;
5432            } else if (obj instanceof PackageSetting) {
5433                final PackageSetting ps = (PackageSetting) obj;
5434                return ps.pkgFlags;
5435            }
5436        }
5437        return 0;
5438    }
5439
5440    @Override
5441    public int getPrivateFlagsForUid(int uid) {
5442        synchronized (mPackages) {
5443            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5444            if (obj instanceof SharedUserSetting) {
5445                final SharedUserSetting sus = (SharedUserSetting) obj;
5446                return sus.pkgPrivateFlags;
5447            } else if (obj instanceof PackageSetting) {
5448                final PackageSetting ps = (PackageSetting) obj;
5449                return ps.pkgPrivateFlags;
5450            }
5451        }
5452        return 0;
5453    }
5454
5455    @Override
5456    public boolean isUidPrivileged(int uid) {
5457        uid = UserHandle.getAppId(uid);
5458        // reader
5459        synchronized (mPackages) {
5460            Object obj = mSettings.getUserIdLPr(uid);
5461            if (obj instanceof SharedUserSetting) {
5462                final SharedUserSetting sus = (SharedUserSetting) obj;
5463                final Iterator<PackageSetting> it = sus.packages.iterator();
5464                while (it.hasNext()) {
5465                    if (it.next().isPrivileged()) {
5466                        return true;
5467                    }
5468                }
5469            } else if (obj instanceof PackageSetting) {
5470                final PackageSetting ps = (PackageSetting) obj;
5471                return ps.isPrivileged();
5472            }
5473        }
5474        return false;
5475    }
5476
5477    @Override
5478    public String[] getAppOpPermissionPackages(String permissionName) {
5479        synchronized (mPackages) {
5480            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5481            if (pkgs == null) {
5482                return null;
5483            }
5484            return pkgs.toArray(new String[pkgs.size()]);
5485        }
5486    }
5487
5488    @Override
5489    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5490            int flags, int userId) {
5491        try {
5492            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5493
5494            if (!sUserManager.exists(userId)) return null;
5495            flags = updateFlagsForResolve(flags, userId, intent);
5496            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5497                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5498
5499            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5500            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5501                    flags, userId);
5502            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5503
5504            final ResolveInfo bestChoice =
5505                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5506            return bestChoice;
5507        } finally {
5508            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5509        }
5510    }
5511
5512    @Override
5513    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5514        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5515            throw new SecurityException(
5516                    "findPersistentPreferredActivity can only be run by the system");
5517        }
5518        if (!sUserManager.exists(userId)) {
5519            return null;
5520        }
5521        intent = updateIntentForResolve(intent);
5522        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5523        final int flags = updateFlagsForResolve(0, userId, intent);
5524        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5525                userId);
5526        synchronized (mPackages) {
5527            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5528                    userId);
5529        }
5530    }
5531
5532    @Override
5533    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5534            IntentFilter filter, int match, ComponentName activity) {
5535        final int userId = UserHandle.getCallingUserId();
5536        if (DEBUG_PREFERRED) {
5537            Log.v(TAG, "setLastChosenActivity intent=" + intent
5538                + " resolvedType=" + resolvedType
5539                + " flags=" + flags
5540                + " filter=" + filter
5541                + " match=" + match
5542                + " activity=" + activity);
5543            filter.dump(new PrintStreamPrinter(System.out), "    ");
5544        }
5545        intent.setComponent(null);
5546        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5547                userId);
5548        // Find any earlier preferred or last chosen entries and nuke them
5549        findPreferredActivity(intent, resolvedType,
5550                flags, query, 0, false, true, false, userId);
5551        // Add the new activity as the last chosen for this filter
5552        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5553                "Setting last chosen");
5554    }
5555
5556    @Override
5557    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5558        final int userId = UserHandle.getCallingUserId();
5559        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5560        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5561                userId);
5562        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5563                false, false, false, userId);
5564    }
5565
5566    private boolean isEphemeralDisabled() {
5567        // ephemeral apps have been disabled across the board
5568        if (DISABLE_EPHEMERAL_APPS) {
5569            return true;
5570        }
5571        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5572        if (!mSystemReady) {
5573            return true;
5574        }
5575        // we can't get a content resolver until the system is ready; these checks must happen last
5576        final ContentResolver resolver = mContext.getContentResolver();
5577        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5578            return true;
5579        }
5580        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5581    }
5582
5583    private boolean isEphemeralAllowed(
5584            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5585            boolean skipPackageCheck) {
5586        // Short circuit and return early if possible.
5587        if (isEphemeralDisabled()) {
5588            return false;
5589        }
5590        final int callingUser = UserHandle.getCallingUserId();
5591        if (callingUser != UserHandle.USER_SYSTEM) {
5592            return false;
5593        }
5594        if (mEphemeralResolverConnection == null) {
5595            return false;
5596        }
5597        if (mEphemeralInstallerComponent == null) {
5598            return false;
5599        }
5600        if (intent.getComponent() != null) {
5601            return false;
5602        }
5603        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5604            return false;
5605        }
5606        if (!skipPackageCheck && intent.getPackage() != null) {
5607            return false;
5608        }
5609        final boolean isWebUri = hasWebURI(intent);
5610        if (!isWebUri || intent.getData().getHost() == null) {
5611            return false;
5612        }
5613        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5614        synchronized (mPackages) {
5615            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5616            for (int n = 0; n < count; n++) {
5617                ResolveInfo info = resolvedActivities.get(n);
5618                String packageName = info.activityInfo.packageName;
5619                PackageSetting ps = mSettings.mPackages.get(packageName);
5620                if (ps != null) {
5621                    // Try to get the status from User settings first
5622                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5623                    int status = (int) (packedStatus >> 32);
5624                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5625                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5626                        if (DEBUG_EPHEMERAL) {
5627                            Slog.v(TAG, "DENY ephemeral apps;"
5628                                + " pkg: " + packageName + ", status: " + status);
5629                        }
5630                        return false;
5631                    }
5632                }
5633            }
5634        }
5635        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5636        return true;
5637    }
5638
5639    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5640            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5641            int userId) {
5642        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5643                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5644                        callingPackage, userId));
5645        mHandler.sendMessage(msg);
5646    }
5647
5648    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5649            int flags, List<ResolveInfo> query, int userId) {
5650        if (query != null) {
5651            final int N = query.size();
5652            if (N == 1) {
5653                return query.get(0);
5654            } else if (N > 1) {
5655                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5656                // If there is more than one activity with the same priority,
5657                // then let the user decide between them.
5658                ResolveInfo r0 = query.get(0);
5659                ResolveInfo r1 = query.get(1);
5660                if (DEBUG_INTENT_MATCHING || debug) {
5661                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5662                            + r1.activityInfo.name + "=" + r1.priority);
5663                }
5664                // If the first activity has a higher priority, or a different
5665                // default, then it is always desirable to pick it.
5666                if (r0.priority != r1.priority
5667                        || r0.preferredOrder != r1.preferredOrder
5668                        || r0.isDefault != r1.isDefault) {
5669                    return query.get(0);
5670                }
5671                // If we have saved a preference for a preferred activity for
5672                // this Intent, use that.
5673                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5674                        flags, query, r0.priority, true, false, debug, userId);
5675                if (ri != null) {
5676                    return ri;
5677                }
5678                ri = new ResolveInfo(mResolveInfo);
5679                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5680                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5681                // If all of the options come from the same package, show the application's
5682                // label and icon instead of the generic resolver's.
5683                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5684                // and then throw away the ResolveInfo itself, meaning that the caller loses
5685                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5686                // a fallback for this case; we only set the target package's resources on
5687                // the ResolveInfo, not the ActivityInfo.
5688                final String intentPackage = intent.getPackage();
5689                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5690                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5691                    ri.resolvePackageName = intentPackage;
5692                    if (userNeedsBadging(userId)) {
5693                        ri.noResourceId = true;
5694                    } else {
5695                        ri.icon = appi.icon;
5696                    }
5697                    ri.iconResourceId = appi.icon;
5698                    ri.labelRes = appi.labelRes;
5699                }
5700                ri.activityInfo.applicationInfo = new ApplicationInfo(
5701                        ri.activityInfo.applicationInfo);
5702                if (userId != 0) {
5703                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5704                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5705                }
5706                // Make sure that the resolver is displayable in car mode
5707                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5708                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5709                return ri;
5710            }
5711        }
5712        return null;
5713    }
5714
5715    /**
5716     * Return true if the given list is not empty and all of its contents have
5717     * an activityInfo with the given package name.
5718     */
5719    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5720        if (ArrayUtils.isEmpty(list)) {
5721            return false;
5722        }
5723        for (int i = 0, N = list.size(); i < N; i++) {
5724            final ResolveInfo ri = list.get(i);
5725            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5726            if (ai == null || !packageName.equals(ai.packageName)) {
5727                return false;
5728            }
5729        }
5730        return true;
5731    }
5732
5733    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5734            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5735        final int N = query.size();
5736        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5737                .get(userId);
5738        // Get the list of persistent preferred activities that handle the intent
5739        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5740        List<PersistentPreferredActivity> pprefs = ppir != null
5741                ? ppir.queryIntent(intent, resolvedType,
5742                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5743                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5744                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5745                : null;
5746        if (pprefs != null && pprefs.size() > 0) {
5747            final int M = pprefs.size();
5748            for (int i=0; i<M; i++) {
5749                final PersistentPreferredActivity ppa = pprefs.get(i);
5750                if (DEBUG_PREFERRED || debug) {
5751                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5752                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5753                            + "\n  component=" + ppa.mComponent);
5754                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5755                }
5756                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5757                        flags | MATCH_DISABLED_COMPONENTS, userId);
5758                if (DEBUG_PREFERRED || debug) {
5759                    Slog.v(TAG, "Found persistent preferred activity:");
5760                    if (ai != null) {
5761                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5762                    } else {
5763                        Slog.v(TAG, "  null");
5764                    }
5765                }
5766                if (ai == null) {
5767                    // This previously registered persistent preferred activity
5768                    // component is no longer known. Ignore it and do NOT remove it.
5769                    continue;
5770                }
5771                for (int j=0; j<N; j++) {
5772                    final ResolveInfo ri = query.get(j);
5773                    if (!ri.activityInfo.applicationInfo.packageName
5774                            .equals(ai.applicationInfo.packageName)) {
5775                        continue;
5776                    }
5777                    if (!ri.activityInfo.name.equals(ai.name)) {
5778                        continue;
5779                    }
5780                    //  Found a persistent preference that can handle the intent.
5781                    if (DEBUG_PREFERRED || debug) {
5782                        Slog.v(TAG, "Returning persistent preferred activity: " +
5783                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5784                    }
5785                    return ri;
5786                }
5787            }
5788        }
5789        return null;
5790    }
5791
5792    // TODO: handle preferred activities missing while user has amnesia
5793    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5794            List<ResolveInfo> query, int priority, boolean always,
5795            boolean removeMatches, boolean debug, int userId) {
5796        if (!sUserManager.exists(userId)) return null;
5797        flags = updateFlagsForResolve(flags, userId, intent);
5798        intent = updateIntentForResolve(intent);
5799        // writer
5800        synchronized (mPackages) {
5801            // Try to find a matching persistent preferred activity.
5802            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5803                    debug, userId);
5804
5805            // If a persistent preferred activity matched, use it.
5806            if (pri != null) {
5807                return pri;
5808            }
5809
5810            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5811            // Get the list of preferred activities that handle the intent
5812            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5813            List<PreferredActivity> prefs = pir != null
5814                    ? pir.queryIntent(intent, resolvedType,
5815                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5816                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5817                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5818                    : null;
5819            if (prefs != null && prefs.size() > 0) {
5820                boolean changed = false;
5821                try {
5822                    // First figure out how good the original match set is.
5823                    // We will only allow preferred activities that came
5824                    // from the same match quality.
5825                    int match = 0;
5826
5827                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5828
5829                    final int N = query.size();
5830                    for (int j=0; j<N; j++) {
5831                        final ResolveInfo ri = query.get(j);
5832                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5833                                + ": 0x" + Integer.toHexString(match));
5834                        if (ri.match > match) {
5835                            match = ri.match;
5836                        }
5837                    }
5838
5839                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5840                            + Integer.toHexString(match));
5841
5842                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5843                    final int M = prefs.size();
5844                    for (int i=0; i<M; i++) {
5845                        final PreferredActivity pa = prefs.get(i);
5846                        if (DEBUG_PREFERRED || debug) {
5847                            Slog.v(TAG, "Checking PreferredActivity ds="
5848                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5849                                    + "\n  component=" + pa.mPref.mComponent);
5850                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5851                        }
5852                        if (pa.mPref.mMatch != match) {
5853                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5854                                    + Integer.toHexString(pa.mPref.mMatch));
5855                            continue;
5856                        }
5857                        // If it's not an "always" type preferred activity and that's what we're
5858                        // looking for, skip it.
5859                        if (always && !pa.mPref.mAlways) {
5860                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5861                            continue;
5862                        }
5863                        final ActivityInfo ai = getActivityInfo(
5864                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5865                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5866                                userId);
5867                        if (DEBUG_PREFERRED || debug) {
5868                            Slog.v(TAG, "Found preferred activity:");
5869                            if (ai != null) {
5870                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5871                            } else {
5872                                Slog.v(TAG, "  null");
5873                            }
5874                        }
5875                        if (ai == null) {
5876                            // This previously registered preferred activity
5877                            // component is no longer known.  Most likely an update
5878                            // to the app was installed and in the new version this
5879                            // component no longer exists.  Clean it up by removing
5880                            // it from the preferred activities list, and skip it.
5881                            Slog.w(TAG, "Removing dangling preferred activity: "
5882                                    + pa.mPref.mComponent);
5883                            pir.removeFilter(pa);
5884                            changed = true;
5885                            continue;
5886                        }
5887                        for (int j=0; j<N; j++) {
5888                            final ResolveInfo ri = query.get(j);
5889                            if (!ri.activityInfo.applicationInfo.packageName
5890                                    .equals(ai.applicationInfo.packageName)) {
5891                                continue;
5892                            }
5893                            if (!ri.activityInfo.name.equals(ai.name)) {
5894                                continue;
5895                            }
5896
5897                            if (removeMatches) {
5898                                pir.removeFilter(pa);
5899                                changed = true;
5900                                if (DEBUG_PREFERRED) {
5901                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5902                                }
5903                                break;
5904                            }
5905
5906                            // Okay we found a previously set preferred or last chosen app.
5907                            // If the result set is different from when this
5908                            // was created, we need to clear it and re-ask the
5909                            // user their preference, if we're looking for an "always" type entry.
5910                            if (always && !pa.mPref.sameSet(query)) {
5911                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5912                                        + intent + " type " + resolvedType);
5913                                if (DEBUG_PREFERRED) {
5914                                    Slog.v(TAG, "Removing preferred activity since set changed "
5915                                            + pa.mPref.mComponent);
5916                                }
5917                                pir.removeFilter(pa);
5918                                // Re-add the filter as a "last chosen" entry (!always)
5919                                PreferredActivity lastChosen = new PreferredActivity(
5920                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5921                                pir.addFilter(lastChosen);
5922                                changed = true;
5923                                return null;
5924                            }
5925
5926                            // Yay! Either the set matched or we're looking for the last chosen
5927                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5928                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5929                            return ri;
5930                        }
5931                    }
5932                } finally {
5933                    if (changed) {
5934                        if (DEBUG_PREFERRED) {
5935                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5936                        }
5937                        scheduleWritePackageRestrictionsLocked(userId);
5938                    }
5939                }
5940            }
5941        }
5942        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5943        return null;
5944    }
5945
5946    /*
5947     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5948     */
5949    @Override
5950    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5951            int targetUserId) {
5952        mContext.enforceCallingOrSelfPermission(
5953                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5954        List<CrossProfileIntentFilter> matches =
5955                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5956        if (matches != null) {
5957            int size = matches.size();
5958            for (int i = 0; i < size; i++) {
5959                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5960            }
5961        }
5962        if (hasWebURI(intent)) {
5963            // cross-profile app linking works only towards the parent.
5964            final UserInfo parent = getProfileParent(sourceUserId);
5965            synchronized(mPackages) {
5966                int flags = updateFlagsForResolve(0, parent.id, intent);
5967                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5968                        intent, resolvedType, flags, sourceUserId, parent.id);
5969                return xpDomainInfo != null;
5970            }
5971        }
5972        return false;
5973    }
5974
5975    private UserInfo getProfileParent(int userId) {
5976        final long identity = Binder.clearCallingIdentity();
5977        try {
5978            return sUserManager.getProfileParent(userId);
5979        } finally {
5980            Binder.restoreCallingIdentity(identity);
5981        }
5982    }
5983
5984    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5985            String resolvedType, int userId) {
5986        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5987        if (resolver != null) {
5988            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5989                    false /*visibleToEphemeral*/, false /*isInstant*/, userId);
5990        }
5991        return null;
5992    }
5993
5994    @Override
5995    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5996            String resolvedType, int flags, int userId) {
5997        try {
5998            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5999
6000            return new ParceledListSlice<>(
6001                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6002        } finally {
6003            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6004        }
6005    }
6006
6007    /**
6008     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
6009     * ephemeral, returns {@code null}.
6010     */
6011    private String getEphemeralPackageName(int callingUid) {
6012        final int appId = UserHandle.getAppId(callingUid);
6013        synchronized (mPackages) {
6014            final Object obj = mSettings.getUserIdLPr(appId);
6015            if (obj instanceof PackageSetting) {
6016                final PackageSetting ps = (PackageSetting) obj;
6017                return ps.pkg.applicationInfo.isInstantApp() ? ps.pkg.packageName : null;
6018            }
6019        }
6020        return null;
6021    }
6022
6023    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6024            String resolvedType, int flags, int userId) {
6025        if (!sUserManager.exists(userId)) return Collections.emptyList();
6026        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
6027        flags = updateFlagsForResolve(flags, userId, intent);
6028        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6029                false /* requireFullPermission */, false /* checkShell */,
6030                "query intent activities");
6031        ComponentName comp = intent.getComponent();
6032        if (comp == null) {
6033            if (intent.getSelector() != null) {
6034                intent = intent.getSelector();
6035                comp = intent.getComponent();
6036            }
6037        }
6038
6039        if (comp != null) {
6040            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6041            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6042            if (ai != null) {
6043                // When specifying an explicit component, we prevent the activity from being
6044                // used when either 1) the calling package is normal and the activity is within
6045                // an ephemeral application or 2) the calling package is ephemeral and the
6046                // activity is not visible to ephemeral applications.
6047                boolean matchEphemeral =
6048                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
6049                boolean ephemeralVisibleOnly =
6050                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
6051                boolean blockResolution =
6052                        (!matchEphemeral && ephemeralPkgName == null
6053                                && (ai.applicationInfo.privateFlags
6054                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
6055                        || (ephemeralVisibleOnly && ephemeralPkgName != null
6056                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
6057                if (!blockResolution) {
6058                    final ResolveInfo ri = new ResolveInfo();
6059                    ri.activityInfo = ai;
6060                    list.add(ri);
6061                }
6062            }
6063            return list;
6064        }
6065
6066        // reader
6067        boolean sortResult = false;
6068        boolean addEphemeral = false;
6069        List<ResolveInfo> result;
6070        final String pkgName = intent.getPackage();
6071        synchronized (mPackages) {
6072            if (pkgName == null) {
6073                List<CrossProfileIntentFilter> matchingFilters =
6074                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6075                // Check for results that need to skip the current profile.
6076                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6077                        resolvedType, flags, userId);
6078                if (xpResolveInfo != null) {
6079                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6080                    xpResult.add(xpResolveInfo);
6081                    return filterForEphemeral(
6082                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
6083                }
6084
6085                // Check for results in the current profile.
6086                result = filterIfNotSystemUser(mActivities.queryIntent(
6087                        intent, resolvedType, flags, userId), userId);
6088                addEphemeral =
6089                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6090
6091                // Check for cross profile results.
6092                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6093                xpResolveInfo = queryCrossProfileIntents(
6094                        matchingFilters, intent, resolvedType, flags, userId,
6095                        hasNonNegativePriorityResult);
6096                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6097                    boolean isVisibleToUser = filterIfNotSystemUser(
6098                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6099                    if (isVisibleToUser) {
6100                        result.add(xpResolveInfo);
6101                        sortResult = true;
6102                    }
6103                }
6104                if (hasWebURI(intent)) {
6105                    CrossProfileDomainInfo xpDomainInfo = null;
6106                    final UserInfo parent = getProfileParent(userId);
6107                    if (parent != null) {
6108                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6109                                flags, userId, parent.id);
6110                    }
6111                    if (xpDomainInfo != null) {
6112                        if (xpResolveInfo != null) {
6113                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6114                            // in the result.
6115                            result.remove(xpResolveInfo);
6116                        }
6117                        if (result.size() == 0 && !addEphemeral) {
6118                            // No result in current profile, but found candidate in parent user.
6119                            // And we are not going to add emphemeral app, so we can return the
6120                            // result straight away.
6121                            result.add(xpDomainInfo.resolveInfo);
6122                            return filterForEphemeral(result, ephemeralPkgName);
6123                        }
6124                    } else if (result.size() <= 1 && !addEphemeral) {
6125                        // No result in parent user and <= 1 result in current profile, and we
6126                        // are not going to add emphemeral app, so we can return the result without
6127                        // further processing.
6128                        return filterForEphemeral(result, ephemeralPkgName);
6129                    }
6130                    // We have more than one candidate (combining results from current and parent
6131                    // profile), so we need filtering and sorting.
6132                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6133                            intent, flags, result, xpDomainInfo, userId);
6134                    sortResult = true;
6135                }
6136            } else {
6137                final PackageParser.Package pkg = mPackages.get(pkgName);
6138                if (pkg != null) {
6139                    result = filterForEphemeral(filterIfNotSystemUser(
6140                            mActivities.queryIntentForPackage(
6141                                    intent, resolvedType, flags, pkg.activities, userId),
6142                            userId), ephemeralPkgName);
6143                } else {
6144                    // the caller wants to resolve for a particular package; however, there
6145                    // were no installed results, so, try to find an ephemeral result
6146                    addEphemeral = isEphemeralAllowed(
6147                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6148                    result = new ArrayList<ResolveInfo>();
6149                }
6150            }
6151        }
6152        if (addEphemeral) {
6153            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6154            final EphemeralRequest requestObject = new EphemeralRequest(
6155                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6156                    null /*launchIntent*/, null /*callingPackage*/, userId);
6157            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6158                    mContext, mEphemeralResolverConnection, requestObject);
6159            if (intentInfo != null) {
6160                if (DEBUG_EPHEMERAL) {
6161                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6162                }
6163                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6164                ephemeralInstaller.ephemeralResponse = intentInfo;
6165                // make sure this resolver is the default
6166                ephemeralInstaller.isDefault = true;
6167                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6168                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6169                // add a non-generic filter
6170                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6171                ephemeralInstaller.filter.addDataPath(
6172                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6173                result.add(ephemeralInstaller);
6174            }
6175            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6176        }
6177        if (sortResult) {
6178            Collections.sort(result, mResolvePrioritySorter);
6179        }
6180        return filterForEphemeral(result, ephemeralPkgName);
6181    }
6182
6183    private static class CrossProfileDomainInfo {
6184        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6185        ResolveInfo resolveInfo;
6186        /* Best domain verification status of the activities found in the other profile */
6187        int bestDomainVerificationStatus;
6188    }
6189
6190    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6191            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6192        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6193                sourceUserId)) {
6194            return null;
6195        }
6196        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6197                resolvedType, flags, parentUserId);
6198
6199        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6200            return null;
6201        }
6202        CrossProfileDomainInfo result = null;
6203        int size = resultTargetUser.size();
6204        for (int i = 0; i < size; i++) {
6205            ResolveInfo riTargetUser = resultTargetUser.get(i);
6206            // Intent filter verification is only for filters that specify a host. So don't return
6207            // those that handle all web uris.
6208            if (riTargetUser.handleAllWebDataURI) {
6209                continue;
6210            }
6211            String packageName = riTargetUser.activityInfo.packageName;
6212            PackageSetting ps = mSettings.mPackages.get(packageName);
6213            if (ps == null) {
6214                continue;
6215            }
6216            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6217            int status = (int)(verificationState >> 32);
6218            if (result == null) {
6219                result = new CrossProfileDomainInfo();
6220                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6221                        sourceUserId, parentUserId);
6222                result.bestDomainVerificationStatus = status;
6223            } else {
6224                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6225                        result.bestDomainVerificationStatus);
6226            }
6227        }
6228        // Don't consider matches with status NEVER across profiles.
6229        if (result != null && result.bestDomainVerificationStatus
6230                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6231            return null;
6232        }
6233        return result;
6234    }
6235
6236    /**
6237     * Verification statuses are ordered from the worse to the best, except for
6238     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6239     */
6240    private int bestDomainVerificationStatus(int status1, int status2) {
6241        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6242            return status2;
6243        }
6244        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6245            return status1;
6246        }
6247        return (int) MathUtils.max(status1, status2);
6248    }
6249
6250    private boolean isUserEnabled(int userId) {
6251        long callingId = Binder.clearCallingIdentity();
6252        try {
6253            UserInfo userInfo = sUserManager.getUserInfo(userId);
6254            return userInfo != null && userInfo.isEnabled();
6255        } finally {
6256            Binder.restoreCallingIdentity(callingId);
6257        }
6258    }
6259
6260    /**
6261     * Filter out activities with systemUserOnly flag set, when current user is not System.
6262     *
6263     * @return filtered list
6264     */
6265    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6266        if (userId == UserHandle.USER_SYSTEM) {
6267            return resolveInfos;
6268        }
6269        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6270            ResolveInfo info = resolveInfos.get(i);
6271            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6272                resolveInfos.remove(i);
6273            }
6274        }
6275        return resolveInfos;
6276    }
6277
6278    /**
6279     * Filters out ephemeral activities.
6280     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6281     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6282     *
6283     * @param resolveInfos The pre-filtered list of resolved activities
6284     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6285     *          is performed.
6286     * @return A filtered list of resolved activities.
6287     */
6288    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6289            String ephemeralPkgName) {
6290        if (ephemeralPkgName == null) {
6291            return resolveInfos;
6292        }
6293        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6294            ResolveInfo info = resolveInfos.get(i);
6295            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6296            // allow activities that are defined in the provided package
6297            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6298                continue;
6299            }
6300            // allow activities that have been explicitly exposed to ephemeral apps
6301            if (!isEphemeralApp
6302                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6303                continue;
6304            }
6305            resolveInfos.remove(i);
6306        }
6307        return resolveInfos;
6308    }
6309
6310    /**
6311     * @param resolveInfos list of resolve infos in descending priority order
6312     * @return if the list contains a resolve info with non-negative priority
6313     */
6314    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6315        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6316    }
6317
6318    private static boolean hasWebURI(Intent intent) {
6319        if (intent.getData() == null) {
6320            return false;
6321        }
6322        final String scheme = intent.getScheme();
6323        if (TextUtils.isEmpty(scheme)) {
6324            return false;
6325        }
6326        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6327    }
6328
6329    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6330            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6331            int userId) {
6332        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6333
6334        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6335            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6336                    candidates.size());
6337        }
6338
6339        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6340        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6341        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6342        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6343        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6344        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6345
6346        synchronized (mPackages) {
6347            final int count = candidates.size();
6348            // First, try to use linked apps. Partition the candidates into four lists:
6349            // one for the final results, one for the "do not use ever", one for "undefined status"
6350            // and finally one for "browser app type".
6351            for (int n=0; n<count; n++) {
6352                ResolveInfo info = candidates.get(n);
6353                String packageName = info.activityInfo.packageName;
6354                PackageSetting ps = mSettings.mPackages.get(packageName);
6355                if (ps != null) {
6356                    // Add to the special match all list (Browser use case)
6357                    if (info.handleAllWebDataURI) {
6358                        matchAllList.add(info);
6359                        continue;
6360                    }
6361                    // Try to get the status from User settings first
6362                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6363                    int status = (int)(packedStatus >> 32);
6364                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6365                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6366                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6367                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6368                                    + " : linkgen=" + linkGeneration);
6369                        }
6370                        // Use link-enabled generation as preferredOrder, i.e.
6371                        // prefer newly-enabled over earlier-enabled.
6372                        info.preferredOrder = linkGeneration;
6373                        alwaysList.add(info);
6374                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6375                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6376                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6377                        }
6378                        neverList.add(info);
6379                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6380                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6381                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6382                        }
6383                        alwaysAskList.add(info);
6384                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6385                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6386                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6387                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6388                        }
6389                        undefinedList.add(info);
6390                    }
6391                }
6392            }
6393
6394            // We'll want to include browser possibilities in a few cases
6395            boolean includeBrowser = false;
6396
6397            // First try to add the "always" resolution(s) for the current user, if any
6398            if (alwaysList.size() > 0) {
6399                result.addAll(alwaysList);
6400            } else {
6401                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6402                result.addAll(undefinedList);
6403                // Maybe add one for the other profile.
6404                if (xpDomainInfo != null && (
6405                        xpDomainInfo.bestDomainVerificationStatus
6406                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6407                    result.add(xpDomainInfo.resolveInfo);
6408                }
6409                includeBrowser = true;
6410            }
6411
6412            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6413            // If there were 'always' entries their preferred order has been set, so we also
6414            // back that off to make the alternatives equivalent
6415            if (alwaysAskList.size() > 0) {
6416                for (ResolveInfo i : result) {
6417                    i.preferredOrder = 0;
6418                }
6419                result.addAll(alwaysAskList);
6420                includeBrowser = true;
6421            }
6422
6423            if (includeBrowser) {
6424                // Also add browsers (all of them or only the default one)
6425                if (DEBUG_DOMAIN_VERIFICATION) {
6426                    Slog.v(TAG, "   ...including browsers in candidate set");
6427                }
6428                if ((matchFlags & MATCH_ALL) != 0) {
6429                    result.addAll(matchAllList);
6430                } else {
6431                    // Browser/generic handling case.  If there's a default browser, go straight
6432                    // to that (but only if there is no other higher-priority match).
6433                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6434                    int maxMatchPrio = 0;
6435                    ResolveInfo defaultBrowserMatch = null;
6436                    final int numCandidates = matchAllList.size();
6437                    for (int n = 0; n < numCandidates; n++) {
6438                        ResolveInfo info = matchAllList.get(n);
6439                        // track the highest overall match priority...
6440                        if (info.priority > maxMatchPrio) {
6441                            maxMatchPrio = info.priority;
6442                        }
6443                        // ...and the highest-priority default browser match
6444                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6445                            if (defaultBrowserMatch == null
6446                                    || (defaultBrowserMatch.priority < info.priority)) {
6447                                if (debug) {
6448                                    Slog.v(TAG, "Considering default browser match " + info);
6449                                }
6450                                defaultBrowserMatch = info;
6451                            }
6452                        }
6453                    }
6454                    if (defaultBrowserMatch != null
6455                            && defaultBrowserMatch.priority >= maxMatchPrio
6456                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6457                    {
6458                        if (debug) {
6459                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6460                        }
6461                        result.add(defaultBrowserMatch);
6462                    } else {
6463                        result.addAll(matchAllList);
6464                    }
6465                }
6466
6467                // If there is nothing selected, add all candidates and remove the ones that the user
6468                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6469                if (result.size() == 0) {
6470                    result.addAll(candidates);
6471                    result.removeAll(neverList);
6472                }
6473            }
6474        }
6475        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6476            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6477                    result.size());
6478            for (ResolveInfo info : result) {
6479                Slog.v(TAG, "  + " + info.activityInfo);
6480            }
6481        }
6482        return result;
6483    }
6484
6485    // Returns a packed value as a long:
6486    //
6487    // high 'int'-sized word: link status: undefined/ask/never/always.
6488    // low 'int'-sized word: relative priority among 'always' results.
6489    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6490        long result = ps.getDomainVerificationStatusForUser(userId);
6491        // if none available, get the master status
6492        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6493            if (ps.getIntentFilterVerificationInfo() != null) {
6494                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6495            }
6496        }
6497        return result;
6498    }
6499
6500    private ResolveInfo querySkipCurrentProfileIntents(
6501            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6502            int flags, int sourceUserId) {
6503        if (matchingFilters != null) {
6504            int size = matchingFilters.size();
6505            for (int i = 0; i < size; i ++) {
6506                CrossProfileIntentFilter filter = matchingFilters.get(i);
6507                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6508                    // Checking if there are activities in the target user that can handle the
6509                    // intent.
6510                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6511                            resolvedType, flags, sourceUserId);
6512                    if (resolveInfo != null) {
6513                        return resolveInfo;
6514                    }
6515                }
6516            }
6517        }
6518        return null;
6519    }
6520
6521    // Return matching ResolveInfo in target user if any.
6522    private ResolveInfo queryCrossProfileIntents(
6523            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6524            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6525        if (matchingFilters != null) {
6526            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6527            // match the same intent. For performance reasons, it is better not to
6528            // run queryIntent twice for the same userId
6529            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6530            int size = matchingFilters.size();
6531            for (int i = 0; i < size; i++) {
6532                CrossProfileIntentFilter filter = matchingFilters.get(i);
6533                int targetUserId = filter.getTargetUserId();
6534                boolean skipCurrentProfile =
6535                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6536                boolean skipCurrentProfileIfNoMatchFound =
6537                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6538                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6539                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6540                    // Checking if there are activities in the target user that can handle the
6541                    // intent.
6542                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6543                            resolvedType, flags, sourceUserId);
6544                    if (resolveInfo != null) return resolveInfo;
6545                    alreadyTriedUserIds.put(targetUserId, true);
6546                }
6547            }
6548        }
6549        return null;
6550    }
6551
6552    /**
6553     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6554     * will forward the intent to the filter's target user.
6555     * Otherwise, returns null.
6556     */
6557    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6558            String resolvedType, int flags, int sourceUserId) {
6559        int targetUserId = filter.getTargetUserId();
6560        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6561                resolvedType, flags, targetUserId);
6562        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6563            // If all the matches in the target profile are suspended, return null.
6564            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6565                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6566                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6567                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6568                            targetUserId);
6569                }
6570            }
6571        }
6572        return null;
6573    }
6574
6575    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6576            int sourceUserId, int targetUserId) {
6577        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6578        long ident = Binder.clearCallingIdentity();
6579        boolean targetIsProfile;
6580        try {
6581            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6582        } finally {
6583            Binder.restoreCallingIdentity(ident);
6584        }
6585        String className;
6586        if (targetIsProfile) {
6587            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6588        } else {
6589            className = FORWARD_INTENT_TO_PARENT;
6590        }
6591        ComponentName forwardingActivityComponentName = new ComponentName(
6592                mAndroidApplication.packageName, className);
6593        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6594                sourceUserId);
6595        if (!targetIsProfile) {
6596            forwardingActivityInfo.showUserIcon = targetUserId;
6597            forwardingResolveInfo.noResourceId = true;
6598        }
6599        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6600        forwardingResolveInfo.priority = 0;
6601        forwardingResolveInfo.preferredOrder = 0;
6602        forwardingResolveInfo.match = 0;
6603        forwardingResolveInfo.isDefault = true;
6604        forwardingResolveInfo.filter = filter;
6605        forwardingResolveInfo.targetUserId = targetUserId;
6606        return forwardingResolveInfo;
6607    }
6608
6609    @Override
6610    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6611            Intent[] specifics, String[] specificTypes, Intent intent,
6612            String resolvedType, int flags, int userId) {
6613        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6614                specificTypes, intent, resolvedType, flags, userId));
6615    }
6616
6617    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6618            Intent[] specifics, String[] specificTypes, Intent intent,
6619            String resolvedType, int flags, int userId) {
6620        if (!sUserManager.exists(userId)) return Collections.emptyList();
6621        flags = updateFlagsForResolve(flags, userId, intent);
6622        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6623                false /* requireFullPermission */, false /* checkShell */,
6624                "query intent activity options");
6625        final String resultsAction = intent.getAction();
6626
6627        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6628                | PackageManager.GET_RESOLVED_FILTER, userId);
6629
6630        if (DEBUG_INTENT_MATCHING) {
6631            Log.v(TAG, "Query " + intent + ": " + results);
6632        }
6633
6634        int specificsPos = 0;
6635        int N;
6636
6637        // todo: note that the algorithm used here is O(N^2).  This
6638        // isn't a problem in our current environment, but if we start running
6639        // into situations where we have more than 5 or 10 matches then this
6640        // should probably be changed to something smarter...
6641
6642        // First we go through and resolve each of the specific items
6643        // that were supplied, taking care of removing any corresponding
6644        // duplicate items in the generic resolve list.
6645        if (specifics != null) {
6646            for (int i=0; i<specifics.length; i++) {
6647                final Intent sintent = specifics[i];
6648                if (sintent == null) {
6649                    continue;
6650                }
6651
6652                if (DEBUG_INTENT_MATCHING) {
6653                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6654                }
6655
6656                String action = sintent.getAction();
6657                if (resultsAction != null && resultsAction.equals(action)) {
6658                    // If this action was explicitly requested, then don't
6659                    // remove things that have it.
6660                    action = null;
6661                }
6662
6663                ResolveInfo ri = null;
6664                ActivityInfo ai = null;
6665
6666                ComponentName comp = sintent.getComponent();
6667                if (comp == null) {
6668                    ri = resolveIntent(
6669                        sintent,
6670                        specificTypes != null ? specificTypes[i] : null,
6671                            flags, userId);
6672                    if (ri == null) {
6673                        continue;
6674                    }
6675                    if (ri == mResolveInfo) {
6676                        // ACK!  Must do something better with this.
6677                    }
6678                    ai = ri.activityInfo;
6679                    comp = new ComponentName(ai.applicationInfo.packageName,
6680                            ai.name);
6681                } else {
6682                    ai = getActivityInfo(comp, flags, userId);
6683                    if (ai == null) {
6684                        continue;
6685                    }
6686                }
6687
6688                // Look for any generic query activities that are duplicates
6689                // of this specific one, and remove them from the results.
6690                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6691                N = results.size();
6692                int j;
6693                for (j=specificsPos; j<N; j++) {
6694                    ResolveInfo sri = results.get(j);
6695                    if ((sri.activityInfo.name.equals(comp.getClassName())
6696                            && sri.activityInfo.applicationInfo.packageName.equals(
6697                                    comp.getPackageName()))
6698                        || (action != null && sri.filter.matchAction(action))) {
6699                        results.remove(j);
6700                        if (DEBUG_INTENT_MATCHING) Log.v(
6701                            TAG, "Removing duplicate item from " + j
6702                            + " due to specific " + specificsPos);
6703                        if (ri == null) {
6704                            ri = sri;
6705                        }
6706                        j--;
6707                        N--;
6708                    }
6709                }
6710
6711                // Add this specific item to its proper place.
6712                if (ri == null) {
6713                    ri = new ResolveInfo();
6714                    ri.activityInfo = ai;
6715                }
6716                results.add(specificsPos, ri);
6717                ri.specificIndex = i;
6718                specificsPos++;
6719            }
6720        }
6721
6722        // Now we go through the remaining generic results and remove any
6723        // duplicate actions that are found here.
6724        N = results.size();
6725        for (int i=specificsPos; i<N-1; i++) {
6726            final ResolveInfo rii = results.get(i);
6727            if (rii.filter == null) {
6728                continue;
6729            }
6730
6731            // Iterate over all of the actions of this result's intent
6732            // filter...  typically this should be just one.
6733            final Iterator<String> it = rii.filter.actionsIterator();
6734            if (it == null) {
6735                continue;
6736            }
6737            while (it.hasNext()) {
6738                final String action = it.next();
6739                if (resultsAction != null && resultsAction.equals(action)) {
6740                    // If this action was explicitly requested, then don't
6741                    // remove things that have it.
6742                    continue;
6743                }
6744                for (int j=i+1; j<N; j++) {
6745                    final ResolveInfo rij = results.get(j);
6746                    if (rij.filter != null && rij.filter.hasAction(action)) {
6747                        results.remove(j);
6748                        if (DEBUG_INTENT_MATCHING) Log.v(
6749                            TAG, "Removing duplicate item from " + j
6750                            + " due to action " + action + " at " + i);
6751                        j--;
6752                        N--;
6753                    }
6754                }
6755            }
6756
6757            // If the caller didn't request filter information, drop it now
6758            // so we don't have to marshall/unmarshall it.
6759            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6760                rii.filter = null;
6761            }
6762        }
6763
6764        // Filter out the caller activity if so requested.
6765        if (caller != null) {
6766            N = results.size();
6767            for (int i=0; i<N; i++) {
6768                ActivityInfo ainfo = results.get(i).activityInfo;
6769                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6770                        && caller.getClassName().equals(ainfo.name)) {
6771                    results.remove(i);
6772                    break;
6773                }
6774            }
6775        }
6776
6777        // If the caller didn't request filter information,
6778        // drop them now so we don't have to
6779        // marshall/unmarshall it.
6780        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6781            N = results.size();
6782            for (int i=0; i<N; i++) {
6783                results.get(i).filter = null;
6784            }
6785        }
6786
6787        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6788        return results;
6789    }
6790
6791    @Override
6792    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6793            String resolvedType, int flags, int userId) {
6794        return new ParceledListSlice<>(
6795                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6796    }
6797
6798    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6799            String resolvedType, int flags, int userId) {
6800        if (!sUserManager.exists(userId)) return Collections.emptyList();
6801        flags = updateFlagsForResolve(flags, userId, intent);
6802        ComponentName comp = intent.getComponent();
6803        if (comp == null) {
6804            if (intent.getSelector() != null) {
6805                intent = intent.getSelector();
6806                comp = intent.getComponent();
6807            }
6808        }
6809        if (comp != null) {
6810            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6811            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6812            if (ai != null) {
6813                ResolveInfo ri = new ResolveInfo();
6814                ri.activityInfo = ai;
6815                list.add(ri);
6816            }
6817            return list;
6818        }
6819
6820        // reader
6821        synchronized (mPackages) {
6822            String pkgName = intent.getPackage();
6823            if (pkgName == null) {
6824                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6825            }
6826            final PackageParser.Package pkg = mPackages.get(pkgName);
6827            if (pkg != null) {
6828                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6829                        userId);
6830            }
6831            return Collections.emptyList();
6832        }
6833    }
6834
6835    @Override
6836    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6837        if (!sUserManager.exists(userId)) return null;
6838        flags = updateFlagsForResolve(flags, userId, intent);
6839        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6840        if (query != null) {
6841            if (query.size() >= 1) {
6842                // If there is more than one service with the same priority,
6843                // just arbitrarily pick the first one.
6844                return query.get(0);
6845            }
6846        }
6847        return null;
6848    }
6849
6850    @Override
6851    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6852            String resolvedType, int flags, int userId) {
6853        return new ParceledListSlice<>(
6854                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6855    }
6856
6857    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6858            String resolvedType, int flags, int userId) {
6859        if (!sUserManager.exists(userId)) return Collections.emptyList();
6860        flags = updateFlagsForResolve(flags, userId, intent);
6861        ComponentName comp = intent.getComponent();
6862        if (comp == null) {
6863            if (intent.getSelector() != null) {
6864                intent = intent.getSelector();
6865                comp = intent.getComponent();
6866            }
6867        }
6868        if (comp != null) {
6869            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6870            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6871            if (si != null) {
6872                final ResolveInfo ri = new ResolveInfo();
6873                ri.serviceInfo = si;
6874                list.add(ri);
6875            }
6876            return list;
6877        }
6878
6879        // reader
6880        synchronized (mPackages) {
6881            String pkgName = intent.getPackage();
6882            if (pkgName == null) {
6883                return mServices.queryIntent(intent, resolvedType, flags, userId);
6884            }
6885            final PackageParser.Package pkg = mPackages.get(pkgName);
6886            if (pkg != null) {
6887                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6888                        userId);
6889            }
6890            return Collections.emptyList();
6891        }
6892    }
6893
6894    @Override
6895    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6896            String resolvedType, int flags, int userId) {
6897        return new ParceledListSlice<>(
6898                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6899    }
6900
6901    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6902            Intent intent, String resolvedType, int flags, int userId) {
6903        if (!sUserManager.exists(userId)) return Collections.emptyList();
6904        flags = updateFlagsForResolve(flags, userId, intent);
6905        ComponentName comp = intent.getComponent();
6906        if (comp == null) {
6907            if (intent.getSelector() != null) {
6908                intent = intent.getSelector();
6909                comp = intent.getComponent();
6910            }
6911        }
6912        if (comp != null) {
6913            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6914            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6915            if (pi != null) {
6916                final ResolveInfo ri = new ResolveInfo();
6917                ri.providerInfo = pi;
6918                list.add(ri);
6919            }
6920            return list;
6921        }
6922
6923        // reader
6924        synchronized (mPackages) {
6925            String pkgName = intent.getPackage();
6926            if (pkgName == null) {
6927                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6928            }
6929            final PackageParser.Package pkg = mPackages.get(pkgName);
6930            if (pkg != null) {
6931                return mProviders.queryIntentForPackage(
6932                        intent, resolvedType, flags, pkg.providers, userId);
6933            }
6934            return Collections.emptyList();
6935        }
6936    }
6937
6938    @Override
6939    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6940        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6941        flags = updateFlagsForPackage(flags, userId, null);
6942        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6943        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6944                true /* requireFullPermission */, false /* checkShell */,
6945                "get installed packages");
6946
6947        // writer
6948        synchronized (mPackages) {
6949            ArrayList<PackageInfo> list;
6950            if (listUninstalled) {
6951                list = new ArrayList<>(mSettings.mPackages.size());
6952                for (PackageSetting ps : mSettings.mPackages.values()) {
6953                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6954                        continue;
6955                    }
6956                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6957                    if (pi != null) {
6958                        list.add(pi);
6959                    }
6960                }
6961            } else {
6962                list = new ArrayList<>(mPackages.size());
6963                for (PackageParser.Package p : mPackages.values()) {
6964                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6965                            Binder.getCallingUid(), userId)) {
6966                        continue;
6967                    }
6968                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6969                            p.mExtras, flags, userId);
6970                    if (pi != null) {
6971                        list.add(pi);
6972                    }
6973                }
6974            }
6975
6976            return new ParceledListSlice<>(list);
6977        }
6978    }
6979
6980    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6981            String[] permissions, boolean[] tmp, int flags, int userId) {
6982        int numMatch = 0;
6983        final PermissionsState permissionsState = ps.getPermissionsState();
6984        for (int i=0; i<permissions.length; i++) {
6985            final String permission = permissions[i];
6986            if (permissionsState.hasPermission(permission, userId)) {
6987                tmp[i] = true;
6988                numMatch++;
6989            } else {
6990                tmp[i] = false;
6991            }
6992        }
6993        if (numMatch == 0) {
6994            return;
6995        }
6996        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6997
6998        // The above might return null in cases of uninstalled apps or install-state
6999        // skew across users/profiles.
7000        if (pi != null) {
7001            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7002                if (numMatch == permissions.length) {
7003                    pi.requestedPermissions = permissions;
7004                } else {
7005                    pi.requestedPermissions = new String[numMatch];
7006                    numMatch = 0;
7007                    for (int i=0; i<permissions.length; i++) {
7008                        if (tmp[i]) {
7009                            pi.requestedPermissions[numMatch] = permissions[i];
7010                            numMatch++;
7011                        }
7012                    }
7013                }
7014            }
7015            list.add(pi);
7016        }
7017    }
7018
7019    @Override
7020    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7021            String[] permissions, int flags, int userId) {
7022        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7023        flags = updateFlagsForPackage(flags, userId, permissions);
7024        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7025                true /* requireFullPermission */, false /* checkShell */,
7026                "get packages holding permissions");
7027        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7028
7029        // writer
7030        synchronized (mPackages) {
7031            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7032            boolean[] tmpBools = new boolean[permissions.length];
7033            if (listUninstalled) {
7034                for (PackageSetting ps : mSettings.mPackages.values()) {
7035                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7036                            userId);
7037                }
7038            } else {
7039                for (PackageParser.Package pkg : mPackages.values()) {
7040                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7041                    if (ps != null) {
7042                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7043                                userId);
7044                    }
7045                }
7046            }
7047
7048            return new ParceledListSlice<PackageInfo>(list);
7049        }
7050    }
7051
7052    @Override
7053    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7054        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7055        flags = updateFlagsForApplication(flags, userId, null);
7056        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7057
7058        // writer
7059        synchronized (mPackages) {
7060            ArrayList<ApplicationInfo> list;
7061            if (listUninstalled) {
7062                list = new ArrayList<>(mSettings.mPackages.size());
7063                for (PackageSetting ps : mSettings.mPackages.values()) {
7064                    ApplicationInfo ai;
7065                    int effectiveFlags = flags;
7066                    if (ps.isSystem()) {
7067                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7068                    }
7069                    if (ps.pkg != null) {
7070                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7071                            continue;
7072                        }
7073                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7074                                ps.readUserState(userId), userId);
7075                        if (ai != null) {
7076                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7077                        }
7078                    } else {
7079                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7080                        // and already converts to externally visible package name
7081                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7082                                Binder.getCallingUid(), effectiveFlags, userId);
7083                    }
7084                    if (ai != null) {
7085                        list.add(ai);
7086                    }
7087                }
7088            } else {
7089                list = new ArrayList<>(mPackages.size());
7090                for (PackageParser.Package p : mPackages.values()) {
7091                    if (p.mExtras != null) {
7092                        PackageSetting ps = (PackageSetting) p.mExtras;
7093                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7094                            continue;
7095                        }
7096                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7097                                ps.readUserState(userId), userId);
7098                        if (ai != null) {
7099                            ai.packageName = resolveExternalPackageNameLPr(p);
7100                            list.add(ai);
7101                        }
7102                    }
7103                }
7104            }
7105
7106            return new ParceledListSlice<>(list);
7107        }
7108    }
7109
7110    @Override
7111    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7112        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7113            return null;
7114        }
7115
7116        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7117                "getEphemeralApplications");
7118        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7119                true /* requireFullPermission */, false /* checkShell */,
7120                "getEphemeralApplications");
7121        synchronized (mPackages) {
7122            List<InstantAppInfo> instantApps = mInstantAppRegistry
7123                    .getInstantAppsLPr(userId);
7124            if (instantApps != null) {
7125                return new ParceledListSlice<>(instantApps);
7126            }
7127        }
7128        return null;
7129    }
7130
7131    @Override
7132    public boolean isInstantApp(String packageName, int userId) {
7133        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7134                true /* requireFullPermission */, false /* checkShell */,
7135                "isInstantApp");
7136        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7137            return false;
7138        }
7139
7140        if (!isCallerSameApp(packageName)) {
7141            return false;
7142        }
7143        synchronized (mPackages) {
7144            PackageParser.Package pkg = mPackages.get(packageName);
7145            if (pkg != null) {
7146                return pkg.applicationInfo.isInstantApp();
7147            }
7148        }
7149        return false;
7150    }
7151
7152    @Override
7153    public byte[] getInstantAppCookie(String packageName, int userId) {
7154        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7155            return null;
7156        }
7157
7158        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7159                true /* requireFullPermission */, false /* checkShell */,
7160                "getInstantAppCookie");
7161        if (!isCallerSameApp(packageName)) {
7162            return null;
7163        }
7164        synchronized (mPackages) {
7165            return mInstantAppRegistry.getInstantAppCookieLPw(
7166                    packageName, userId);
7167        }
7168    }
7169
7170    @Override
7171    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7172        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7173            return true;
7174        }
7175
7176        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7177                true /* requireFullPermission */, true /* checkShell */,
7178                "setInstantAppCookie");
7179        if (!isCallerSameApp(packageName)) {
7180            return false;
7181        }
7182        synchronized (mPackages) {
7183            return mInstantAppRegistry.setInstantAppCookieLPw(
7184                    packageName, cookie, userId);
7185        }
7186    }
7187
7188    @Override
7189    public Bitmap getInstantAppIcon(String packageName, int userId) {
7190        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7191            return null;
7192        }
7193
7194        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7195                "getInstantAppIcon");
7196
7197        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7198                true /* requireFullPermission */, false /* checkShell */,
7199                "getInstantAppIcon");
7200
7201        synchronized (mPackages) {
7202            return mInstantAppRegistry.getInstantAppIconLPw(
7203                    packageName, userId);
7204        }
7205    }
7206
7207    private boolean isCallerSameApp(String packageName) {
7208        PackageParser.Package pkg = mPackages.get(packageName);
7209        return pkg != null
7210                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7211    }
7212
7213    @Override
7214    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7215        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7216    }
7217
7218    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7219        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7220
7221        // reader
7222        synchronized (mPackages) {
7223            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7224            final int userId = UserHandle.getCallingUserId();
7225            while (i.hasNext()) {
7226                final PackageParser.Package p = i.next();
7227                if (p.applicationInfo == null) continue;
7228
7229                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7230                        && !p.applicationInfo.isDirectBootAware();
7231                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7232                        && p.applicationInfo.isDirectBootAware();
7233
7234                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7235                        && (!mSafeMode || isSystemApp(p))
7236                        && (matchesUnaware || matchesAware)) {
7237                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7238                    if (ps != null) {
7239                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7240                                ps.readUserState(userId), userId);
7241                        if (ai != null) {
7242                            finalList.add(ai);
7243                        }
7244                    }
7245                }
7246            }
7247        }
7248
7249        return finalList;
7250    }
7251
7252    @Override
7253    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7254        if (!sUserManager.exists(userId)) return null;
7255        flags = updateFlagsForComponent(flags, userId, name);
7256        // reader
7257        synchronized (mPackages) {
7258            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7259            PackageSetting ps = provider != null
7260                    ? mSettings.mPackages.get(provider.owner.packageName)
7261                    : null;
7262            return ps != null
7263                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7264                    ? PackageParser.generateProviderInfo(provider, flags,
7265                            ps.readUserState(userId), userId)
7266                    : null;
7267        }
7268    }
7269
7270    /**
7271     * @deprecated
7272     */
7273    @Deprecated
7274    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7275        // reader
7276        synchronized (mPackages) {
7277            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7278                    .entrySet().iterator();
7279            final int userId = UserHandle.getCallingUserId();
7280            while (i.hasNext()) {
7281                Map.Entry<String, PackageParser.Provider> entry = i.next();
7282                PackageParser.Provider p = entry.getValue();
7283                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7284
7285                if (ps != null && p.syncable
7286                        && (!mSafeMode || (p.info.applicationInfo.flags
7287                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7288                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7289                            ps.readUserState(userId), userId);
7290                    if (info != null) {
7291                        outNames.add(entry.getKey());
7292                        outInfo.add(info);
7293                    }
7294                }
7295            }
7296        }
7297    }
7298
7299    @Override
7300    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7301            int uid, int flags) {
7302        final int userId = processName != null ? UserHandle.getUserId(uid)
7303                : UserHandle.getCallingUserId();
7304        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7305        flags = updateFlagsForComponent(flags, userId, processName);
7306
7307        ArrayList<ProviderInfo> finalList = null;
7308        // reader
7309        synchronized (mPackages) {
7310            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7311            while (i.hasNext()) {
7312                final PackageParser.Provider p = i.next();
7313                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7314                if (ps != null && p.info.authority != null
7315                        && (processName == null
7316                                || (p.info.processName.equals(processName)
7317                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7318                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7319                    if (finalList == null) {
7320                        finalList = new ArrayList<ProviderInfo>(3);
7321                    }
7322                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7323                            ps.readUserState(userId), userId);
7324                    if (info != null) {
7325                        finalList.add(info);
7326                    }
7327                }
7328            }
7329        }
7330
7331        if (finalList != null) {
7332            Collections.sort(finalList, mProviderInitOrderSorter);
7333            return new ParceledListSlice<ProviderInfo>(finalList);
7334        }
7335
7336        return ParceledListSlice.emptyList();
7337    }
7338
7339    @Override
7340    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7341        // reader
7342        synchronized (mPackages) {
7343            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7344            return PackageParser.generateInstrumentationInfo(i, flags);
7345        }
7346    }
7347
7348    @Override
7349    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7350            String targetPackage, int flags) {
7351        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7352    }
7353
7354    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7355            int flags) {
7356        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7357
7358        // reader
7359        synchronized (mPackages) {
7360            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7361            while (i.hasNext()) {
7362                final PackageParser.Instrumentation p = i.next();
7363                if (targetPackage == null
7364                        || targetPackage.equals(p.info.targetPackage)) {
7365                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7366                            flags);
7367                    if (ii != null) {
7368                        finalList.add(ii);
7369                    }
7370                }
7371            }
7372        }
7373
7374        return finalList;
7375    }
7376
7377    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7378        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7379        if (overlays == null) {
7380            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7381            return;
7382        }
7383        for (PackageParser.Package opkg : overlays.values()) {
7384            // Not much to do if idmap fails: we already logged the error
7385            // and we certainly don't want to abort installation of pkg simply
7386            // because an overlay didn't fit properly. For these reasons,
7387            // ignore the return value of createIdmapForPackagePairLI.
7388            createIdmapForPackagePairLI(pkg, opkg);
7389        }
7390    }
7391
7392    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7393            PackageParser.Package opkg) {
7394        if (!opkg.mTrustedOverlay) {
7395            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7396                    opkg.baseCodePath + ": overlay not trusted");
7397            return false;
7398        }
7399        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7400        if (overlaySet == null) {
7401            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7402                    opkg.baseCodePath + " but target package has no known overlays");
7403            return false;
7404        }
7405        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7406        // TODO: generate idmap for split APKs
7407        try {
7408            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7409        } catch (InstallerException e) {
7410            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7411                    + opkg.baseCodePath);
7412            return false;
7413        }
7414        PackageParser.Package[] overlayArray =
7415            overlaySet.values().toArray(new PackageParser.Package[0]);
7416        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7417            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7418                return p1.mOverlayPriority - p2.mOverlayPriority;
7419            }
7420        };
7421        Arrays.sort(overlayArray, cmp);
7422
7423        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7424        int i = 0;
7425        for (PackageParser.Package p : overlayArray) {
7426            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7427        }
7428        return true;
7429    }
7430
7431    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7432        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7433        try {
7434            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7435        } finally {
7436            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7437        }
7438    }
7439
7440    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7441        final File[] files = dir.listFiles();
7442        if (ArrayUtils.isEmpty(files)) {
7443            Log.d(TAG, "No files in app dir " + dir);
7444            return;
7445        }
7446
7447        if (DEBUG_PACKAGE_SCANNING) {
7448            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7449                    + " flags=0x" + Integer.toHexString(parseFlags));
7450        }
7451        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7452                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7453
7454        // Submit files for parsing in parallel
7455        int fileCount = 0;
7456        for (File file : files) {
7457            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7458                    && !PackageInstallerService.isStageName(file.getName());
7459            if (!isPackage) {
7460                // Ignore entries which are not packages
7461                continue;
7462            }
7463            parallelPackageParser.submit(file, parseFlags);
7464            fileCount++;
7465        }
7466
7467        // Process results one by one
7468        for (; fileCount > 0; fileCount--) {
7469            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7470            Throwable throwable = parseResult.throwable;
7471            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7472
7473            if (throwable == null) {
7474                // Static shared libraries have synthetic package names
7475                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7476                    renameStaticSharedLibraryPackage(parseResult.pkg);
7477                }
7478                try {
7479                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7480                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7481                                currentTime, null);
7482                    }
7483                } catch (PackageManagerException e) {
7484                    errorCode = e.error;
7485                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7486                }
7487            } else if (throwable instanceof PackageParser.PackageParserException) {
7488                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7489                        throwable;
7490                errorCode = e.error;
7491                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7492            } else {
7493                throw new IllegalStateException("Unexpected exception occurred while parsing "
7494                        + parseResult.scanFile, throwable);
7495            }
7496
7497            // Delete invalid userdata apps
7498            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7499                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7500                logCriticalInfo(Log.WARN,
7501                        "Deleting invalid package at " + parseResult.scanFile);
7502                removeCodePathLI(parseResult.scanFile);
7503            }
7504        }
7505        parallelPackageParser.close();
7506    }
7507
7508    private static File getSettingsProblemFile() {
7509        File dataDir = Environment.getDataDirectory();
7510        File systemDir = new File(dataDir, "system");
7511        File fname = new File(systemDir, "uiderrors.txt");
7512        return fname;
7513    }
7514
7515    static void reportSettingsProblem(int priority, String msg) {
7516        logCriticalInfo(priority, msg);
7517    }
7518
7519    static void logCriticalInfo(int priority, String msg) {
7520        Slog.println(priority, TAG, msg);
7521        EventLogTags.writePmCriticalInfo(msg);
7522        try {
7523            File fname = getSettingsProblemFile();
7524            FileOutputStream out = new FileOutputStream(fname, true);
7525            PrintWriter pw = new FastPrintWriter(out);
7526            SimpleDateFormat formatter = new SimpleDateFormat();
7527            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7528            pw.println(dateString + ": " + msg);
7529            pw.close();
7530            FileUtils.setPermissions(
7531                    fname.toString(),
7532                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7533                    -1, -1);
7534        } catch (java.io.IOException e) {
7535        }
7536    }
7537
7538    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7539        if (srcFile.isDirectory()) {
7540            final File baseFile = new File(pkg.baseCodePath);
7541            long maxModifiedTime = baseFile.lastModified();
7542            if (pkg.splitCodePaths != null) {
7543                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7544                    final File splitFile = new File(pkg.splitCodePaths[i]);
7545                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7546                }
7547            }
7548            return maxModifiedTime;
7549        }
7550        return srcFile.lastModified();
7551    }
7552
7553    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7554            final int policyFlags) throws PackageManagerException {
7555        // When upgrading from pre-N MR1, verify the package time stamp using the package
7556        // directory and not the APK file.
7557        final long lastModifiedTime = mIsPreNMR1Upgrade
7558                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7559        if (ps != null
7560                && ps.codePath.equals(srcFile)
7561                && ps.timeStamp == lastModifiedTime
7562                && !isCompatSignatureUpdateNeeded(pkg)
7563                && !isRecoverSignatureUpdateNeeded(pkg)) {
7564            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7565            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7566            ArraySet<PublicKey> signingKs;
7567            synchronized (mPackages) {
7568                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7569            }
7570            if (ps.signatures.mSignatures != null
7571                    && ps.signatures.mSignatures.length != 0
7572                    && signingKs != null) {
7573                // Optimization: reuse the existing cached certificates
7574                // if the package appears to be unchanged.
7575                pkg.mSignatures = ps.signatures.mSignatures;
7576                pkg.mSigningKeys = signingKs;
7577                return;
7578            }
7579
7580            Slog.w(TAG, "PackageSetting for " + ps.name
7581                    + " is missing signatures.  Collecting certs again to recover them.");
7582        } else {
7583            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7584        }
7585
7586        try {
7587            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7588            PackageParser.collectCertificates(pkg, policyFlags);
7589        } catch (PackageParserException e) {
7590            throw PackageManagerException.from(e);
7591        } finally {
7592            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7593        }
7594    }
7595
7596    /**
7597     *  Traces a package scan.
7598     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7599     */
7600    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7601            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7602        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7603        try {
7604            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7605        } finally {
7606            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7607        }
7608    }
7609
7610    /**
7611     *  Scans a package and returns the newly parsed package.
7612     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7613     */
7614    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7615            long currentTime, UserHandle user) throws PackageManagerException {
7616        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7617        PackageParser pp = new PackageParser();
7618        pp.setSeparateProcesses(mSeparateProcesses);
7619        pp.setOnlyCoreApps(mOnlyCore);
7620        pp.setDisplayMetrics(mMetrics);
7621
7622        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7623            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7624        }
7625
7626        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7627        final PackageParser.Package pkg;
7628        try {
7629            pkg = pp.parsePackage(scanFile, parseFlags);
7630        } catch (PackageParserException e) {
7631            throw PackageManagerException.from(e);
7632        } finally {
7633            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7634        }
7635
7636        // Static shared libraries have synthetic package names
7637        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7638            renameStaticSharedLibraryPackage(pkg);
7639        }
7640
7641        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7642    }
7643
7644    /**
7645     *  Scans a package and returns the newly parsed package.
7646     *  @throws PackageManagerException on a parse error.
7647     */
7648    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7649            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7650            throws PackageManagerException {
7651        // If the package has children and this is the first dive in the function
7652        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7653        // packages (parent and children) would be successfully scanned before the
7654        // actual scan since scanning mutates internal state and we want to atomically
7655        // install the package and its children.
7656        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7657            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7658                scanFlags |= SCAN_CHECK_ONLY;
7659            }
7660        } else {
7661            scanFlags &= ~SCAN_CHECK_ONLY;
7662        }
7663
7664        // Scan the parent
7665        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7666                scanFlags, currentTime, user);
7667
7668        // Scan the children
7669        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7670        for (int i = 0; i < childCount; i++) {
7671            PackageParser.Package childPackage = pkg.childPackages.get(i);
7672            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7673                    currentTime, user);
7674        }
7675
7676
7677        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7678            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7679        }
7680
7681        return scannedPkg;
7682    }
7683
7684    /**
7685     *  Scans a package and returns the newly parsed package.
7686     *  @throws PackageManagerException on a parse error.
7687     */
7688    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7689            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7690            throws PackageManagerException {
7691        PackageSetting ps = null;
7692        PackageSetting updatedPkg;
7693        // reader
7694        synchronized (mPackages) {
7695            // Look to see if we already know about this package.
7696            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7697            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7698                // This package has been renamed to its original name.  Let's
7699                // use that.
7700                ps = mSettings.getPackageLPr(oldName);
7701            }
7702            // If there was no original package, see one for the real package name.
7703            if (ps == null) {
7704                ps = mSettings.getPackageLPr(pkg.packageName);
7705            }
7706            // Check to see if this package could be hiding/updating a system
7707            // package.  Must look for it either under the original or real
7708            // package name depending on our state.
7709            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7710            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7711
7712            // If this is a package we don't know about on the system partition, we
7713            // may need to remove disabled child packages on the system partition
7714            // or may need to not add child packages if the parent apk is updated
7715            // on the data partition and no longer defines this child package.
7716            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7717                // If this is a parent package for an updated system app and this system
7718                // app got an OTA update which no longer defines some of the child packages
7719                // we have to prune them from the disabled system packages.
7720                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7721                if (disabledPs != null) {
7722                    final int scannedChildCount = (pkg.childPackages != null)
7723                            ? pkg.childPackages.size() : 0;
7724                    final int disabledChildCount = disabledPs.childPackageNames != null
7725                            ? disabledPs.childPackageNames.size() : 0;
7726                    for (int i = 0; i < disabledChildCount; i++) {
7727                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7728                        boolean disabledPackageAvailable = false;
7729                        for (int j = 0; j < scannedChildCount; j++) {
7730                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7731                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7732                                disabledPackageAvailable = true;
7733                                break;
7734                            }
7735                         }
7736                         if (!disabledPackageAvailable) {
7737                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7738                         }
7739                    }
7740                }
7741            }
7742        }
7743
7744        boolean updatedPkgBetter = false;
7745        // First check if this is a system package that may involve an update
7746        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7747            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7748            // it needs to drop FLAG_PRIVILEGED.
7749            if (locationIsPrivileged(scanFile)) {
7750                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7751            } else {
7752                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7753            }
7754
7755            if (ps != null && !ps.codePath.equals(scanFile)) {
7756                // The path has changed from what was last scanned...  check the
7757                // version of the new path against what we have stored to determine
7758                // what to do.
7759                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7760                if (pkg.mVersionCode <= ps.versionCode) {
7761                    // The system package has been updated and the code path does not match
7762                    // Ignore entry. Skip it.
7763                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7764                            + " ignored: updated version " + ps.versionCode
7765                            + " better than this " + pkg.mVersionCode);
7766                    if (!updatedPkg.codePath.equals(scanFile)) {
7767                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7768                                + ps.name + " changing from " + updatedPkg.codePathString
7769                                + " to " + scanFile);
7770                        updatedPkg.codePath = scanFile;
7771                        updatedPkg.codePathString = scanFile.toString();
7772                        updatedPkg.resourcePath = scanFile;
7773                        updatedPkg.resourcePathString = scanFile.toString();
7774                    }
7775                    updatedPkg.pkg = pkg;
7776                    updatedPkg.versionCode = pkg.mVersionCode;
7777
7778                    // Update the disabled system child packages to point to the package too.
7779                    final int childCount = updatedPkg.childPackageNames != null
7780                            ? updatedPkg.childPackageNames.size() : 0;
7781                    for (int i = 0; i < childCount; i++) {
7782                        String childPackageName = updatedPkg.childPackageNames.get(i);
7783                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7784                                childPackageName);
7785                        if (updatedChildPkg != null) {
7786                            updatedChildPkg.pkg = pkg;
7787                            updatedChildPkg.versionCode = pkg.mVersionCode;
7788                        }
7789                    }
7790
7791                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7792                            + scanFile + " ignored: updated version " + ps.versionCode
7793                            + " better than this " + pkg.mVersionCode);
7794                } else {
7795                    // The current app on the system partition is better than
7796                    // what we have updated to on the data partition; switch
7797                    // back to the system partition version.
7798                    // At this point, its safely assumed that package installation for
7799                    // apps in system partition will go through. If not there won't be a working
7800                    // version of the app
7801                    // writer
7802                    synchronized (mPackages) {
7803                        // Just remove the loaded entries from package lists.
7804                        mPackages.remove(ps.name);
7805                    }
7806
7807                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7808                            + " reverting from " + ps.codePathString
7809                            + ": new version " + pkg.mVersionCode
7810                            + " better than installed " + ps.versionCode);
7811
7812                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7813                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7814                    synchronized (mInstallLock) {
7815                        args.cleanUpResourcesLI();
7816                    }
7817                    synchronized (mPackages) {
7818                        mSettings.enableSystemPackageLPw(ps.name);
7819                    }
7820                    updatedPkgBetter = true;
7821                }
7822            }
7823        }
7824
7825        if (updatedPkg != null) {
7826            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7827            // initially
7828            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7829
7830            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7831            // flag set initially
7832            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7833                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7834            }
7835        }
7836
7837        // Verify certificates against what was last scanned
7838        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7839
7840        /*
7841         * A new system app appeared, but we already had a non-system one of the
7842         * same name installed earlier.
7843         */
7844        boolean shouldHideSystemApp = false;
7845        if (updatedPkg == null && ps != null
7846                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7847            /*
7848             * Check to make sure the signatures match first. If they don't,
7849             * wipe the installed application and its data.
7850             */
7851            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7852                    != PackageManager.SIGNATURE_MATCH) {
7853                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7854                        + " signatures don't match existing userdata copy; removing");
7855                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7856                        "scanPackageInternalLI")) {
7857                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7858                }
7859                ps = null;
7860            } else {
7861                /*
7862                 * If the newly-added system app is an older version than the
7863                 * already installed version, hide it. It will be scanned later
7864                 * and re-added like an update.
7865                 */
7866                if (pkg.mVersionCode <= ps.versionCode) {
7867                    shouldHideSystemApp = true;
7868                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7869                            + " but new version " + pkg.mVersionCode + " better than installed "
7870                            + ps.versionCode + "; hiding system");
7871                } else {
7872                    /*
7873                     * The newly found system app is a newer version that the
7874                     * one previously installed. Simply remove the
7875                     * already-installed application and replace it with our own
7876                     * while keeping the application data.
7877                     */
7878                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7879                            + " reverting from " + ps.codePathString + ": new version "
7880                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7881                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7882                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7883                    synchronized (mInstallLock) {
7884                        args.cleanUpResourcesLI();
7885                    }
7886                }
7887            }
7888        }
7889
7890        // The apk is forward locked (not public) if its code and resources
7891        // are kept in different files. (except for app in either system or
7892        // vendor path).
7893        // TODO grab this value from PackageSettings
7894        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7895            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7896                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7897            }
7898        }
7899
7900        // TODO: extend to support forward-locked splits
7901        String resourcePath = null;
7902        String baseResourcePath = null;
7903        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7904            if (ps != null && ps.resourcePathString != null) {
7905                resourcePath = ps.resourcePathString;
7906                baseResourcePath = ps.resourcePathString;
7907            } else {
7908                // Should not happen at all. Just log an error.
7909                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7910            }
7911        } else {
7912            resourcePath = pkg.codePath;
7913            baseResourcePath = pkg.baseCodePath;
7914        }
7915
7916        // Set application objects path explicitly.
7917        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7918        pkg.setApplicationInfoCodePath(pkg.codePath);
7919        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7920        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7921        pkg.setApplicationInfoResourcePath(resourcePath);
7922        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7923        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7924
7925        // Note that we invoke the following method only if we are about to unpack an application
7926        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7927                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7928
7929        /*
7930         * If the system app should be overridden by a previously installed
7931         * data, hide the system app now and let the /data/app scan pick it up
7932         * again.
7933         */
7934        if (shouldHideSystemApp) {
7935            synchronized (mPackages) {
7936                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7937            }
7938        }
7939
7940        return scannedPkg;
7941    }
7942
7943    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7944        // Derive the new package synthetic package name
7945        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7946                + pkg.staticSharedLibVersion);
7947    }
7948
7949    private static String fixProcessName(String defProcessName,
7950            String processName) {
7951        if (processName == null) {
7952            return defProcessName;
7953        }
7954        return processName;
7955    }
7956
7957    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7958            throws PackageManagerException {
7959        if (pkgSetting.signatures.mSignatures != null) {
7960            // Already existing package. Make sure signatures match
7961            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7962                    == PackageManager.SIGNATURE_MATCH;
7963            if (!match) {
7964                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7965                        == PackageManager.SIGNATURE_MATCH;
7966            }
7967            if (!match) {
7968                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7969                        == PackageManager.SIGNATURE_MATCH;
7970            }
7971            if (!match) {
7972                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7973                        + pkg.packageName + " signatures do not match the "
7974                        + "previously installed version; ignoring!");
7975            }
7976        }
7977
7978        // Check for shared user signatures
7979        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7980            // Already existing package. Make sure signatures match
7981            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7982                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7983            if (!match) {
7984                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7985                        == PackageManager.SIGNATURE_MATCH;
7986            }
7987            if (!match) {
7988                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7989                        == PackageManager.SIGNATURE_MATCH;
7990            }
7991            if (!match) {
7992                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7993                        "Package " + pkg.packageName
7994                        + " has no signatures that match those in shared user "
7995                        + pkgSetting.sharedUser.name + "; ignoring!");
7996            }
7997        }
7998    }
7999
8000    /**
8001     * Enforces that only the system UID or root's UID can call a method exposed
8002     * via Binder.
8003     *
8004     * @param message used as message if SecurityException is thrown
8005     * @throws SecurityException if the caller is not system or root
8006     */
8007    private static final void enforceSystemOrRoot(String message) {
8008        final int uid = Binder.getCallingUid();
8009        if (uid != Process.SYSTEM_UID && uid != 0) {
8010            throw new SecurityException(message);
8011        }
8012    }
8013
8014    @Override
8015    public void performFstrimIfNeeded() {
8016        enforceSystemOrRoot("Only the system can request fstrim");
8017
8018        // Before everything else, see whether we need to fstrim.
8019        try {
8020            IStorageManager sm = PackageHelper.getStorageManager();
8021            if (sm != null) {
8022                boolean doTrim = false;
8023                final long interval = android.provider.Settings.Global.getLong(
8024                        mContext.getContentResolver(),
8025                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8026                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8027                if (interval > 0) {
8028                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8029                    if (timeSinceLast > interval) {
8030                        doTrim = true;
8031                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8032                                + "; running immediately");
8033                    }
8034                }
8035                if (doTrim) {
8036                    final boolean dexOptDialogShown;
8037                    synchronized (mPackages) {
8038                        dexOptDialogShown = mDexOptDialogShown;
8039                    }
8040                    if (!isFirstBoot() && dexOptDialogShown) {
8041                        try {
8042                            ActivityManager.getService().showBootMessage(
8043                                    mContext.getResources().getString(
8044                                            R.string.android_upgrading_fstrim), true);
8045                        } catch (RemoteException e) {
8046                        }
8047                    }
8048                    sm.runMaintenance();
8049                }
8050            } else {
8051                Slog.e(TAG, "storageManager service unavailable!");
8052            }
8053        } catch (RemoteException e) {
8054            // Can't happen; StorageManagerService is local
8055        }
8056    }
8057
8058    @Override
8059    public void updatePackagesIfNeeded() {
8060        enforceSystemOrRoot("Only the system can request package update");
8061
8062        // We need to re-extract after an OTA.
8063        boolean causeUpgrade = isUpgrade();
8064
8065        // First boot or factory reset.
8066        // Note: we also handle devices that are upgrading to N right now as if it is their
8067        //       first boot, as they do not have profile data.
8068        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8069
8070        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8071        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8072
8073        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8074            return;
8075        }
8076
8077        List<PackageParser.Package> pkgs;
8078        synchronized (mPackages) {
8079            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8080        }
8081
8082        final long startTime = System.nanoTime();
8083        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8084                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8085
8086        final int elapsedTimeSeconds =
8087                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8088
8089        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8090        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8091        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8092        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8093        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8094    }
8095
8096    /**
8097     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8098     * containing statistics about the invocation. The array consists of three elements,
8099     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8100     * and {@code numberOfPackagesFailed}.
8101     */
8102    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8103            String compilerFilter) {
8104
8105        int numberOfPackagesVisited = 0;
8106        int numberOfPackagesOptimized = 0;
8107        int numberOfPackagesSkipped = 0;
8108        int numberOfPackagesFailed = 0;
8109        final int numberOfPackagesToDexopt = pkgs.size();
8110
8111        for (PackageParser.Package pkg : pkgs) {
8112            numberOfPackagesVisited++;
8113
8114            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8115                if (DEBUG_DEXOPT) {
8116                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8117                }
8118                numberOfPackagesSkipped++;
8119                continue;
8120            }
8121
8122            if (DEBUG_DEXOPT) {
8123                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8124                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8125            }
8126
8127            if (showDialog) {
8128                try {
8129                    ActivityManager.getService().showBootMessage(
8130                            mContext.getResources().getString(R.string.android_upgrading_apk,
8131                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8132                } catch (RemoteException e) {
8133                }
8134                synchronized (mPackages) {
8135                    mDexOptDialogShown = true;
8136                }
8137            }
8138
8139            // If the OTA updates a system app which was previously preopted to a non-preopted state
8140            // the app might end up being verified at runtime. That's because by default the apps
8141            // are verify-profile but for preopted apps there's no profile.
8142            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8143            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8144            // filter (by default interpret-only).
8145            // Note that at this stage unused apps are already filtered.
8146            if (isSystemApp(pkg) &&
8147                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8148                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8149                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8150            }
8151
8152            // checkProfiles is false to avoid merging profiles during boot which
8153            // might interfere with background compilation (b/28612421).
8154            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8155            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8156            // trade-off worth doing to save boot time work.
8157            int dexOptStatus = performDexOptTraced(pkg.packageName,
8158                    false /* checkProfiles */,
8159                    compilerFilter,
8160                    false /* force */);
8161            switch (dexOptStatus) {
8162                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8163                    numberOfPackagesOptimized++;
8164                    break;
8165                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8166                    numberOfPackagesSkipped++;
8167                    break;
8168                case PackageDexOptimizer.DEX_OPT_FAILED:
8169                    numberOfPackagesFailed++;
8170                    break;
8171                default:
8172                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8173                    break;
8174            }
8175        }
8176
8177        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8178                numberOfPackagesFailed };
8179    }
8180
8181    @Override
8182    public void notifyPackageUse(String packageName, int reason) {
8183        synchronized (mPackages) {
8184            PackageParser.Package p = mPackages.get(packageName);
8185            if (p == null) {
8186                return;
8187            }
8188            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8189        }
8190    }
8191
8192    @Override
8193    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8194        int userId = UserHandle.getCallingUserId();
8195        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8196        if (ai == null) {
8197            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8198                + loadingPackageName + ", user=" + userId);
8199            return;
8200        }
8201        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8202    }
8203
8204    // TODO: this is not used nor needed. Delete it.
8205    @Override
8206    public boolean performDexOptIfNeeded(String packageName) {
8207        int dexOptStatus = performDexOptTraced(packageName,
8208                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8209        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8210    }
8211
8212    @Override
8213    public boolean performDexOpt(String packageName,
8214            boolean checkProfiles, int compileReason, boolean force) {
8215        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8216                getCompilerFilterForReason(compileReason), force);
8217        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8218    }
8219
8220    @Override
8221    public boolean performDexOptMode(String packageName,
8222            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8223        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8224                targetCompilerFilter, force);
8225        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8226    }
8227
8228    private int performDexOptTraced(String packageName,
8229                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8230        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8231        try {
8232            return performDexOptInternal(packageName, checkProfiles,
8233                    targetCompilerFilter, force);
8234        } finally {
8235            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8236        }
8237    }
8238
8239    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8240    // if the package can now be considered up to date for the given filter.
8241    private int performDexOptInternal(String packageName,
8242                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8243        PackageParser.Package p;
8244        synchronized (mPackages) {
8245            p = mPackages.get(packageName);
8246            if (p == null) {
8247                // Package could not be found. Report failure.
8248                return PackageDexOptimizer.DEX_OPT_FAILED;
8249            }
8250            mPackageUsage.maybeWriteAsync(mPackages);
8251            mCompilerStats.maybeWriteAsync();
8252        }
8253        long callingId = Binder.clearCallingIdentity();
8254        try {
8255            synchronized (mInstallLock) {
8256                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8257                        targetCompilerFilter, force);
8258            }
8259        } finally {
8260            Binder.restoreCallingIdentity(callingId);
8261        }
8262    }
8263
8264    public ArraySet<String> getOptimizablePackages() {
8265        ArraySet<String> pkgs = new ArraySet<String>();
8266        synchronized (mPackages) {
8267            for (PackageParser.Package p : mPackages.values()) {
8268                if (PackageDexOptimizer.canOptimizePackage(p)) {
8269                    pkgs.add(p.packageName);
8270                }
8271            }
8272        }
8273        return pkgs;
8274    }
8275
8276    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8277            boolean checkProfiles, String targetCompilerFilter,
8278            boolean force) {
8279        // Select the dex optimizer based on the force parameter.
8280        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8281        //       allocate an object here.
8282        PackageDexOptimizer pdo = force
8283                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8284                : mPackageDexOptimizer;
8285
8286        // Optimize all dependencies first. Note: we ignore the return value and march on
8287        // on errors.
8288        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8289        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8290        if (!deps.isEmpty()) {
8291            for (PackageParser.Package depPackage : deps) {
8292                // TODO: Analyze and investigate if we (should) profile libraries.
8293                // Currently this will do a full compilation of the library by default.
8294                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8295                        false /* checkProfiles */,
8296                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8297                        getOrCreateCompilerPackageStats(depPackage));
8298            }
8299        }
8300        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8301                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8302    }
8303
8304    // Performs dexopt on the used secondary dex files belonging to the given package.
8305    // Returns true if all dex files were process successfully (which could mean either dexopt or
8306    // skip). Returns false if any of the files caused errors.
8307    @Override
8308    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8309            boolean force) {
8310        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8311    }
8312
8313    /**
8314     * Reconcile the information we have about the secondary dex files belonging to
8315     * {@code packagName} and the actual dex files. For all dex files that were
8316     * deleted, update the internal records and delete the generated oat files.
8317     */
8318    @Override
8319    public void reconcileSecondaryDexFiles(String packageName) {
8320        mDexManager.reconcileSecondaryDexFiles(packageName);
8321    }
8322
8323    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8324    // a reference there.
8325    /*package*/ DexManager getDexManager() {
8326        return mDexManager;
8327    }
8328
8329    /**
8330     * Execute the background dexopt job immediately.
8331     */
8332    @Override
8333    public boolean runBackgroundDexoptJob() {
8334        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8335    }
8336
8337    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8338        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8339                || p.usesStaticLibraries != null) {
8340            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8341            Set<String> collectedNames = new HashSet<>();
8342            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8343
8344            retValue.remove(p);
8345
8346            return retValue;
8347        } else {
8348            return Collections.emptyList();
8349        }
8350    }
8351
8352    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8353            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8354        if (!collectedNames.contains(p.packageName)) {
8355            collectedNames.add(p.packageName);
8356            collected.add(p);
8357
8358            if (p.usesLibraries != null) {
8359                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8360                        null, collected, collectedNames);
8361            }
8362            if (p.usesOptionalLibraries != null) {
8363                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8364                        null, collected, collectedNames);
8365            }
8366            if (p.usesStaticLibraries != null) {
8367                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8368                        p.usesStaticLibrariesVersions, collected, collectedNames);
8369            }
8370        }
8371    }
8372
8373    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8374            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8375        final int libNameCount = libs.size();
8376        for (int i = 0; i < libNameCount; i++) {
8377            String libName = libs.get(i);
8378            int version = (versions != null && versions.length == libNameCount)
8379                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8380            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8381            if (libPkg != null) {
8382                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8383            }
8384        }
8385    }
8386
8387    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8388        synchronized (mPackages) {
8389            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8390            if (libEntry != null) {
8391                return mPackages.get(libEntry.apk);
8392            }
8393            return null;
8394        }
8395    }
8396
8397    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8398        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8399        if (versionedLib == null) {
8400            return null;
8401        }
8402        return versionedLib.get(version);
8403    }
8404
8405    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8406        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8407                pkg.staticSharedLibName);
8408        if (versionedLib == null) {
8409            return null;
8410        }
8411        int previousLibVersion = -1;
8412        final int versionCount = versionedLib.size();
8413        for (int i = 0; i < versionCount; i++) {
8414            final int libVersion = versionedLib.keyAt(i);
8415            if (libVersion < pkg.staticSharedLibVersion) {
8416                previousLibVersion = Math.max(previousLibVersion, libVersion);
8417            }
8418        }
8419        if (previousLibVersion >= 0) {
8420            return versionedLib.get(previousLibVersion);
8421        }
8422        return null;
8423    }
8424
8425    public void shutdown() {
8426        mPackageUsage.writeNow(mPackages);
8427        mCompilerStats.writeNow();
8428    }
8429
8430    @Override
8431    public void dumpProfiles(String packageName) {
8432        PackageParser.Package pkg;
8433        synchronized (mPackages) {
8434            pkg = mPackages.get(packageName);
8435            if (pkg == null) {
8436                throw new IllegalArgumentException("Unknown package: " + packageName);
8437            }
8438        }
8439        /* Only the shell, root, or the app user should be able to dump profiles. */
8440        int callingUid = Binder.getCallingUid();
8441        if (callingUid != Process.SHELL_UID &&
8442            callingUid != Process.ROOT_UID &&
8443            callingUid != pkg.applicationInfo.uid) {
8444            throw new SecurityException("dumpProfiles");
8445        }
8446
8447        synchronized (mInstallLock) {
8448            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8449            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8450            try {
8451                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8452                String codePaths = TextUtils.join(";", allCodePaths);
8453                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8454            } catch (InstallerException e) {
8455                Slog.w(TAG, "Failed to dump profiles", e);
8456            }
8457            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8458        }
8459    }
8460
8461    @Override
8462    public void forceDexOpt(String packageName) {
8463        enforceSystemOrRoot("forceDexOpt");
8464
8465        PackageParser.Package pkg;
8466        synchronized (mPackages) {
8467            pkg = mPackages.get(packageName);
8468            if (pkg == null) {
8469                throw new IllegalArgumentException("Unknown package: " + packageName);
8470            }
8471        }
8472
8473        synchronized (mInstallLock) {
8474            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8475
8476            // Whoever is calling forceDexOpt wants a fully compiled package.
8477            // Don't use profiles since that may cause compilation to be skipped.
8478            final int res = performDexOptInternalWithDependenciesLI(pkg,
8479                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8480                    true /* force */);
8481
8482            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8483            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8484                throw new IllegalStateException("Failed to dexopt: " + res);
8485            }
8486        }
8487    }
8488
8489    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8490        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8491            Slog.w(TAG, "Unable to update from " + oldPkg.name
8492                    + " to " + newPkg.packageName
8493                    + ": old package not in system partition");
8494            return false;
8495        } else if (mPackages.get(oldPkg.name) != null) {
8496            Slog.w(TAG, "Unable to update from " + oldPkg.name
8497                    + " to " + newPkg.packageName
8498                    + ": old package still exists");
8499            return false;
8500        }
8501        return true;
8502    }
8503
8504    void removeCodePathLI(File codePath) {
8505        if (codePath.isDirectory()) {
8506            try {
8507                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8508            } catch (InstallerException e) {
8509                Slog.w(TAG, "Failed to remove code path", e);
8510            }
8511        } else {
8512            codePath.delete();
8513        }
8514    }
8515
8516    private int[] resolveUserIds(int userId) {
8517        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8518    }
8519
8520    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8521        if (pkg == null) {
8522            Slog.wtf(TAG, "Package was null!", new Throwable());
8523            return;
8524        }
8525        clearAppDataLeafLIF(pkg, userId, flags);
8526        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8527        for (int i = 0; i < childCount; i++) {
8528            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8529        }
8530    }
8531
8532    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8533        final PackageSetting ps;
8534        synchronized (mPackages) {
8535            ps = mSettings.mPackages.get(pkg.packageName);
8536        }
8537        for (int realUserId : resolveUserIds(userId)) {
8538            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8539            try {
8540                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8541                        ceDataInode);
8542            } catch (InstallerException e) {
8543                Slog.w(TAG, String.valueOf(e));
8544            }
8545        }
8546    }
8547
8548    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8549        if (pkg == null) {
8550            Slog.wtf(TAG, "Package was null!", new Throwable());
8551            return;
8552        }
8553        destroyAppDataLeafLIF(pkg, userId, flags);
8554        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8555        for (int i = 0; i < childCount; i++) {
8556            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8557        }
8558    }
8559
8560    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8561        final PackageSetting ps;
8562        synchronized (mPackages) {
8563            ps = mSettings.mPackages.get(pkg.packageName);
8564        }
8565        for (int realUserId : resolveUserIds(userId)) {
8566            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8567            try {
8568                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8569                        ceDataInode);
8570            } catch (InstallerException e) {
8571                Slog.w(TAG, String.valueOf(e));
8572            }
8573        }
8574    }
8575
8576    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8577        if (pkg == null) {
8578            Slog.wtf(TAG, "Package was null!", new Throwable());
8579            return;
8580        }
8581        destroyAppProfilesLeafLIF(pkg);
8582        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8583        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8584        for (int i = 0; i < childCount; i++) {
8585            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8586            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8587                    true /* removeBaseMarker */);
8588        }
8589    }
8590
8591    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8592            boolean removeBaseMarker) {
8593        if (pkg.isForwardLocked()) {
8594            return;
8595        }
8596
8597        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8598            try {
8599                path = PackageManagerServiceUtils.realpath(new File(path));
8600            } catch (IOException e) {
8601                // TODO: Should we return early here ?
8602                Slog.w(TAG, "Failed to get canonical path", e);
8603                continue;
8604            }
8605
8606            final String useMarker = path.replace('/', '@');
8607            for (int realUserId : resolveUserIds(userId)) {
8608                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8609                if (removeBaseMarker) {
8610                    File foreignUseMark = new File(profileDir, useMarker);
8611                    if (foreignUseMark.exists()) {
8612                        if (!foreignUseMark.delete()) {
8613                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8614                                    + pkg.packageName);
8615                        }
8616                    }
8617                }
8618
8619                File[] markers = profileDir.listFiles();
8620                if (markers != null) {
8621                    final String searchString = "@" + pkg.packageName + "@";
8622                    // We also delete all markers that contain the package name we're
8623                    // uninstalling. These are associated with secondary dex-files belonging
8624                    // to the package. Reconstructing the path of these dex files is messy
8625                    // in general.
8626                    for (File marker : markers) {
8627                        if (marker.getName().indexOf(searchString) > 0) {
8628                            if (!marker.delete()) {
8629                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8630                                    + pkg.packageName);
8631                            }
8632                        }
8633                    }
8634                }
8635            }
8636        }
8637    }
8638
8639    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8640        try {
8641            mInstaller.destroyAppProfiles(pkg.packageName);
8642        } catch (InstallerException e) {
8643            Slog.w(TAG, String.valueOf(e));
8644        }
8645    }
8646
8647    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8648        if (pkg == null) {
8649            Slog.wtf(TAG, "Package was null!", new Throwable());
8650            return;
8651        }
8652        clearAppProfilesLeafLIF(pkg);
8653        // We don't remove the base foreign use marker when clearing profiles because
8654        // we will rename it when the app is updated. Unlike the actual profile contents,
8655        // the foreign use marker is good across installs.
8656        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8657        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8658        for (int i = 0; i < childCount; i++) {
8659            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8660        }
8661    }
8662
8663    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8664        try {
8665            mInstaller.clearAppProfiles(pkg.packageName);
8666        } catch (InstallerException e) {
8667            Slog.w(TAG, String.valueOf(e));
8668        }
8669    }
8670
8671    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8672            long lastUpdateTime) {
8673        // Set parent install/update time
8674        PackageSetting ps = (PackageSetting) pkg.mExtras;
8675        if (ps != null) {
8676            ps.firstInstallTime = firstInstallTime;
8677            ps.lastUpdateTime = lastUpdateTime;
8678        }
8679        // Set children install/update time
8680        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8681        for (int i = 0; i < childCount; i++) {
8682            PackageParser.Package childPkg = pkg.childPackages.get(i);
8683            ps = (PackageSetting) childPkg.mExtras;
8684            if (ps != null) {
8685                ps.firstInstallTime = firstInstallTime;
8686                ps.lastUpdateTime = lastUpdateTime;
8687            }
8688        }
8689    }
8690
8691    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8692            PackageParser.Package changingLib) {
8693        if (file.path != null) {
8694            usesLibraryFiles.add(file.path);
8695            return;
8696        }
8697        PackageParser.Package p = mPackages.get(file.apk);
8698        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8699            // If we are doing this while in the middle of updating a library apk,
8700            // then we need to make sure to use that new apk for determining the
8701            // dependencies here.  (We haven't yet finished committing the new apk
8702            // to the package manager state.)
8703            if (p == null || p.packageName.equals(changingLib.packageName)) {
8704                p = changingLib;
8705            }
8706        }
8707        if (p != null) {
8708            usesLibraryFiles.addAll(p.getAllCodePaths());
8709        }
8710    }
8711
8712    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8713            PackageParser.Package changingLib) throws PackageManagerException {
8714        if (pkg == null) {
8715            return;
8716        }
8717        ArraySet<String> usesLibraryFiles = null;
8718        if (pkg.usesLibraries != null) {
8719            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8720                    null, null, pkg.packageName, changingLib, true, null);
8721        }
8722        if (pkg.usesStaticLibraries != null) {
8723            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8724                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8725                    pkg.packageName, changingLib, true, usesLibraryFiles);
8726        }
8727        if (pkg.usesOptionalLibraries != null) {
8728            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8729                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8730        }
8731        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8732            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8733        } else {
8734            pkg.usesLibraryFiles = null;
8735        }
8736    }
8737
8738    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8739            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8740            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8741            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8742            throws PackageManagerException {
8743        final int libCount = requestedLibraries.size();
8744        for (int i = 0; i < libCount; i++) {
8745            final String libName = requestedLibraries.get(i);
8746            final int libVersion = requiredVersions != null ? requiredVersions[i]
8747                    : SharedLibraryInfo.VERSION_UNDEFINED;
8748            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8749            if (libEntry == null) {
8750                if (required) {
8751                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8752                            "Package " + packageName + " requires unavailable shared library "
8753                                    + libName + "; failing!");
8754                } else {
8755                    Slog.w(TAG, "Package " + packageName
8756                            + " desires unavailable shared library "
8757                            + libName + "; ignoring!");
8758                }
8759            } else {
8760                if (requiredVersions != null && requiredCertDigests != null) {
8761                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8762                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8763                            "Package " + packageName + " requires unavailable static shared"
8764                                    + " library " + libName + " version "
8765                                    + libEntry.info.getVersion() + "; failing!");
8766                    }
8767
8768                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8769                    if (libPkg == null) {
8770                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8771                                "Package " + packageName + " requires unavailable static shared"
8772                                        + " library; failing!");
8773                    }
8774
8775                    String expectedCertDigest = requiredCertDigests[i];
8776                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8777                                libPkg.mSignatures[0]);
8778                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8779                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8780                                "Package " + packageName + " requires differently signed" +
8781                                        " static shared library; failing!");
8782                    }
8783                }
8784
8785                if (outUsedLibraries == null) {
8786                    outUsedLibraries = new ArraySet<>();
8787                }
8788                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8789            }
8790        }
8791        return outUsedLibraries;
8792    }
8793
8794    private static boolean hasString(List<String> list, List<String> which) {
8795        if (list == null) {
8796            return false;
8797        }
8798        for (int i=list.size()-1; i>=0; i--) {
8799            for (int j=which.size()-1; j>=0; j--) {
8800                if (which.get(j).equals(list.get(i))) {
8801                    return true;
8802                }
8803            }
8804        }
8805        return false;
8806    }
8807
8808    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8809            PackageParser.Package changingPkg) {
8810        ArrayList<PackageParser.Package> res = null;
8811        for (PackageParser.Package pkg : mPackages.values()) {
8812            if (changingPkg != null
8813                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8814                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8815                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8816                            changingPkg.staticSharedLibName)) {
8817                return null;
8818            }
8819            if (res == null) {
8820                res = new ArrayList<>();
8821            }
8822            res.add(pkg);
8823            try {
8824                updateSharedLibrariesLPr(pkg, changingPkg);
8825            } catch (PackageManagerException e) {
8826                // If a system app update or an app and a required lib missing we
8827                // delete the package and for updated system apps keep the data as
8828                // it is better for the user to reinstall than to be in an limbo
8829                // state. Also libs disappearing under an app should never happen
8830                // - just in case.
8831                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8832                    final int flags = pkg.isUpdatedSystemApp()
8833                            ? PackageManager.DELETE_KEEP_DATA : 0;
8834                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8835                            flags , null, true, null);
8836                }
8837                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8838            }
8839        }
8840        return res;
8841    }
8842
8843    /**
8844     * Derive the value of the {@code cpuAbiOverride} based on the provided
8845     * value and an optional stored value from the package settings.
8846     */
8847    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8848        String cpuAbiOverride = null;
8849
8850        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8851            cpuAbiOverride = null;
8852        } else if (abiOverride != null) {
8853            cpuAbiOverride = abiOverride;
8854        } else if (settings != null) {
8855            cpuAbiOverride = settings.cpuAbiOverrideString;
8856        }
8857
8858        return cpuAbiOverride;
8859    }
8860
8861    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8862            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8863                    throws PackageManagerException {
8864        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8865        // If the package has children and this is the first dive in the function
8866        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8867        // whether all packages (parent and children) would be successfully scanned
8868        // before the actual scan since scanning mutates internal state and we want
8869        // to atomically install the package and its children.
8870        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8871            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8872                scanFlags |= SCAN_CHECK_ONLY;
8873            }
8874        } else {
8875            scanFlags &= ~SCAN_CHECK_ONLY;
8876        }
8877
8878        final PackageParser.Package scannedPkg;
8879        try {
8880            // Scan the parent
8881            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8882            // Scan the children
8883            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8884            for (int i = 0; i < childCount; i++) {
8885                PackageParser.Package childPkg = pkg.childPackages.get(i);
8886                scanPackageLI(childPkg, policyFlags,
8887                        scanFlags, currentTime, user);
8888            }
8889        } finally {
8890            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8891        }
8892
8893        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8894            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8895        }
8896
8897        return scannedPkg;
8898    }
8899
8900    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8901            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8902        boolean success = false;
8903        try {
8904            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8905                    currentTime, user);
8906            success = true;
8907            return res;
8908        } finally {
8909            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8910                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8911                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8912                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8913                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8914            }
8915        }
8916    }
8917
8918    /**
8919     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8920     */
8921    private static boolean apkHasCode(String fileName) {
8922        StrictJarFile jarFile = null;
8923        try {
8924            jarFile = new StrictJarFile(fileName,
8925                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8926            return jarFile.findEntry("classes.dex") != null;
8927        } catch (IOException ignore) {
8928        } finally {
8929            try {
8930                if (jarFile != null) {
8931                    jarFile.close();
8932                }
8933            } catch (IOException ignore) {}
8934        }
8935        return false;
8936    }
8937
8938    /**
8939     * Enforces code policy for the package. This ensures that if an APK has
8940     * declared hasCode="true" in its manifest that the APK actually contains
8941     * code.
8942     *
8943     * @throws PackageManagerException If bytecode could not be found when it should exist
8944     */
8945    private static void assertCodePolicy(PackageParser.Package pkg)
8946            throws PackageManagerException {
8947        final boolean shouldHaveCode =
8948                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8949        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8950            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8951                    "Package " + pkg.baseCodePath + " code is missing");
8952        }
8953
8954        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8955            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8956                final boolean splitShouldHaveCode =
8957                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8958                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8959                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8960                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8961                }
8962            }
8963        }
8964    }
8965
8966    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8967            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8968                    throws PackageManagerException {
8969        if (DEBUG_PACKAGE_SCANNING) {
8970            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8971                Log.d(TAG, "Scanning package " + pkg.packageName);
8972        }
8973
8974        applyPolicy(pkg, policyFlags);
8975
8976        assertPackageIsValid(pkg, policyFlags, scanFlags);
8977
8978        // Initialize package source and resource directories
8979        final File scanFile = new File(pkg.codePath);
8980        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8981        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8982
8983        SharedUserSetting suid = null;
8984        PackageSetting pkgSetting = null;
8985
8986        // Getting the package setting may have a side-effect, so if we
8987        // are only checking if scan would succeed, stash a copy of the
8988        // old setting to restore at the end.
8989        PackageSetting nonMutatedPs = null;
8990
8991        // We keep references to the derived CPU Abis from settings in oder to reuse
8992        // them in the case where we're not upgrading or booting for the first time.
8993        String primaryCpuAbiFromSettings = null;
8994        String secondaryCpuAbiFromSettings = null;
8995
8996        // writer
8997        synchronized (mPackages) {
8998            if (pkg.mSharedUserId != null) {
8999                // SIDE EFFECTS; may potentially allocate a new shared user
9000                suid = mSettings.getSharedUserLPw(
9001                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9002                if (DEBUG_PACKAGE_SCANNING) {
9003                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9004                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9005                                + "): packages=" + suid.packages);
9006                }
9007            }
9008
9009            // Check if we are renaming from an original package name.
9010            PackageSetting origPackage = null;
9011            String realName = null;
9012            if (pkg.mOriginalPackages != null) {
9013                // This package may need to be renamed to a previously
9014                // installed name.  Let's check on that...
9015                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9016                if (pkg.mOriginalPackages.contains(renamed)) {
9017                    // This package had originally been installed as the
9018                    // original name, and we have already taken care of
9019                    // transitioning to the new one.  Just update the new
9020                    // one to continue using the old name.
9021                    realName = pkg.mRealPackage;
9022                    if (!pkg.packageName.equals(renamed)) {
9023                        // Callers into this function may have already taken
9024                        // care of renaming the package; only do it here if
9025                        // it is not already done.
9026                        pkg.setPackageName(renamed);
9027                    }
9028                } else {
9029                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9030                        if ((origPackage = mSettings.getPackageLPr(
9031                                pkg.mOriginalPackages.get(i))) != null) {
9032                            // We do have the package already installed under its
9033                            // original name...  should we use it?
9034                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9035                                // New package is not compatible with original.
9036                                origPackage = null;
9037                                continue;
9038                            } else if (origPackage.sharedUser != null) {
9039                                // Make sure uid is compatible between packages.
9040                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9041                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9042                                            + " to " + pkg.packageName + ": old uid "
9043                                            + origPackage.sharedUser.name
9044                                            + " differs from " + pkg.mSharedUserId);
9045                                    origPackage = null;
9046                                    continue;
9047                                }
9048                                // TODO: Add case when shared user id is added [b/28144775]
9049                            } else {
9050                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9051                                        + pkg.packageName + " to old name " + origPackage.name);
9052                            }
9053                            break;
9054                        }
9055                    }
9056                }
9057            }
9058
9059            if (mTransferedPackages.contains(pkg.packageName)) {
9060                Slog.w(TAG, "Package " + pkg.packageName
9061                        + " was transferred to another, but its .apk remains");
9062            }
9063
9064            // See comments in nonMutatedPs declaration
9065            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9066                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9067                if (foundPs != null) {
9068                    nonMutatedPs = new PackageSetting(foundPs);
9069                }
9070            }
9071
9072            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9073                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9074                if (foundPs != null) {
9075                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9076                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9077                }
9078            }
9079
9080            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9081            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9082                PackageManagerService.reportSettingsProblem(Log.WARN,
9083                        "Package " + pkg.packageName + " shared user changed from "
9084                                + (pkgSetting.sharedUser != null
9085                                        ? pkgSetting.sharedUser.name : "<nothing>")
9086                                + " to "
9087                                + (suid != null ? suid.name : "<nothing>")
9088                                + "; replacing with new");
9089                pkgSetting = null;
9090            }
9091            final PackageSetting oldPkgSetting =
9092                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9093            final PackageSetting disabledPkgSetting =
9094                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9095
9096            String[] usesStaticLibraries = null;
9097            if (pkg.usesStaticLibraries != null) {
9098                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9099                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9100            }
9101
9102            if (pkgSetting == null) {
9103                final String parentPackageName = (pkg.parentPackage != null)
9104                        ? pkg.parentPackage.packageName : null;
9105
9106                // REMOVE SharedUserSetting from method; update in a separate call
9107                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9108                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9109                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9110                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9111                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9112                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
9113                        UserManagerService.getInstance(), usesStaticLibraries,
9114                        pkg.usesStaticLibrariesVersions);
9115                // SIDE EFFECTS; updates system state; move elsewhere
9116                if (origPackage != null) {
9117                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9118                }
9119                mSettings.addUserToSettingLPw(pkgSetting);
9120            } else {
9121                // REMOVE SharedUserSetting from method; update in a separate call.
9122                //
9123                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9124                // secondaryCpuAbi are not known at this point so we always update them
9125                // to null here, only to reset them at a later point.
9126                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9127                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9128                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9129                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9130                        UserManagerService.getInstance(), usesStaticLibraries,
9131                        pkg.usesStaticLibrariesVersions);
9132            }
9133            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9134            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9135
9136            // SIDE EFFECTS; modifies system state; move elsewhere
9137            if (pkgSetting.origPackage != null) {
9138                // If we are first transitioning from an original package,
9139                // fix up the new package's name now.  We need to do this after
9140                // looking up the package under its new name, so getPackageLP
9141                // can take care of fiddling things correctly.
9142                pkg.setPackageName(origPackage.name);
9143
9144                // File a report about this.
9145                String msg = "New package " + pkgSetting.realName
9146                        + " renamed to replace old package " + pkgSetting.name;
9147                reportSettingsProblem(Log.WARN, msg);
9148
9149                // Make a note of it.
9150                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9151                    mTransferedPackages.add(origPackage.name);
9152                }
9153
9154                // No longer need to retain this.
9155                pkgSetting.origPackage = null;
9156            }
9157
9158            // SIDE EFFECTS; modifies system state; move elsewhere
9159            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9160                // Make a note of it.
9161                mTransferedPackages.add(pkg.packageName);
9162            }
9163
9164            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9165                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9166            }
9167
9168            if ((scanFlags & SCAN_BOOTING) == 0
9169                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9170                // Check all shared libraries and map to their actual file path.
9171                // We only do this here for apps not on a system dir, because those
9172                // are the only ones that can fail an install due to this.  We
9173                // will take care of the system apps by updating all of their
9174                // library paths after the scan is done. Also during the initial
9175                // scan don't update any libs as we do this wholesale after all
9176                // apps are scanned to avoid dependency based scanning.
9177                updateSharedLibrariesLPr(pkg, null);
9178            }
9179
9180            if (mFoundPolicyFile) {
9181                SELinuxMMAC.assignSeinfoValue(pkg);
9182            }
9183
9184            pkg.applicationInfo.uid = pkgSetting.appId;
9185            pkg.mExtras = pkgSetting;
9186
9187
9188            // Static shared libs have same package with different versions where
9189            // we internally use a synthetic package name to allow multiple versions
9190            // of the same package, therefore we need to compare signatures against
9191            // the package setting for the latest library version.
9192            PackageSetting signatureCheckPs = pkgSetting;
9193            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9194                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9195                if (libraryEntry != null) {
9196                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9197                }
9198            }
9199
9200            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9201                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9202                    // We just determined the app is signed correctly, so bring
9203                    // over the latest parsed certs.
9204                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9205                } else {
9206                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9207                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9208                                "Package " + pkg.packageName + " upgrade keys do not match the "
9209                                + "previously installed version");
9210                    } else {
9211                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9212                        String msg = "System package " + pkg.packageName
9213                                + " signature changed; retaining data.";
9214                        reportSettingsProblem(Log.WARN, msg);
9215                    }
9216                }
9217            } else {
9218                try {
9219                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9220                    verifySignaturesLP(signatureCheckPs, pkg);
9221                    // We just determined the app is signed correctly, so bring
9222                    // over the latest parsed certs.
9223                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9224                } catch (PackageManagerException e) {
9225                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9226                        throw e;
9227                    }
9228                    // The signature has changed, but this package is in the system
9229                    // image...  let's recover!
9230                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9231                    // However...  if this package is part of a shared user, but it
9232                    // doesn't match the signature of the shared user, let's fail.
9233                    // What this means is that you can't change the signatures
9234                    // associated with an overall shared user, which doesn't seem all
9235                    // that unreasonable.
9236                    if (signatureCheckPs.sharedUser != null) {
9237                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9238                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9239                            throw new PackageManagerException(
9240                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9241                                    "Signature mismatch for shared user: "
9242                                            + pkgSetting.sharedUser);
9243                        }
9244                    }
9245                    // File a report about this.
9246                    String msg = "System package " + pkg.packageName
9247                            + " signature changed; retaining data.";
9248                    reportSettingsProblem(Log.WARN, msg);
9249                }
9250            }
9251
9252            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9253                // This package wants to adopt ownership of permissions from
9254                // another package.
9255                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9256                    final String origName = pkg.mAdoptPermissions.get(i);
9257                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9258                    if (orig != null) {
9259                        if (verifyPackageUpdateLPr(orig, pkg)) {
9260                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9261                                    + pkg.packageName);
9262                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9263                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9264                        }
9265                    }
9266                }
9267            }
9268        }
9269
9270        pkg.applicationInfo.processName = fixProcessName(
9271                pkg.applicationInfo.packageName,
9272                pkg.applicationInfo.processName);
9273
9274        if (pkg != mPlatformPackage) {
9275            // Get all of our default paths setup
9276            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9277        }
9278
9279        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9280
9281        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9282            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9283                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9284                derivePackageAbi(
9285                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9286                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9287
9288                // Some system apps still use directory structure for native libraries
9289                // in which case we might end up not detecting abi solely based on apk
9290                // structure. Try to detect abi based on directory structure.
9291                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9292                        pkg.applicationInfo.primaryCpuAbi == null) {
9293                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9294                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9295                }
9296            } else {
9297                // This is not a first boot or an upgrade, don't bother deriving the
9298                // ABI during the scan. Instead, trust the value that was stored in the
9299                // package setting.
9300                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9301                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9302
9303                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9304
9305                if (DEBUG_ABI_SELECTION) {
9306                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9307                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9308                        pkg.applicationInfo.secondaryCpuAbi);
9309                }
9310            }
9311        } else {
9312            if ((scanFlags & SCAN_MOVE) != 0) {
9313                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9314                // but we already have this packages package info in the PackageSetting. We just
9315                // use that and derive the native library path based on the new codepath.
9316                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9317                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9318            }
9319
9320            // Set native library paths again. For moves, the path will be updated based on the
9321            // ABIs we've determined above. For non-moves, the path will be updated based on the
9322            // ABIs we determined during compilation, but the path will depend on the final
9323            // package path (after the rename away from the stage path).
9324            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9325        }
9326
9327        // This is a special case for the "system" package, where the ABI is
9328        // dictated by the zygote configuration (and init.rc). We should keep track
9329        // of this ABI so that we can deal with "normal" applications that run under
9330        // the same UID correctly.
9331        if (mPlatformPackage == pkg) {
9332            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9333                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9334        }
9335
9336        // If there's a mismatch between the abi-override in the package setting
9337        // and the abiOverride specified for the install. Warn about this because we
9338        // would've already compiled the app without taking the package setting into
9339        // account.
9340        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9341            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9342                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9343                        " for package " + pkg.packageName);
9344            }
9345        }
9346
9347        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9348        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9349        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9350
9351        // Copy the derived override back to the parsed package, so that we can
9352        // update the package settings accordingly.
9353        pkg.cpuAbiOverride = cpuAbiOverride;
9354
9355        if (DEBUG_ABI_SELECTION) {
9356            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9357                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9358                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9359        }
9360
9361        // Push the derived path down into PackageSettings so we know what to
9362        // clean up at uninstall time.
9363        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9364
9365        if (DEBUG_ABI_SELECTION) {
9366            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9367                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9368                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9369        }
9370
9371        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9372        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9373            // We don't do this here during boot because we can do it all
9374            // at once after scanning all existing packages.
9375            //
9376            // We also do this *before* we perform dexopt on this package, so that
9377            // we can avoid redundant dexopts, and also to make sure we've got the
9378            // code and package path correct.
9379            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9380        }
9381
9382        if (mFactoryTest && pkg.requestedPermissions.contains(
9383                android.Manifest.permission.FACTORY_TEST)) {
9384            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9385        }
9386
9387        if (isSystemApp(pkg)) {
9388            pkgSetting.isOrphaned = true;
9389        }
9390
9391        // Take care of first install / last update times.
9392        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9393        if (currentTime != 0) {
9394            if (pkgSetting.firstInstallTime == 0) {
9395                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9396            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9397                pkgSetting.lastUpdateTime = currentTime;
9398            }
9399        } else if (pkgSetting.firstInstallTime == 0) {
9400            // We need *something*.  Take time time stamp of the file.
9401            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9402        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9403            if (scanFileTime != pkgSetting.timeStamp) {
9404                // A package on the system image has changed; consider this
9405                // to be an update.
9406                pkgSetting.lastUpdateTime = scanFileTime;
9407            }
9408        }
9409        pkgSetting.setTimeStamp(scanFileTime);
9410
9411        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9412            if (nonMutatedPs != null) {
9413                synchronized (mPackages) {
9414                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9415                }
9416            }
9417        } else {
9418            // Modify state for the given package setting
9419            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9420                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9421            if (isEphemeral(pkg)) {
9422                final int userId = user == null ? 0 : user.getIdentifier();
9423                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9424            }
9425        }
9426        return pkg;
9427    }
9428
9429    /**
9430     * Applies policy to the parsed package based upon the given policy flags.
9431     * Ensures the package is in a good state.
9432     * <p>
9433     * Implementation detail: This method must NOT have any side effect. It would
9434     * ideally be static, but, it requires locks to read system state.
9435     */
9436    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9437        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9438            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9439            if (pkg.applicationInfo.isDirectBootAware()) {
9440                // we're direct boot aware; set for all components
9441                for (PackageParser.Service s : pkg.services) {
9442                    s.info.encryptionAware = s.info.directBootAware = true;
9443                }
9444                for (PackageParser.Provider p : pkg.providers) {
9445                    p.info.encryptionAware = p.info.directBootAware = true;
9446                }
9447                for (PackageParser.Activity a : pkg.activities) {
9448                    a.info.encryptionAware = a.info.directBootAware = true;
9449                }
9450                for (PackageParser.Activity r : pkg.receivers) {
9451                    r.info.encryptionAware = r.info.directBootAware = true;
9452                }
9453            }
9454        } else {
9455            // Only allow system apps to be flagged as core apps.
9456            pkg.coreApp = false;
9457            // clear flags not applicable to regular apps
9458            pkg.applicationInfo.privateFlags &=
9459                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9460            pkg.applicationInfo.privateFlags &=
9461                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9462        }
9463        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9464
9465        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9466            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9467        }
9468
9469        if (!isSystemApp(pkg)) {
9470            // Only system apps can use these features.
9471            pkg.mOriginalPackages = null;
9472            pkg.mRealPackage = null;
9473            pkg.mAdoptPermissions = null;
9474        }
9475    }
9476
9477    /**
9478     * Asserts the parsed package is valid according to the given policy. If the
9479     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9480     * <p>
9481     * Implementation detail: This method must NOT have any side effects. It would
9482     * ideally be static, but, it requires locks to read system state.
9483     *
9484     * @throws PackageManagerException If the package fails any of the validation checks
9485     */
9486    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9487            throws PackageManagerException {
9488        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9489            assertCodePolicy(pkg);
9490        }
9491
9492        if (pkg.applicationInfo.getCodePath() == null ||
9493                pkg.applicationInfo.getResourcePath() == null) {
9494            // Bail out. The resource and code paths haven't been set.
9495            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9496                    "Code and resource paths haven't been set correctly");
9497        }
9498
9499        // Make sure we're not adding any bogus keyset info
9500        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9501        ksms.assertScannedPackageValid(pkg);
9502
9503        synchronized (mPackages) {
9504            // The special "android" package can only be defined once
9505            if (pkg.packageName.equals("android")) {
9506                if (mAndroidApplication != null) {
9507                    Slog.w(TAG, "*************************************************");
9508                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9509                    Slog.w(TAG, " codePath=" + pkg.codePath);
9510                    Slog.w(TAG, "*************************************************");
9511                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9512                            "Core android package being redefined.  Skipping.");
9513                }
9514            }
9515
9516            // A package name must be unique; don't allow duplicates
9517            if (mPackages.containsKey(pkg.packageName)) {
9518                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9519                        "Application package " + pkg.packageName
9520                        + " already installed.  Skipping duplicate.");
9521            }
9522
9523            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9524                // Static libs have a synthetic package name containing the version
9525                // but we still want the base name to be unique.
9526                if (mPackages.containsKey(pkg.manifestPackageName)) {
9527                    throw new PackageManagerException(
9528                            "Duplicate static shared lib provider package");
9529                }
9530
9531                // Static shared libraries should have at least O target SDK
9532                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9533                    throw new PackageManagerException(
9534                            "Packages declaring static-shared libs must target O SDK or higher");
9535                }
9536
9537                // Package declaring static a shared lib cannot be ephemeral
9538                if (pkg.applicationInfo.isInstantApp()) {
9539                    throw new PackageManagerException(
9540                            "Packages declaring static-shared libs cannot be ephemeral");
9541                }
9542
9543                // Package declaring static a shared lib cannot be renamed since the package
9544                // name is synthetic and apps can't code around package manager internals.
9545                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9546                    throw new PackageManagerException(
9547                            "Packages declaring static-shared libs cannot be renamed");
9548                }
9549
9550                // Package declaring static a shared lib cannot declare child packages
9551                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9552                    throw new PackageManagerException(
9553                            "Packages declaring static-shared libs cannot have child packages");
9554                }
9555
9556                // Package declaring static a shared lib cannot declare dynamic libs
9557                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9558                    throw new PackageManagerException(
9559                            "Packages declaring static-shared libs cannot declare dynamic libs");
9560                }
9561
9562                // Package declaring static a shared lib cannot declare shared users
9563                if (pkg.mSharedUserId != null) {
9564                    throw new PackageManagerException(
9565                            "Packages declaring static-shared libs cannot declare shared users");
9566                }
9567
9568                // Static shared libs cannot declare activities
9569                if (!pkg.activities.isEmpty()) {
9570                    throw new PackageManagerException(
9571                            "Static shared libs cannot declare activities");
9572                }
9573
9574                // Static shared libs cannot declare services
9575                if (!pkg.services.isEmpty()) {
9576                    throw new PackageManagerException(
9577                            "Static shared libs cannot declare services");
9578                }
9579
9580                // Static shared libs cannot declare providers
9581                if (!pkg.providers.isEmpty()) {
9582                    throw new PackageManagerException(
9583                            "Static shared libs cannot declare content providers");
9584                }
9585
9586                // Static shared libs cannot declare receivers
9587                if (!pkg.receivers.isEmpty()) {
9588                    throw new PackageManagerException(
9589                            "Static shared libs cannot declare broadcast receivers");
9590                }
9591
9592                // Static shared libs cannot declare permission groups
9593                if (!pkg.permissionGroups.isEmpty()) {
9594                    throw new PackageManagerException(
9595                            "Static shared libs cannot declare permission groups");
9596                }
9597
9598                // Static shared libs cannot declare permissions
9599                if (!pkg.permissions.isEmpty()) {
9600                    throw new PackageManagerException(
9601                            "Static shared libs cannot declare permissions");
9602                }
9603
9604                // Static shared libs cannot declare protected broadcasts
9605                if (pkg.protectedBroadcasts != null) {
9606                    throw new PackageManagerException(
9607                            "Static shared libs cannot declare protected broadcasts");
9608                }
9609
9610                // Static shared libs cannot be overlay targets
9611                if (pkg.mOverlayTarget != null) {
9612                    throw new PackageManagerException(
9613                            "Static shared libs cannot be overlay targets");
9614                }
9615
9616                // The version codes must be ordered as lib versions
9617                int minVersionCode = Integer.MIN_VALUE;
9618                int maxVersionCode = Integer.MAX_VALUE;
9619
9620                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9621                        pkg.staticSharedLibName);
9622                if (versionedLib != null) {
9623                    final int versionCount = versionedLib.size();
9624                    for (int i = 0; i < versionCount; i++) {
9625                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9626                        // TODO: We will change version code to long, so in the new API it is long
9627                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9628                                .getVersionCode();
9629                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9630                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9631                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9632                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9633                        } else {
9634                            minVersionCode = maxVersionCode = libVersionCode;
9635                            break;
9636                        }
9637                    }
9638                }
9639                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9640                    throw new PackageManagerException("Static shared"
9641                            + " lib version codes must be ordered as lib versions");
9642                }
9643            }
9644
9645            // Only privileged apps and updated privileged apps can add child packages.
9646            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9647                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9648                    throw new PackageManagerException("Only privileged apps can add child "
9649                            + "packages. Ignoring package " + pkg.packageName);
9650                }
9651                final int childCount = pkg.childPackages.size();
9652                for (int i = 0; i < childCount; i++) {
9653                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9654                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9655                            childPkg.packageName)) {
9656                        throw new PackageManagerException("Can't override child of "
9657                                + "another disabled app. Ignoring package " + pkg.packageName);
9658                    }
9659                }
9660            }
9661
9662            // If we're only installing presumed-existing packages, require that the
9663            // scanned APK is both already known and at the path previously established
9664            // for it.  Previously unknown packages we pick up normally, but if we have an
9665            // a priori expectation about this package's install presence, enforce it.
9666            // With a singular exception for new system packages. When an OTA contains
9667            // a new system package, we allow the codepath to change from a system location
9668            // to the user-installed location. If we don't allow this change, any newer,
9669            // user-installed version of the application will be ignored.
9670            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9671                if (mExpectingBetter.containsKey(pkg.packageName)) {
9672                    logCriticalInfo(Log.WARN,
9673                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9674                } else {
9675                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9676                    if (known != null) {
9677                        if (DEBUG_PACKAGE_SCANNING) {
9678                            Log.d(TAG, "Examining " + pkg.codePath
9679                                    + " and requiring known paths " + known.codePathString
9680                                    + " & " + known.resourcePathString);
9681                        }
9682                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9683                                || !pkg.applicationInfo.getResourcePath().equals(
9684                                        known.resourcePathString)) {
9685                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9686                                    "Application package " + pkg.packageName
9687                                    + " found at " + pkg.applicationInfo.getCodePath()
9688                                    + " but expected at " + known.codePathString
9689                                    + "; ignoring.");
9690                        }
9691                    }
9692                }
9693            }
9694
9695            // Verify that this new package doesn't have any content providers
9696            // that conflict with existing packages.  Only do this if the
9697            // package isn't already installed, since we don't want to break
9698            // things that are installed.
9699            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9700                final int N = pkg.providers.size();
9701                int i;
9702                for (i=0; i<N; i++) {
9703                    PackageParser.Provider p = pkg.providers.get(i);
9704                    if (p.info.authority != null) {
9705                        String names[] = p.info.authority.split(";");
9706                        for (int j = 0; j < names.length; j++) {
9707                            if (mProvidersByAuthority.containsKey(names[j])) {
9708                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9709                                final String otherPackageName =
9710                                        ((other != null && other.getComponentName() != null) ?
9711                                                other.getComponentName().getPackageName() : "?");
9712                                throw new PackageManagerException(
9713                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9714                                        "Can't install because provider name " + names[j]
9715                                                + " (in package " + pkg.applicationInfo.packageName
9716                                                + ") is already used by " + otherPackageName);
9717                            }
9718                        }
9719                    }
9720                }
9721            }
9722        }
9723    }
9724
9725    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9726            int type, String declaringPackageName, int declaringVersionCode) {
9727        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9728        if (versionedLib == null) {
9729            versionedLib = new SparseArray<>();
9730            mSharedLibraries.put(name, versionedLib);
9731            if (type == SharedLibraryInfo.TYPE_STATIC) {
9732                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9733            }
9734        } else if (versionedLib.indexOfKey(version) >= 0) {
9735            return false;
9736        }
9737        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9738                version, type, declaringPackageName, declaringVersionCode);
9739        versionedLib.put(version, libEntry);
9740        return true;
9741    }
9742
9743    private boolean removeSharedLibraryLPw(String name, int version) {
9744        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9745        if (versionedLib == null) {
9746            return false;
9747        }
9748        final int libIdx = versionedLib.indexOfKey(version);
9749        if (libIdx < 0) {
9750            return false;
9751        }
9752        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9753        versionedLib.remove(version);
9754        if (versionedLib.size() <= 0) {
9755            mSharedLibraries.remove(name);
9756            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9757                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9758                        .getPackageName());
9759            }
9760        }
9761        return true;
9762    }
9763
9764    /**
9765     * Adds a scanned package to the system. When this method is finished, the package will
9766     * be available for query, resolution, etc...
9767     */
9768    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9769            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9770        final String pkgName = pkg.packageName;
9771        if (mCustomResolverComponentName != null &&
9772                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9773            setUpCustomResolverActivity(pkg);
9774        }
9775
9776        if (pkg.packageName.equals("android")) {
9777            synchronized (mPackages) {
9778                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9779                    // Set up information for our fall-back user intent resolution activity.
9780                    mPlatformPackage = pkg;
9781                    pkg.mVersionCode = mSdkVersion;
9782                    mAndroidApplication = pkg.applicationInfo;
9783
9784                    if (!mResolverReplaced) {
9785                        mResolveActivity.applicationInfo = mAndroidApplication;
9786                        mResolveActivity.name = ResolverActivity.class.getName();
9787                        mResolveActivity.packageName = mAndroidApplication.packageName;
9788                        mResolveActivity.processName = "system:ui";
9789                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9790                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9791                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9792                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9793                        mResolveActivity.exported = true;
9794                        mResolveActivity.enabled = true;
9795                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9796                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9797                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9798                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9799                                | ActivityInfo.CONFIG_ORIENTATION
9800                                | ActivityInfo.CONFIG_KEYBOARD
9801                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9802                        mResolveInfo.activityInfo = mResolveActivity;
9803                        mResolveInfo.priority = 0;
9804                        mResolveInfo.preferredOrder = 0;
9805                        mResolveInfo.match = 0;
9806                        mResolveComponentName = new ComponentName(
9807                                mAndroidApplication.packageName, mResolveActivity.name);
9808                    }
9809                }
9810            }
9811        }
9812
9813        ArrayList<PackageParser.Package> clientLibPkgs = null;
9814        // writer
9815        synchronized (mPackages) {
9816            boolean hasStaticSharedLibs = false;
9817
9818            // Any app can add new static shared libraries
9819            if (pkg.staticSharedLibName != null) {
9820                // Static shared libs don't allow renaming as they have synthetic package
9821                // names to allow install of multiple versions, so use name from manifest.
9822                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9823                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9824                        pkg.manifestPackageName, pkg.mVersionCode)) {
9825                    hasStaticSharedLibs = true;
9826                } else {
9827                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9828                                + pkg.staticSharedLibName + " already exists; skipping");
9829                }
9830                // Static shared libs cannot be updated once installed since they
9831                // use synthetic package name which includes the version code, so
9832                // not need to update other packages's shared lib dependencies.
9833            }
9834
9835            if (!hasStaticSharedLibs
9836                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9837                // Only system apps can add new dynamic shared libraries.
9838                if (pkg.libraryNames != null) {
9839                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9840                        String name = pkg.libraryNames.get(i);
9841                        boolean allowed = false;
9842                        if (pkg.isUpdatedSystemApp()) {
9843                            // New library entries can only be added through the
9844                            // system image.  This is important to get rid of a lot
9845                            // of nasty edge cases: for example if we allowed a non-
9846                            // system update of the app to add a library, then uninstalling
9847                            // the update would make the library go away, and assumptions
9848                            // we made such as through app install filtering would now
9849                            // have allowed apps on the device which aren't compatible
9850                            // with it.  Better to just have the restriction here, be
9851                            // conservative, and create many fewer cases that can negatively
9852                            // impact the user experience.
9853                            final PackageSetting sysPs = mSettings
9854                                    .getDisabledSystemPkgLPr(pkg.packageName);
9855                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9856                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9857                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9858                                        allowed = true;
9859                                        break;
9860                                    }
9861                                }
9862                            }
9863                        } else {
9864                            allowed = true;
9865                        }
9866                        if (allowed) {
9867                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9868                                    SharedLibraryInfo.VERSION_UNDEFINED,
9869                                    SharedLibraryInfo.TYPE_DYNAMIC,
9870                                    pkg.packageName, pkg.mVersionCode)) {
9871                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9872                                        + name + " already exists; skipping");
9873                            }
9874                        } else {
9875                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9876                                    + name + " that is not declared on system image; skipping");
9877                        }
9878                    }
9879
9880                    if ((scanFlags & SCAN_BOOTING) == 0) {
9881                        // If we are not booting, we need to update any applications
9882                        // that are clients of our shared library.  If we are booting,
9883                        // this will all be done once the scan is complete.
9884                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9885                    }
9886                }
9887            }
9888        }
9889
9890        if ((scanFlags & SCAN_BOOTING) != 0) {
9891            // No apps can run during boot scan, so they don't need to be frozen
9892        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9893            // Caller asked to not kill app, so it's probably not frozen
9894        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9895            // Caller asked us to ignore frozen check for some reason; they
9896            // probably didn't know the package name
9897        } else {
9898            // We're doing major surgery on this package, so it better be frozen
9899            // right now to keep it from launching
9900            checkPackageFrozen(pkgName);
9901        }
9902
9903        // Also need to kill any apps that are dependent on the library.
9904        if (clientLibPkgs != null) {
9905            for (int i=0; i<clientLibPkgs.size(); i++) {
9906                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9907                killApplication(clientPkg.applicationInfo.packageName,
9908                        clientPkg.applicationInfo.uid, "update lib");
9909            }
9910        }
9911
9912        // writer
9913        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9914
9915        boolean createIdmapFailed = false;
9916        synchronized (mPackages) {
9917            // We don't expect installation to fail beyond this point
9918
9919            if (pkgSetting.pkg != null) {
9920                // Note that |user| might be null during the initial boot scan. If a codePath
9921                // for an app has changed during a boot scan, it's due to an app update that's
9922                // part of the system partition and marker changes must be applied to all users.
9923                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9924                final int[] userIds = resolveUserIds(userId);
9925                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9926            }
9927
9928            // Add the new setting to mSettings
9929            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9930            // Add the new setting to mPackages
9931            mPackages.put(pkg.applicationInfo.packageName, pkg);
9932            // Make sure we don't accidentally delete its data.
9933            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9934            while (iter.hasNext()) {
9935                PackageCleanItem item = iter.next();
9936                if (pkgName.equals(item.packageName)) {
9937                    iter.remove();
9938                }
9939            }
9940
9941            // Add the package's KeySets to the global KeySetManagerService
9942            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9943            ksms.addScannedPackageLPw(pkg);
9944
9945            int N = pkg.providers.size();
9946            StringBuilder r = null;
9947            int i;
9948            for (i=0; i<N; i++) {
9949                PackageParser.Provider p = pkg.providers.get(i);
9950                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9951                        p.info.processName);
9952                mProviders.addProvider(p);
9953                p.syncable = p.info.isSyncable;
9954                if (p.info.authority != null) {
9955                    String names[] = p.info.authority.split(";");
9956                    p.info.authority = null;
9957                    for (int j = 0; j < names.length; j++) {
9958                        if (j == 1 && p.syncable) {
9959                            // We only want the first authority for a provider to possibly be
9960                            // syncable, so if we already added this provider using a different
9961                            // authority clear the syncable flag. We copy the provider before
9962                            // changing it because the mProviders object contains a reference
9963                            // to a provider that we don't want to change.
9964                            // Only do this for the second authority since the resulting provider
9965                            // object can be the same for all future authorities for this provider.
9966                            p = new PackageParser.Provider(p);
9967                            p.syncable = false;
9968                        }
9969                        if (!mProvidersByAuthority.containsKey(names[j])) {
9970                            mProvidersByAuthority.put(names[j], p);
9971                            if (p.info.authority == null) {
9972                                p.info.authority = names[j];
9973                            } else {
9974                                p.info.authority = p.info.authority + ";" + names[j];
9975                            }
9976                            if (DEBUG_PACKAGE_SCANNING) {
9977                                if (chatty)
9978                                    Log.d(TAG, "Registered content provider: " + names[j]
9979                                            + ", className = " + p.info.name + ", isSyncable = "
9980                                            + p.info.isSyncable);
9981                            }
9982                        } else {
9983                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9984                            Slog.w(TAG, "Skipping provider name " + names[j] +
9985                                    " (in package " + pkg.applicationInfo.packageName +
9986                                    "): name already used by "
9987                                    + ((other != null && other.getComponentName() != null)
9988                                            ? other.getComponentName().getPackageName() : "?"));
9989                        }
9990                    }
9991                }
9992                if (chatty) {
9993                    if (r == null) {
9994                        r = new StringBuilder(256);
9995                    } else {
9996                        r.append(' ');
9997                    }
9998                    r.append(p.info.name);
9999                }
10000            }
10001            if (r != null) {
10002                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10003            }
10004
10005            N = pkg.services.size();
10006            r = null;
10007            for (i=0; i<N; i++) {
10008                PackageParser.Service s = pkg.services.get(i);
10009                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10010                        s.info.processName);
10011                mServices.addService(s);
10012                if (chatty) {
10013                    if (r == null) {
10014                        r = new StringBuilder(256);
10015                    } else {
10016                        r.append(' ');
10017                    }
10018                    r.append(s.info.name);
10019                }
10020            }
10021            if (r != null) {
10022                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10023            }
10024
10025            N = pkg.receivers.size();
10026            r = null;
10027            for (i=0; i<N; i++) {
10028                PackageParser.Activity a = pkg.receivers.get(i);
10029                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10030                        a.info.processName);
10031                mReceivers.addActivity(a, "receiver");
10032                if (chatty) {
10033                    if (r == null) {
10034                        r = new StringBuilder(256);
10035                    } else {
10036                        r.append(' ');
10037                    }
10038                    r.append(a.info.name);
10039                }
10040            }
10041            if (r != null) {
10042                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10043            }
10044
10045            N = pkg.activities.size();
10046            r = null;
10047            for (i=0; i<N; i++) {
10048                PackageParser.Activity a = pkg.activities.get(i);
10049                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10050                        a.info.processName);
10051                mActivities.addActivity(a, "activity");
10052                if (chatty) {
10053                    if (r == null) {
10054                        r = new StringBuilder(256);
10055                    } else {
10056                        r.append(' ');
10057                    }
10058                    r.append(a.info.name);
10059                }
10060            }
10061            if (r != null) {
10062                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10063            }
10064
10065            N = pkg.permissionGroups.size();
10066            r = null;
10067            for (i=0; i<N; i++) {
10068                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10069                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10070                final String curPackageName = cur == null ? null : cur.info.packageName;
10071                // Dont allow ephemeral apps to define new permission groups.
10072                if (pkg.applicationInfo.isInstantApp()) {
10073                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10074                            + pg.info.packageName
10075                            + " ignored: ephemeral apps cannot define new permission groups.");
10076                    continue;
10077                }
10078                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10079                if (cur == null || isPackageUpdate) {
10080                    mPermissionGroups.put(pg.info.name, pg);
10081                    if (chatty) {
10082                        if (r == null) {
10083                            r = new StringBuilder(256);
10084                        } else {
10085                            r.append(' ');
10086                        }
10087                        if (isPackageUpdate) {
10088                            r.append("UPD:");
10089                        }
10090                        r.append(pg.info.name);
10091                    }
10092                } else {
10093                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10094                            + pg.info.packageName + " ignored: original from "
10095                            + cur.info.packageName);
10096                    if (chatty) {
10097                        if (r == null) {
10098                            r = new StringBuilder(256);
10099                        } else {
10100                            r.append(' ');
10101                        }
10102                        r.append("DUP:");
10103                        r.append(pg.info.name);
10104                    }
10105                }
10106            }
10107            if (r != null) {
10108                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10109            }
10110
10111            N = pkg.permissions.size();
10112            r = null;
10113            for (i=0; i<N; i++) {
10114                PackageParser.Permission p = pkg.permissions.get(i);
10115
10116                // Dont allow ephemeral apps to define new permissions.
10117                if (pkg.applicationInfo.isInstantApp()) {
10118                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10119                            + p.info.packageName
10120                            + " ignored: ephemeral apps cannot define new permissions.");
10121                    continue;
10122                }
10123
10124                // Assume by default that we did not install this permission into the system.
10125                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10126
10127                // Now that permission groups have a special meaning, we ignore permission
10128                // groups for legacy apps to prevent unexpected behavior. In particular,
10129                // permissions for one app being granted to someone just becase they happen
10130                // to be in a group defined by another app (before this had no implications).
10131                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10132                    p.group = mPermissionGroups.get(p.info.group);
10133                    // Warn for a permission in an unknown group.
10134                    if (p.info.group != null && p.group == null) {
10135                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10136                                + p.info.packageName + " in an unknown group " + p.info.group);
10137                    }
10138                }
10139
10140                ArrayMap<String, BasePermission> permissionMap =
10141                        p.tree ? mSettings.mPermissionTrees
10142                                : mSettings.mPermissions;
10143                BasePermission bp = permissionMap.get(p.info.name);
10144
10145                // Allow system apps to redefine non-system permissions
10146                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10147                    final boolean currentOwnerIsSystem = (bp.perm != null
10148                            && isSystemApp(bp.perm.owner));
10149                    if (isSystemApp(p.owner)) {
10150                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10151                            // It's a built-in permission and no owner, take ownership now
10152                            bp.packageSetting = pkgSetting;
10153                            bp.perm = p;
10154                            bp.uid = pkg.applicationInfo.uid;
10155                            bp.sourcePackage = p.info.packageName;
10156                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10157                        } else if (!currentOwnerIsSystem) {
10158                            String msg = "New decl " + p.owner + " of permission  "
10159                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10160                            reportSettingsProblem(Log.WARN, msg);
10161                            bp = null;
10162                        }
10163                    }
10164                }
10165
10166                if (bp == null) {
10167                    bp = new BasePermission(p.info.name, p.info.packageName,
10168                            BasePermission.TYPE_NORMAL);
10169                    permissionMap.put(p.info.name, bp);
10170                }
10171
10172                if (bp.perm == null) {
10173                    if (bp.sourcePackage == null
10174                            || bp.sourcePackage.equals(p.info.packageName)) {
10175                        BasePermission tree = findPermissionTreeLP(p.info.name);
10176                        if (tree == null
10177                                || tree.sourcePackage.equals(p.info.packageName)) {
10178                            bp.packageSetting = pkgSetting;
10179                            bp.perm = p;
10180                            bp.uid = pkg.applicationInfo.uid;
10181                            bp.sourcePackage = p.info.packageName;
10182                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10183                            if (chatty) {
10184                                if (r == null) {
10185                                    r = new StringBuilder(256);
10186                                } else {
10187                                    r.append(' ');
10188                                }
10189                                r.append(p.info.name);
10190                            }
10191                        } else {
10192                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10193                                    + p.info.packageName + " ignored: base tree "
10194                                    + tree.name + " is from package "
10195                                    + tree.sourcePackage);
10196                        }
10197                    } else {
10198                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10199                                + p.info.packageName + " ignored: original from "
10200                                + bp.sourcePackage);
10201                    }
10202                } else if (chatty) {
10203                    if (r == null) {
10204                        r = new StringBuilder(256);
10205                    } else {
10206                        r.append(' ');
10207                    }
10208                    r.append("DUP:");
10209                    r.append(p.info.name);
10210                }
10211                if (bp.perm == p) {
10212                    bp.protectionLevel = p.info.protectionLevel;
10213                }
10214            }
10215
10216            if (r != null) {
10217                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10218            }
10219
10220            N = pkg.instrumentation.size();
10221            r = null;
10222            for (i=0; i<N; i++) {
10223                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10224                a.info.packageName = pkg.applicationInfo.packageName;
10225                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10226                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10227                a.info.splitNames = pkg.splitNames;
10228                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10229                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10230                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10231                a.info.dataDir = pkg.applicationInfo.dataDir;
10232                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10233                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10234                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10235                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10236                mInstrumentation.put(a.getComponentName(), a);
10237                if (chatty) {
10238                    if (r == null) {
10239                        r = new StringBuilder(256);
10240                    } else {
10241                        r.append(' ');
10242                    }
10243                    r.append(a.info.name);
10244                }
10245            }
10246            if (r != null) {
10247                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10248            }
10249
10250            if (pkg.protectedBroadcasts != null) {
10251                N = pkg.protectedBroadcasts.size();
10252                for (i=0; i<N; i++) {
10253                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10254                }
10255            }
10256
10257            // Create idmap files for pairs of (packages, overlay packages).
10258            // Note: "android", ie framework-res.apk, is handled by native layers.
10259            if (pkg.mOverlayTarget != null) {
10260                // This is an overlay package.
10261                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10262                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10263                        mOverlays.put(pkg.mOverlayTarget,
10264                                new ArrayMap<String, PackageParser.Package>());
10265                    }
10266                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10267                    map.put(pkg.packageName, pkg);
10268                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10269                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10270                        createIdmapFailed = true;
10271                    }
10272                }
10273            } else if (mOverlays.containsKey(pkg.packageName) &&
10274                    !pkg.packageName.equals("android")) {
10275                // This is a regular package, with one or more known overlay packages.
10276                createIdmapsForPackageLI(pkg);
10277            }
10278        }
10279
10280        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10281
10282        if (createIdmapFailed) {
10283            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10284                    "scanPackageLI failed to createIdmap");
10285        }
10286    }
10287
10288    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10289            PackageParser.Package update, int[] userIds) {
10290        if (existing.applicationInfo == null || update.applicationInfo == null) {
10291            // This isn't due to an app installation.
10292            return;
10293        }
10294
10295        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10296        final File newCodePath = new File(update.applicationInfo.getCodePath());
10297
10298        // The codePath hasn't changed, so there's nothing for us to do.
10299        if (Objects.equals(oldCodePath, newCodePath)) {
10300            return;
10301        }
10302
10303        File canonicalNewCodePath;
10304        try {
10305            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10306        } catch (IOException e) {
10307            Slog.w(TAG, "Failed to get canonical path.", e);
10308            return;
10309        }
10310
10311        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10312        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10313        // that the last component of the path (i.e, the name) doesn't need canonicalization
10314        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10315        // but may change in the future. Hopefully this function won't exist at that point.
10316        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10317                oldCodePath.getName());
10318
10319        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10320        // with "@".
10321        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10322        if (!oldMarkerPrefix.endsWith("@")) {
10323            oldMarkerPrefix += "@";
10324        }
10325        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10326        if (!newMarkerPrefix.endsWith("@")) {
10327            newMarkerPrefix += "@";
10328        }
10329
10330        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10331        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10332        for (String updatedPath : updatedPaths) {
10333            String updatedPathName = new File(updatedPath).getName();
10334            markerSuffixes.add(updatedPathName.replace('/', '@'));
10335        }
10336
10337        for (int userId : userIds) {
10338            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10339
10340            for (String markerSuffix : markerSuffixes) {
10341                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10342                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10343                if (oldForeignUseMark.exists()) {
10344                    try {
10345                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10346                                newForeignUseMark.getAbsolutePath());
10347                    } catch (ErrnoException e) {
10348                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10349                        oldForeignUseMark.delete();
10350                    }
10351                }
10352            }
10353        }
10354    }
10355
10356    /**
10357     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10358     * is derived purely on the basis of the contents of {@code scanFile} and
10359     * {@code cpuAbiOverride}.
10360     *
10361     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10362     */
10363    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10364                                 String cpuAbiOverride, boolean extractLibs,
10365                                 File appLib32InstallDir)
10366            throws PackageManagerException {
10367        // Give ourselves some initial paths; we'll come back for another
10368        // pass once we've determined ABI below.
10369        setNativeLibraryPaths(pkg, appLib32InstallDir);
10370
10371        // We would never need to extract libs for forward-locked and external packages,
10372        // since the container service will do it for us. We shouldn't attempt to
10373        // extract libs from system app when it was not updated.
10374        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10375                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10376            extractLibs = false;
10377        }
10378
10379        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10380        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10381
10382        NativeLibraryHelper.Handle handle = null;
10383        try {
10384            handle = NativeLibraryHelper.Handle.create(pkg);
10385            // TODO(multiArch): This can be null for apps that didn't go through the
10386            // usual installation process. We can calculate it again, like we
10387            // do during install time.
10388            //
10389            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10390            // unnecessary.
10391            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10392
10393            // Null out the abis so that they can be recalculated.
10394            pkg.applicationInfo.primaryCpuAbi = null;
10395            pkg.applicationInfo.secondaryCpuAbi = null;
10396            if (isMultiArch(pkg.applicationInfo)) {
10397                // Warn if we've set an abiOverride for multi-lib packages..
10398                // By definition, we need to copy both 32 and 64 bit libraries for
10399                // such packages.
10400                if (pkg.cpuAbiOverride != null
10401                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10402                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10403                }
10404
10405                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10406                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10407                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10408                    if (extractLibs) {
10409                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10410                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10411                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10412                                useIsaSpecificSubdirs);
10413                    } else {
10414                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10415                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10416                    }
10417                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10418                }
10419
10420                maybeThrowExceptionForMultiArchCopy(
10421                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10422
10423                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10424                    if (extractLibs) {
10425                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10426                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10427                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10428                                useIsaSpecificSubdirs);
10429                    } else {
10430                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10431                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10432                    }
10433                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10434                }
10435
10436                maybeThrowExceptionForMultiArchCopy(
10437                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10438
10439                if (abi64 >= 0) {
10440                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10441                }
10442
10443                if (abi32 >= 0) {
10444                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10445                    if (abi64 >= 0) {
10446                        if (pkg.use32bitAbi) {
10447                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10448                            pkg.applicationInfo.primaryCpuAbi = abi;
10449                        } else {
10450                            pkg.applicationInfo.secondaryCpuAbi = abi;
10451                        }
10452                    } else {
10453                        pkg.applicationInfo.primaryCpuAbi = abi;
10454                    }
10455                }
10456
10457            } else {
10458                String[] abiList = (cpuAbiOverride != null) ?
10459                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10460
10461                // Enable gross and lame hacks for apps that are built with old
10462                // SDK tools. We must scan their APKs for renderscript bitcode and
10463                // not launch them if it's present. Don't bother checking on devices
10464                // that don't have 64 bit support.
10465                boolean needsRenderScriptOverride = false;
10466                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10467                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10468                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10469                    needsRenderScriptOverride = true;
10470                }
10471
10472                final int copyRet;
10473                if (extractLibs) {
10474                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10475                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10476                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10477                } else {
10478                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10479                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10480                }
10481                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10482
10483                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10484                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10485                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10486                }
10487
10488                if (copyRet >= 0) {
10489                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10490                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10491                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10492                } else if (needsRenderScriptOverride) {
10493                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10494                }
10495            }
10496        } catch (IOException ioe) {
10497            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10498        } finally {
10499            IoUtils.closeQuietly(handle);
10500        }
10501
10502        // Now that we've calculated the ABIs and determined if it's an internal app,
10503        // we will go ahead and populate the nativeLibraryPath.
10504        setNativeLibraryPaths(pkg, appLib32InstallDir);
10505    }
10506
10507    /**
10508     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10509     * i.e, so that all packages can be run inside a single process if required.
10510     *
10511     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10512     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10513     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10514     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10515     * updating a package that belongs to a shared user.
10516     *
10517     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10518     * adds unnecessary complexity.
10519     */
10520    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10521            PackageParser.Package scannedPackage) {
10522        String requiredInstructionSet = null;
10523        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10524            requiredInstructionSet = VMRuntime.getInstructionSet(
10525                     scannedPackage.applicationInfo.primaryCpuAbi);
10526        }
10527
10528        PackageSetting requirer = null;
10529        for (PackageSetting ps : packagesForUser) {
10530            // If packagesForUser contains scannedPackage, we skip it. This will happen
10531            // when scannedPackage is an update of an existing package. Without this check,
10532            // we will never be able to change the ABI of any package belonging to a shared
10533            // user, even if it's compatible with other packages.
10534            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10535                if (ps.primaryCpuAbiString == null) {
10536                    continue;
10537                }
10538
10539                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10540                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10541                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10542                    // this but there's not much we can do.
10543                    String errorMessage = "Instruction set mismatch, "
10544                            + ((requirer == null) ? "[caller]" : requirer)
10545                            + " requires " + requiredInstructionSet + " whereas " + ps
10546                            + " requires " + instructionSet;
10547                    Slog.w(TAG, errorMessage);
10548                }
10549
10550                if (requiredInstructionSet == null) {
10551                    requiredInstructionSet = instructionSet;
10552                    requirer = ps;
10553                }
10554            }
10555        }
10556
10557        if (requiredInstructionSet != null) {
10558            String adjustedAbi;
10559            if (requirer != null) {
10560                // requirer != null implies that either scannedPackage was null or that scannedPackage
10561                // did not require an ABI, in which case we have to adjust scannedPackage to match
10562                // the ABI of the set (which is the same as requirer's ABI)
10563                adjustedAbi = requirer.primaryCpuAbiString;
10564                if (scannedPackage != null) {
10565                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10566                }
10567            } else {
10568                // requirer == null implies that we're updating all ABIs in the set to
10569                // match scannedPackage.
10570                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10571            }
10572
10573            for (PackageSetting ps : packagesForUser) {
10574                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10575                    if (ps.primaryCpuAbiString != null) {
10576                        continue;
10577                    }
10578
10579                    ps.primaryCpuAbiString = adjustedAbi;
10580                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10581                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10582                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10583                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10584                                + " (requirer="
10585                                + (requirer == null ? "null" : requirer.pkg.packageName)
10586                                + ", scannedPackage="
10587                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10588                                + ")");
10589                        try {
10590                            mInstaller.rmdex(ps.codePathString,
10591                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10592                        } catch (InstallerException ignored) {
10593                        }
10594                    }
10595                }
10596            }
10597        }
10598    }
10599
10600    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10601        synchronized (mPackages) {
10602            mResolverReplaced = true;
10603            // Set up information for custom user intent resolution activity.
10604            mResolveActivity.applicationInfo = pkg.applicationInfo;
10605            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10606            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10607            mResolveActivity.processName = pkg.applicationInfo.packageName;
10608            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10609            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10610                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10611            mResolveActivity.theme = 0;
10612            mResolveActivity.exported = true;
10613            mResolveActivity.enabled = true;
10614            mResolveInfo.activityInfo = mResolveActivity;
10615            mResolveInfo.priority = 0;
10616            mResolveInfo.preferredOrder = 0;
10617            mResolveInfo.match = 0;
10618            mResolveComponentName = mCustomResolverComponentName;
10619            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10620                    mResolveComponentName);
10621        }
10622    }
10623
10624    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10625        if (installerComponent == null) {
10626            if (DEBUG_EPHEMERAL) {
10627                Slog.d(TAG, "Clear ephemeral installer activity");
10628            }
10629            mEphemeralInstallerActivity.applicationInfo = null;
10630            return;
10631        }
10632
10633        if (DEBUG_EPHEMERAL) {
10634            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10635        }
10636        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10637        // Set up information for ephemeral installer activity
10638        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10639        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10640        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10641        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10642        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10643        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10644                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10645        mEphemeralInstallerActivity.theme = 0;
10646        mEphemeralInstallerActivity.exported = true;
10647        mEphemeralInstallerActivity.enabled = true;
10648        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10649        mEphemeralInstallerInfo.priority = 0;
10650        mEphemeralInstallerInfo.preferredOrder = 1;
10651        mEphemeralInstallerInfo.isDefault = true;
10652        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10653                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10654    }
10655
10656    private static String calculateBundledApkRoot(final String codePathString) {
10657        final File codePath = new File(codePathString);
10658        final File codeRoot;
10659        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10660            codeRoot = Environment.getRootDirectory();
10661        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10662            codeRoot = Environment.getOemDirectory();
10663        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10664            codeRoot = Environment.getVendorDirectory();
10665        } else {
10666            // Unrecognized code path; take its top real segment as the apk root:
10667            // e.g. /something/app/blah.apk => /something
10668            try {
10669                File f = codePath.getCanonicalFile();
10670                File parent = f.getParentFile();    // non-null because codePath is a file
10671                File tmp;
10672                while ((tmp = parent.getParentFile()) != null) {
10673                    f = parent;
10674                    parent = tmp;
10675                }
10676                codeRoot = f;
10677                Slog.w(TAG, "Unrecognized code path "
10678                        + codePath + " - using " + codeRoot);
10679            } catch (IOException e) {
10680                // Can't canonicalize the code path -- shenanigans?
10681                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10682                return Environment.getRootDirectory().getPath();
10683            }
10684        }
10685        return codeRoot.getPath();
10686    }
10687
10688    /**
10689     * Derive and set the location of native libraries for the given package,
10690     * which varies depending on where and how the package was installed.
10691     */
10692    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10693        final ApplicationInfo info = pkg.applicationInfo;
10694        final String codePath = pkg.codePath;
10695        final File codeFile = new File(codePath);
10696        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10697        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10698
10699        info.nativeLibraryRootDir = null;
10700        info.nativeLibraryRootRequiresIsa = false;
10701        info.nativeLibraryDir = null;
10702        info.secondaryNativeLibraryDir = null;
10703
10704        if (isApkFile(codeFile)) {
10705            // Monolithic install
10706            if (bundledApp) {
10707                // If "/system/lib64/apkname" exists, assume that is the per-package
10708                // native library directory to use; otherwise use "/system/lib/apkname".
10709                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10710                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10711                        getPrimaryInstructionSet(info));
10712
10713                // This is a bundled system app so choose the path based on the ABI.
10714                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10715                // is just the default path.
10716                final String apkName = deriveCodePathName(codePath);
10717                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10718                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10719                        apkName).getAbsolutePath();
10720
10721                if (info.secondaryCpuAbi != null) {
10722                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10723                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10724                            secondaryLibDir, apkName).getAbsolutePath();
10725                }
10726            } else if (asecApp) {
10727                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10728                        .getAbsolutePath();
10729            } else {
10730                final String apkName = deriveCodePathName(codePath);
10731                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10732                        .getAbsolutePath();
10733            }
10734
10735            info.nativeLibraryRootRequiresIsa = false;
10736            info.nativeLibraryDir = info.nativeLibraryRootDir;
10737        } else {
10738            // Cluster install
10739            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10740            info.nativeLibraryRootRequiresIsa = true;
10741
10742            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10743                    getPrimaryInstructionSet(info)).getAbsolutePath();
10744
10745            if (info.secondaryCpuAbi != null) {
10746                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10747                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10748            }
10749        }
10750    }
10751
10752    /**
10753     * Calculate the abis and roots for a bundled app. These can uniquely
10754     * be determined from the contents of the system partition, i.e whether
10755     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10756     * of this information, and instead assume that the system was built
10757     * sensibly.
10758     */
10759    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10760                                           PackageSetting pkgSetting) {
10761        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10762
10763        // If "/system/lib64/apkname" exists, assume that is the per-package
10764        // native library directory to use; otherwise use "/system/lib/apkname".
10765        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10766        setBundledAppAbi(pkg, apkRoot, apkName);
10767        // pkgSetting might be null during rescan following uninstall of updates
10768        // to a bundled app, so accommodate that possibility.  The settings in
10769        // that case will be established later from the parsed package.
10770        //
10771        // If the settings aren't null, sync them up with what we've just derived.
10772        // note that apkRoot isn't stored in the package settings.
10773        if (pkgSetting != null) {
10774            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10775            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10776        }
10777    }
10778
10779    /**
10780     * Deduces the ABI of a bundled app and sets the relevant fields on the
10781     * parsed pkg object.
10782     *
10783     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10784     *        under which system libraries are installed.
10785     * @param apkName the name of the installed package.
10786     */
10787    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10788        final File codeFile = new File(pkg.codePath);
10789
10790        final boolean has64BitLibs;
10791        final boolean has32BitLibs;
10792        if (isApkFile(codeFile)) {
10793            // Monolithic install
10794            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10795            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10796        } else {
10797            // Cluster install
10798            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10799            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10800                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10801                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10802                has64BitLibs = (new File(rootDir, isa)).exists();
10803            } else {
10804                has64BitLibs = false;
10805            }
10806            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10807                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10808                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10809                has32BitLibs = (new File(rootDir, isa)).exists();
10810            } else {
10811                has32BitLibs = false;
10812            }
10813        }
10814
10815        if (has64BitLibs && !has32BitLibs) {
10816            // The package has 64 bit libs, but not 32 bit libs. Its primary
10817            // ABI should be 64 bit. We can safely assume here that the bundled
10818            // native libraries correspond to the most preferred ABI in the list.
10819
10820            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10821            pkg.applicationInfo.secondaryCpuAbi = null;
10822        } else if (has32BitLibs && !has64BitLibs) {
10823            // The package has 32 bit libs but not 64 bit libs. Its primary
10824            // ABI should be 32 bit.
10825
10826            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10827            pkg.applicationInfo.secondaryCpuAbi = null;
10828        } else if (has32BitLibs && has64BitLibs) {
10829            // The application has both 64 and 32 bit bundled libraries. We check
10830            // here that the app declares multiArch support, and warn if it doesn't.
10831            //
10832            // We will be lenient here and record both ABIs. The primary will be the
10833            // ABI that's higher on the list, i.e, a device that's configured to prefer
10834            // 64 bit apps will see a 64 bit primary ABI,
10835
10836            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10837                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10838            }
10839
10840            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10841                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10842                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10843            } else {
10844                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10845                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10846            }
10847        } else {
10848            pkg.applicationInfo.primaryCpuAbi = null;
10849            pkg.applicationInfo.secondaryCpuAbi = null;
10850        }
10851    }
10852
10853    private void killApplication(String pkgName, int appId, String reason) {
10854        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10855    }
10856
10857    private void killApplication(String pkgName, int appId, int userId, String reason) {
10858        // Request the ActivityManager to kill the process(only for existing packages)
10859        // so that we do not end up in a confused state while the user is still using the older
10860        // version of the application while the new one gets installed.
10861        final long token = Binder.clearCallingIdentity();
10862        try {
10863            IActivityManager am = ActivityManager.getService();
10864            if (am != null) {
10865                try {
10866                    am.killApplication(pkgName, appId, userId, reason);
10867                } catch (RemoteException e) {
10868                }
10869            }
10870        } finally {
10871            Binder.restoreCallingIdentity(token);
10872        }
10873    }
10874
10875    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10876        // Remove the parent package setting
10877        PackageSetting ps = (PackageSetting) pkg.mExtras;
10878        if (ps != null) {
10879            removePackageLI(ps, chatty);
10880        }
10881        // Remove the child package setting
10882        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10883        for (int i = 0; i < childCount; i++) {
10884            PackageParser.Package childPkg = pkg.childPackages.get(i);
10885            ps = (PackageSetting) childPkg.mExtras;
10886            if (ps != null) {
10887                removePackageLI(ps, chatty);
10888            }
10889        }
10890    }
10891
10892    void removePackageLI(PackageSetting ps, boolean chatty) {
10893        if (DEBUG_INSTALL) {
10894            if (chatty)
10895                Log.d(TAG, "Removing package " + ps.name);
10896        }
10897
10898        // writer
10899        synchronized (mPackages) {
10900            mPackages.remove(ps.name);
10901            final PackageParser.Package pkg = ps.pkg;
10902            if (pkg != null) {
10903                cleanPackageDataStructuresLILPw(pkg, chatty);
10904            }
10905        }
10906    }
10907
10908    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10909        if (DEBUG_INSTALL) {
10910            if (chatty)
10911                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10912        }
10913
10914        // writer
10915        synchronized (mPackages) {
10916            // Remove the parent package
10917            mPackages.remove(pkg.applicationInfo.packageName);
10918            cleanPackageDataStructuresLILPw(pkg, chatty);
10919
10920            // Remove the child packages
10921            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10922            for (int i = 0; i < childCount; i++) {
10923                PackageParser.Package childPkg = pkg.childPackages.get(i);
10924                mPackages.remove(childPkg.applicationInfo.packageName);
10925                cleanPackageDataStructuresLILPw(childPkg, chatty);
10926            }
10927        }
10928    }
10929
10930    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10931        int N = pkg.providers.size();
10932        StringBuilder r = null;
10933        int i;
10934        for (i=0; i<N; i++) {
10935            PackageParser.Provider p = pkg.providers.get(i);
10936            mProviders.removeProvider(p);
10937            if (p.info.authority == null) {
10938
10939                /* There was another ContentProvider with this authority when
10940                 * this app was installed so this authority is null,
10941                 * Ignore it as we don't have to unregister the provider.
10942                 */
10943                continue;
10944            }
10945            String names[] = p.info.authority.split(";");
10946            for (int j = 0; j < names.length; j++) {
10947                if (mProvidersByAuthority.get(names[j]) == p) {
10948                    mProvidersByAuthority.remove(names[j]);
10949                    if (DEBUG_REMOVE) {
10950                        if (chatty)
10951                            Log.d(TAG, "Unregistered content provider: " + names[j]
10952                                    + ", className = " + p.info.name + ", isSyncable = "
10953                                    + p.info.isSyncable);
10954                    }
10955                }
10956            }
10957            if (DEBUG_REMOVE && chatty) {
10958                if (r == null) {
10959                    r = new StringBuilder(256);
10960                } else {
10961                    r.append(' ');
10962                }
10963                r.append(p.info.name);
10964            }
10965        }
10966        if (r != null) {
10967            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10968        }
10969
10970        N = pkg.services.size();
10971        r = null;
10972        for (i=0; i<N; i++) {
10973            PackageParser.Service s = pkg.services.get(i);
10974            mServices.removeService(s);
10975            if (chatty) {
10976                if (r == null) {
10977                    r = new StringBuilder(256);
10978                } else {
10979                    r.append(' ');
10980                }
10981                r.append(s.info.name);
10982            }
10983        }
10984        if (r != null) {
10985            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10986        }
10987
10988        N = pkg.receivers.size();
10989        r = null;
10990        for (i=0; i<N; i++) {
10991            PackageParser.Activity a = pkg.receivers.get(i);
10992            mReceivers.removeActivity(a, "receiver");
10993            if (DEBUG_REMOVE && chatty) {
10994                if (r == null) {
10995                    r = new StringBuilder(256);
10996                } else {
10997                    r.append(' ');
10998                }
10999                r.append(a.info.name);
11000            }
11001        }
11002        if (r != null) {
11003            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11004        }
11005
11006        N = pkg.activities.size();
11007        r = null;
11008        for (i=0; i<N; i++) {
11009            PackageParser.Activity a = pkg.activities.get(i);
11010            mActivities.removeActivity(a, "activity");
11011            if (DEBUG_REMOVE && chatty) {
11012                if (r == null) {
11013                    r = new StringBuilder(256);
11014                } else {
11015                    r.append(' ');
11016                }
11017                r.append(a.info.name);
11018            }
11019        }
11020        if (r != null) {
11021            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11022        }
11023
11024        N = pkg.permissions.size();
11025        r = null;
11026        for (i=0; i<N; i++) {
11027            PackageParser.Permission p = pkg.permissions.get(i);
11028            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11029            if (bp == null) {
11030                bp = mSettings.mPermissionTrees.get(p.info.name);
11031            }
11032            if (bp != null && bp.perm == p) {
11033                bp.perm = null;
11034                if (DEBUG_REMOVE && chatty) {
11035                    if (r == null) {
11036                        r = new StringBuilder(256);
11037                    } else {
11038                        r.append(' ');
11039                    }
11040                    r.append(p.info.name);
11041                }
11042            }
11043            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11044                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11045                if (appOpPkgs != null) {
11046                    appOpPkgs.remove(pkg.packageName);
11047                }
11048            }
11049        }
11050        if (r != null) {
11051            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11052        }
11053
11054        N = pkg.requestedPermissions.size();
11055        r = null;
11056        for (i=0; i<N; i++) {
11057            String perm = pkg.requestedPermissions.get(i);
11058            BasePermission bp = mSettings.mPermissions.get(perm);
11059            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11060                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11061                if (appOpPkgs != null) {
11062                    appOpPkgs.remove(pkg.packageName);
11063                    if (appOpPkgs.isEmpty()) {
11064                        mAppOpPermissionPackages.remove(perm);
11065                    }
11066                }
11067            }
11068        }
11069        if (r != null) {
11070            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11071        }
11072
11073        N = pkg.instrumentation.size();
11074        r = null;
11075        for (i=0; i<N; i++) {
11076            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11077            mInstrumentation.remove(a.getComponentName());
11078            if (DEBUG_REMOVE && chatty) {
11079                if (r == null) {
11080                    r = new StringBuilder(256);
11081                } else {
11082                    r.append(' ');
11083                }
11084                r.append(a.info.name);
11085            }
11086        }
11087        if (r != null) {
11088            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11089        }
11090
11091        r = null;
11092        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11093            // Only system apps can hold shared libraries.
11094            if (pkg.libraryNames != null) {
11095                for (i = 0; i < pkg.libraryNames.size(); i++) {
11096                    String name = pkg.libraryNames.get(i);
11097                    if (removeSharedLibraryLPw(name, 0)) {
11098                        if (DEBUG_REMOVE && chatty) {
11099                            if (r == null) {
11100                                r = new StringBuilder(256);
11101                            } else {
11102                                r.append(' ');
11103                            }
11104                            r.append(name);
11105                        }
11106                    }
11107                }
11108            }
11109        }
11110
11111        r = null;
11112
11113        // Any package can hold static shared libraries.
11114        if (pkg.staticSharedLibName != null) {
11115            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11116                if (DEBUG_REMOVE && chatty) {
11117                    if (r == null) {
11118                        r = new StringBuilder(256);
11119                    } else {
11120                        r.append(' ');
11121                    }
11122                    r.append(pkg.staticSharedLibName);
11123                }
11124            }
11125        }
11126
11127        if (r != null) {
11128            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11129        }
11130    }
11131
11132    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11133        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11134            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11135                return true;
11136            }
11137        }
11138        return false;
11139    }
11140
11141    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11142    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11143    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11144
11145    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11146        // Update the parent permissions
11147        updatePermissionsLPw(pkg.packageName, pkg, flags);
11148        // Update the child permissions
11149        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11150        for (int i = 0; i < childCount; i++) {
11151            PackageParser.Package childPkg = pkg.childPackages.get(i);
11152            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11153        }
11154    }
11155
11156    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11157            int flags) {
11158        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11159        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11160    }
11161
11162    private void updatePermissionsLPw(String changingPkg,
11163            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11164        // Make sure there are no dangling permission trees.
11165        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11166        while (it.hasNext()) {
11167            final BasePermission bp = it.next();
11168            if (bp.packageSetting == null) {
11169                // We may not yet have parsed the package, so just see if
11170                // we still know about its settings.
11171                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11172            }
11173            if (bp.packageSetting == null) {
11174                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11175                        + " from package " + bp.sourcePackage);
11176                it.remove();
11177            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11178                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11179                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11180                            + " from package " + bp.sourcePackage);
11181                    flags |= UPDATE_PERMISSIONS_ALL;
11182                    it.remove();
11183                }
11184            }
11185        }
11186
11187        // Make sure all dynamic permissions have been assigned to a package,
11188        // and make sure there are no dangling permissions.
11189        it = mSettings.mPermissions.values().iterator();
11190        while (it.hasNext()) {
11191            final BasePermission bp = it.next();
11192            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11193                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11194                        + bp.name + " pkg=" + bp.sourcePackage
11195                        + " info=" + bp.pendingInfo);
11196                if (bp.packageSetting == null && bp.pendingInfo != null) {
11197                    final BasePermission tree = findPermissionTreeLP(bp.name);
11198                    if (tree != null && tree.perm != null) {
11199                        bp.packageSetting = tree.packageSetting;
11200                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11201                                new PermissionInfo(bp.pendingInfo));
11202                        bp.perm.info.packageName = tree.perm.info.packageName;
11203                        bp.perm.info.name = bp.name;
11204                        bp.uid = tree.uid;
11205                    }
11206                }
11207            }
11208            if (bp.packageSetting == null) {
11209                // We may not yet have parsed the package, so just see if
11210                // we still know about its settings.
11211                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11212            }
11213            if (bp.packageSetting == null) {
11214                Slog.w(TAG, "Removing dangling permission: " + bp.name
11215                        + " from package " + bp.sourcePackage);
11216                it.remove();
11217            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11218                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11219                    Slog.i(TAG, "Removing old permission: " + bp.name
11220                            + " from package " + bp.sourcePackage);
11221                    flags |= UPDATE_PERMISSIONS_ALL;
11222                    it.remove();
11223                }
11224            }
11225        }
11226
11227        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11228        // Now update the permissions for all packages, in particular
11229        // replace the granted permissions of the system packages.
11230        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11231            for (PackageParser.Package pkg : mPackages.values()) {
11232                if (pkg != pkgInfo) {
11233                    // Only replace for packages on requested volume
11234                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11235                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11236                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11237                    grantPermissionsLPw(pkg, replace, changingPkg);
11238                }
11239            }
11240        }
11241
11242        if (pkgInfo != null) {
11243            // Only replace for packages on requested volume
11244            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11245            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11246                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11247            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11248        }
11249        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11250    }
11251
11252    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11253            String packageOfInterest) {
11254        // IMPORTANT: There are two types of permissions: install and runtime.
11255        // Install time permissions are granted when the app is installed to
11256        // all device users and users added in the future. Runtime permissions
11257        // are granted at runtime explicitly to specific users. Normal and signature
11258        // protected permissions are install time permissions. Dangerous permissions
11259        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11260        // otherwise they are runtime permissions. This function does not manage
11261        // runtime permissions except for the case an app targeting Lollipop MR1
11262        // being upgraded to target a newer SDK, in which case dangerous permissions
11263        // are transformed from install time to runtime ones.
11264
11265        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11266        if (ps == null) {
11267            return;
11268        }
11269
11270        PermissionsState permissionsState = ps.getPermissionsState();
11271        PermissionsState origPermissions = permissionsState;
11272
11273        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11274
11275        boolean runtimePermissionsRevoked = false;
11276        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11277
11278        boolean changedInstallPermission = false;
11279
11280        if (replace) {
11281            ps.installPermissionsFixed = false;
11282            if (!ps.isSharedUser()) {
11283                origPermissions = new PermissionsState(permissionsState);
11284                permissionsState.reset();
11285            } else {
11286                // We need to know only about runtime permission changes since the
11287                // calling code always writes the install permissions state but
11288                // the runtime ones are written only if changed. The only cases of
11289                // changed runtime permissions here are promotion of an install to
11290                // runtime and revocation of a runtime from a shared user.
11291                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11292                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11293                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11294                    runtimePermissionsRevoked = true;
11295                }
11296            }
11297        }
11298
11299        permissionsState.setGlobalGids(mGlobalGids);
11300
11301        final int N = pkg.requestedPermissions.size();
11302        for (int i=0; i<N; i++) {
11303            final String name = pkg.requestedPermissions.get(i);
11304            final BasePermission bp = mSettings.mPermissions.get(name);
11305
11306            if (DEBUG_INSTALL) {
11307                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11308            }
11309
11310            if (bp == null || bp.packageSetting == null) {
11311                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11312                    Slog.w(TAG, "Unknown permission " + name
11313                            + " in package " + pkg.packageName);
11314                }
11315                continue;
11316            }
11317
11318
11319            // Limit ephemeral apps to ephemeral allowed permissions.
11320            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11321                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11322                        + pkg.packageName);
11323                continue;
11324            }
11325
11326            final String perm = bp.name;
11327            boolean allowedSig = false;
11328            int grant = GRANT_DENIED;
11329
11330            // Keep track of app op permissions.
11331            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11332                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11333                if (pkgs == null) {
11334                    pkgs = new ArraySet<>();
11335                    mAppOpPermissionPackages.put(bp.name, pkgs);
11336                }
11337                pkgs.add(pkg.packageName);
11338            }
11339
11340            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11341            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11342                    >= Build.VERSION_CODES.M;
11343            switch (level) {
11344                case PermissionInfo.PROTECTION_NORMAL: {
11345                    // For all apps normal permissions are install time ones.
11346                    grant = GRANT_INSTALL;
11347                } break;
11348
11349                case PermissionInfo.PROTECTION_DANGEROUS: {
11350                    // If a permission review is required for legacy apps we represent
11351                    // their permissions as always granted runtime ones since we need
11352                    // to keep the review required permission flag per user while an
11353                    // install permission's state is shared across all users.
11354                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11355                        // For legacy apps dangerous permissions are install time ones.
11356                        grant = GRANT_INSTALL;
11357                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11358                        // For legacy apps that became modern, install becomes runtime.
11359                        grant = GRANT_UPGRADE;
11360                    } else if (mPromoteSystemApps
11361                            && isSystemApp(ps)
11362                            && mExistingSystemPackages.contains(ps.name)) {
11363                        // For legacy system apps, install becomes runtime.
11364                        // We cannot check hasInstallPermission() for system apps since those
11365                        // permissions were granted implicitly and not persisted pre-M.
11366                        grant = GRANT_UPGRADE;
11367                    } else {
11368                        // For modern apps keep runtime permissions unchanged.
11369                        grant = GRANT_RUNTIME;
11370                    }
11371                } break;
11372
11373                case PermissionInfo.PROTECTION_SIGNATURE: {
11374                    // For all apps signature permissions are install time ones.
11375                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11376                    if (allowedSig) {
11377                        grant = GRANT_INSTALL;
11378                    }
11379                } break;
11380            }
11381
11382            if (DEBUG_INSTALL) {
11383                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11384            }
11385
11386            if (grant != GRANT_DENIED) {
11387                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11388                    // If this is an existing, non-system package, then
11389                    // we can't add any new permissions to it.
11390                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11391                        // Except...  if this is a permission that was added
11392                        // to the platform (note: need to only do this when
11393                        // updating the platform).
11394                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11395                            grant = GRANT_DENIED;
11396                        }
11397                    }
11398                }
11399
11400                switch (grant) {
11401                    case GRANT_INSTALL: {
11402                        // Revoke this as runtime permission to handle the case of
11403                        // a runtime permission being downgraded to an install one.
11404                        // Also in permission review mode we keep dangerous permissions
11405                        // for legacy apps
11406                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11407                            if (origPermissions.getRuntimePermissionState(
11408                                    bp.name, userId) != null) {
11409                                // Revoke the runtime permission and clear the flags.
11410                                origPermissions.revokeRuntimePermission(bp, userId);
11411                                origPermissions.updatePermissionFlags(bp, userId,
11412                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11413                                // If we revoked a permission permission, we have to write.
11414                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11415                                        changedRuntimePermissionUserIds, userId);
11416                            }
11417                        }
11418                        // Grant an install permission.
11419                        if (permissionsState.grantInstallPermission(bp) !=
11420                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11421                            changedInstallPermission = true;
11422                        }
11423                    } break;
11424
11425                    case GRANT_RUNTIME: {
11426                        // Grant previously granted runtime permissions.
11427                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11428                            PermissionState permissionState = origPermissions
11429                                    .getRuntimePermissionState(bp.name, userId);
11430                            int flags = permissionState != null
11431                                    ? permissionState.getFlags() : 0;
11432                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11433                                // Don't propagate the permission in a permission review mode if
11434                                // the former was revoked, i.e. marked to not propagate on upgrade.
11435                                // Note that in a permission review mode install permissions are
11436                                // represented as constantly granted runtime ones since we need to
11437                                // keep a per user state associated with the permission. Also the
11438                                // revoke on upgrade flag is no longer applicable and is reset.
11439                                final boolean revokeOnUpgrade = (flags & PackageManager
11440                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11441                                if (revokeOnUpgrade) {
11442                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11443                                    // Since we changed the flags, we have to write.
11444                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11445                                            changedRuntimePermissionUserIds, userId);
11446                                }
11447                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11448                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11449                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11450                                        // If we cannot put the permission as it was,
11451                                        // we have to write.
11452                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11453                                                changedRuntimePermissionUserIds, userId);
11454                                    }
11455                                }
11456
11457                                // If the app supports runtime permissions no need for a review.
11458                                if (mPermissionReviewRequired
11459                                        && appSupportsRuntimePermissions
11460                                        && (flags & PackageManager
11461                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11462                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11463                                    // Since we changed the flags, we have to write.
11464                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11465                                            changedRuntimePermissionUserIds, userId);
11466                                }
11467                            } else if (mPermissionReviewRequired
11468                                    && !appSupportsRuntimePermissions) {
11469                                // For legacy apps that need a permission review, every new
11470                                // runtime permission is granted but it is pending a review.
11471                                // We also need to review only platform defined runtime
11472                                // permissions as these are the only ones the platform knows
11473                                // how to disable the API to simulate revocation as legacy
11474                                // apps don't expect to run with revoked permissions.
11475                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11476                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11477                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11478                                        // We changed the flags, hence have to write.
11479                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11480                                                changedRuntimePermissionUserIds, userId);
11481                                    }
11482                                }
11483                                if (permissionsState.grantRuntimePermission(bp, userId)
11484                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11485                                    // We changed the permission, hence have to write.
11486                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11487                                            changedRuntimePermissionUserIds, userId);
11488                                }
11489                            }
11490                            // Propagate the permission flags.
11491                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11492                        }
11493                    } break;
11494
11495                    case GRANT_UPGRADE: {
11496                        // Grant runtime permissions for a previously held install permission.
11497                        PermissionState permissionState = origPermissions
11498                                .getInstallPermissionState(bp.name);
11499                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11500
11501                        if (origPermissions.revokeInstallPermission(bp)
11502                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11503                            // We will be transferring the permission flags, so clear them.
11504                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11505                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11506                            changedInstallPermission = true;
11507                        }
11508
11509                        // If the permission is not to be promoted to runtime we ignore it and
11510                        // also its other flags as they are not applicable to install permissions.
11511                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11512                            for (int userId : currentUserIds) {
11513                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11514                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11515                                    // Transfer the permission flags.
11516                                    permissionsState.updatePermissionFlags(bp, userId,
11517                                            flags, flags);
11518                                    // If we granted the permission, we have to write.
11519                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11520                                            changedRuntimePermissionUserIds, userId);
11521                                }
11522                            }
11523                        }
11524                    } break;
11525
11526                    default: {
11527                        if (packageOfInterest == null
11528                                || packageOfInterest.equals(pkg.packageName)) {
11529                            Slog.w(TAG, "Not granting permission " + perm
11530                                    + " to package " + pkg.packageName
11531                                    + " because it was previously installed without");
11532                        }
11533                    } break;
11534                }
11535            } else {
11536                if (permissionsState.revokeInstallPermission(bp) !=
11537                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11538                    // Also drop the permission flags.
11539                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11540                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11541                    changedInstallPermission = true;
11542                    Slog.i(TAG, "Un-granting permission " + perm
11543                            + " from package " + pkg.packageName
11544                            + " (protectionLevel=" + bp.protectionLevel
11545                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11546                            + ")");
11547                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11548                    // Don't print warning for app op permissions, since it is fine for them
11549                    // not to be granted, there is a UI for the user to decide.
11550                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11551                        Slog.w(TAG, "Not granting permission " + perm
11552                                + " to package " + pkg.packageName
11553                                + " (protectionLevel=" + bp.protectionLevel
11554                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11555                                + ")");
11556                    }
11557                }
11558            }
11559        }
11560
11561        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11562                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11563            // This is the first that we have heard about this package, so the
11564            // permissions we have now selected are fixed until explicitly
11565            // changed.
11566            ps.installPermissionsFixed = true;
11567        }
11568
11569        // Persist the runtime permissions state for users with changes. If permissions
11570        // were revoked because no app in the shared user declares them we have to
11571        // write synchronously to avoid losing runtime permissions state.
11572        for (int userId : changedRuntimePermissionUserIds) {
11573            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11574        }
11575    }
11576
11577    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11578        boolean allowed = false;
11579        final int NP = PackageParser.NEW_PERMISSIONS.length;
11580        for (int ip=0; ip<NP; ip++) {
11581            final PackageParser.NewPermissionInfo npi
11582                    = PackageParser.NEW_PERMISSIONS[ip];
11583            if (npi.name.equals(perm)
11584                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11585                allowed = true;
11586                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11587                        + pkg.packageName);
11588                break;
11589            }
11590        }
11591        return allowed;
11592    }
11593
11594    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11595            BasePermission bp, PermissionsState origPermissions) {
11596        boolean privilegedPermission = (bp.protectionLevel
11597                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11598        boolean privappPermissionsDisable =
11599                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11600        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11601        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11602        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11603                && !platformPackage && platformPermission) {
11604            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11605                    .getPrivAppPermissions(pkg.packageName);
11606            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11607            if (!whitelisted) {
11608                Slog.w(TAG, "Privileged permission " + perm + " for package "
11609                        + pkg.packageName + " - not in privapp-permissions whitelist");
11610                if (!mSystemReady) {
11611                    if (mPrivappPermissionsViolations == null) {
11612                        mPrivappPermissionsViolations = new ArraySet<>();
11613                    }
11614                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11615                }
11616                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11617                    return false;
11618                }
11619            }
11620        }
11621        boolean allowed = (compareSignatures(
11622                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11623                        == PackageManager.SIGNATURE_MATCH)
11624                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11625                        == PackageManager.SIGNATURE_MATCH);
11626        if (!allowed && privilegedPermission) {
11627            if (isSystemApp(pkg)) {
11628                // For updated system applications, a system permission
11629                // is granted only if it had been defined by the original application.
11630                if (pkg.isUpdatedSystemApp()) {
11631                    final PackageSetting sysPs = mSettings
11632                            .getDisabledSystemPkgLPr(pkg.packageName);
11633                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11634                        // If the original was granted this permission, we take
11635                        // that grant decision as read and propagate it to the
11636                        // update.
11637                        if (sysPs.isPrivileged()) {
11638                            allowed = true;
11639                        }
11640                    } else {
11641                        // The system apk may have been updated with an older
11642                        // version of the one on the data partition, but which
11643                        // granted a new system permission that it didn't have
11644                        // before.  In this case we do want to allow the app to
11645                        // now get the new permission if the ancestral apk is
11646                        // privileged to get it.
11647                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11648                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11649                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11650                                    allowed = true;
11651                                    break;
11652                                }
11653                            }
11654                        }
11655                        // Also if a privileged parent package on the system image or any of
11656                        // its children requested a privileged permission, the updated child
11657                        // packages can also get the permission.
11658                        if (pkg.parentPackage != null) {
11659                            final PackageSetting disabledSysParentPs = mSettings
11660                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11661                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11662                                    && disabledSysParentPs.isPrivileged()) {
11663                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11664                                    allowed = true;
11665                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11666                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11667                                    for (int i = 0; i < count; i++) {
11668                                        PackageParser.Package disabledSysChildPkg =
11669                                                disabledSysParentPs.pkg.childPackages.get(i);
11670                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11671                                                perm)) {
11672                                            allowed = true;
11673                                            break;
11674                                        }
11675                                    }
11676                                }
11677                            }
11678                        }
11679                    }
11680                } else {
11681                    allowed = isPrivilegedApp(pkg);
11682                }
11683            }
11684        }
11685        if (!allowed) {
11686            if (!allowed && (bp.protectionLevel
11687                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11688                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11689                // If this was a previously normal/dangerous permission that got moved
11690                // to a system permission as part of the runtime permission redesign, then
11691                // we still want to blindly grant it to old apps.
11692                allowed = true;
11693            }
11694            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11695                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11696                // If this permission is to be granted to the system installer and
11697                // this app is an installer, then it gets the permission.
11698                allowed = true;
11699            }
11700            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11701                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11702                // If this permission is to be granted to the system verifier and
11703                // this app is a verifier, then it gets the permission.
11704                allowed = true;
11705            }
11706            if (!allowed && (bp.protectionLevel
11707                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11708                    && isSystemApp(pkg)) {
11709                // Any pre-installed system app is allowed to get this permission.
11710                allowed = true;
11711            }
11712            if (!allowed && (bp.protectionLevel
11713                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11714                // For development permissions, a development permission
11715                // is granted only if it was already granted.
11716                allowed = origPermissions.hasInstallPermission(perm);
11717            }
11718            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11719                    && pkg.packageName.equals(mSetupWizardPackage)) {
11720                // If this permission is to be granted to the system setup wizard and
11721                // this app is a setup wizard, then it gets the permission.
11722                allowed = true;
11723            }
11724        }
11725        return allowed;
11726    }
11727
11728    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11729        final int permCount = pkg.requestedPermissions.size();
11730        for (int j = 0; j < permCount; j++) {
11731            String requestedPermission = pkg.requestedPermissions.get(j);
11732            if (permission.equals(requestedPermission)) {
11733                return true;
11734            }
11735        }
11736        return false;
11737    }
11738
11739    final class ActivityIntentResolver
11740            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11741        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11742                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11743            if (!sUserManager.exists(userId)) return null;
11744            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11745                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11746                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11747            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11748                    isEphemeral, userId);
11749        }
11750
11751        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11752                int userId) {
11753            if (!sUserManager.exists(userId)) return null;
11754            mFlags = flags;
11755            return super.queryIntent(intent, resolvedType,
11756                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11757                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11758                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11759        }
11760
11761        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11762                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11763            if (!sUserManager.exists(userId)) return null;
11764            if (packageActivities == null) {
11765                return null;
11766            }
11767            mFlags = flags;
11768            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11769            final boolean vislbleToEphemeral =
11770                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11771            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11772            final int N = packageActivities.size();
11773            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11774                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11775
11776            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11777            for (int i = 0; i < N; ++i) {
11778                intentFilters = packageActivities.get(i).intents;
11779                if (intentFilters != null && intentFilters.size() > 0) {
11780                    PackageParser.ActivityIntentInfo[] array =
11781                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11782                    intentFilters.toArray(array);
11783                    listCut.add(array);
11784                }
11785            }
11786            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11787                    vislbleToEphemeral, isEphemeral, listCut, userId);
11788        }
11789
11790        /**
11791         * Finds a privileged activity that matches the specified activity names.
11792         */
11793        private PackageParser.Activity findMatchingActivity(
11794                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11795            for (PackageParser.Activity sysActivity : activityList) {
11796                if (sysActivity.info.name.equals(activityInfo.name)) {
11797                    return sysActivity;
11798                }
11799                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11800                    return sysActivity;
11801                }
11802                if (sysActivity.info.targetActivity != null) {
11803                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11804                        return sysActivity;
11805                    }
11806                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11807                        return sysActivity;
11808                    }
11809                }
11810            }
11811            return null;
11812        }
11813
11814        public class IterGenerator<E> {
11815            public Iterator<E> generate(ActivityIntentInfo info) {
11816                return null;
11817            }
11818        }
11819
11820        public class ActionIterGenerator extends IterGenerator<String> {
11821            @Override
11822            public Iterator<String> generate(ActivityIntentInfo info) {
11823                return info.actionsIterator();
11824            }
11825        }
11826
11827        public class CategoriesIterGenerator extends IterGenerator<String> {
11828            @Override
11829            public Iterator<String> generate(ActivityIntentInfo info) {
11830                return info.categoriesIterator();
11831            }
11832        }
11833
11834        public class SchemesIterGenerator extends IterGenerator<String> {
11835            @Override
11836            public Iterator<String> generate(ActivityIntentInfo info) {
11837                return info.schemesIterator();
11838            }
11839        }
11840
11841        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11842            @Override
11843            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11844                return info.authoritiesIterator();
11845            }
11846        }
11847
11848        /**
11849         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11850         * MODIFIED. Do not pass in a list that should not be changed.
11851         */
11852        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11853                IterGenerator<T> generator, Iterator<T> searchIterator) {
11854            // loop through the set of actions; every one must be found in the intent filter
11855            while (searchIterator.hasNext()) {
11856                // we must have at least one filter in the list to consider a match
11857                if (intentList.size() == 0) {
11858                    break;
11859                }
11860
11861                final T searchAction = searchIterator.next();
11862
11863                // loop through the set of intent filters
11864                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11865                while (intentIter.hasNext()) {
11866                    final ActivityIntentInfo intentInfo = intentIter.next();
11867                    boolean selectionFound = false;
11868
11869                    // loop through the intent filter's selection criteria; at least one
11870                    // of them must match the searched criteria
11871                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11872                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11873                        final T intentSelection = intentSelectionIter.next();
11874                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11875                            selectionFound = true;
11876                            break;
11877                        }
11878                    }
11879
11880                    // the selection criteria wasn't found in this filter's set; this filter
11881                    // is not a potential match
11882                    if (!selectionFound) {
11883                        intentIter.remove();
11884                    }
11885                }
11886            }
11887        }
11888
11889        private boolean isProtectedAction(ActivityIntentInfo filter) {
11890            final Iterator<String> actionsIter = filter.actionsIterator();
11891            while (actionsIter != null && actionsIter.hasNext()) {
11892                final String filterAction = actionsIter.next();
11893                if (PROTECTED_ACTIONS.contains(filterAction)) {
11894                    return true;
11895                }
11896            }
11897            return false;
11898        }
11899
11900        /**
11901         * Adjusts the priority of the given intent filter according to policy.
11902         * <p>
11903         * <ul>
11904         * <li>The priority for non privileged applications is capped to '0'</li>
11905         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11906         * <li>The priority for unbundled updates to privileged applications is capped to the
11907         *      priority defined on the system partition</li>
11908         * </ul>
11909         * <p>
11910         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11911         * allowed to obtain any priority on any action.
11912         */
11913        private void adjustPriority(
11914                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11915            // nothing to do; priority is fine as-is
11916            if (intent.getPriority() <= 0) {
11917                return;
11918            }
11919
11920            final ActivityInfo activityInfo = intent.activity.info;
11921            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11922
11923            final boolean privilegedApp =
11924                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11925            if (!privilegedApp) {
11926                // non-privileged applications can never define a priority >0
11927                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11928                        + " package: " + applicationInfo.packageName
11929                        + " activity: " + intent.activity.className
11930                        + " origPrio: " + intent.getPriority());
11931                intent.setPriority(0);
11932                return;
11933            }
11934
11935            if (systemActivities == null) {
11936                // the system package is not disabled; we're parsing the system partition
11937                if (isProtectedAction(intent)) {
11938                    if (mDeferProtectedFilters) {
11939                        // We can't deal with these just yet. No component should ever obtain a
11940                        // >0 priority for a protected actions, with ONE exception -- the setup
11941                        // wizard. The setup wizard, however, cannot be known until we're able to
11942                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11943                        // until all intent filters have been processed. Chicken, meet egg.
11944                        // Let the filter temporarily have a high priority and rectify the
11945                        // priorities after all system packages have been scanned.
11946                        mProtectedFilters.add(intent);
11947                        if (DEBUG_FILTERS) {
11948                            Slog.i(TAG, "Protected action; save for later;"
11949                                    + " package: " + applicationInfo.packageName
11950                                    + " activity: " + intent.activity.className
11951                                    + " origPrio: " + intent.getPriority());
11952                        }
11953                        return;
11954                    } else {
11955                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11956                            Slog.i(TAG, "No setup wizard;"
11957                                + " All protected intents capped to priority 0");
11958                        }
11959                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11960                            if (DEBUG_FILTERS) {
11961                                Slog.i(TAG, "Found setup wizard;"
11962                                    + " allow priority " + intent.getPriority() + ";"
11963                                    + " package: " + intent.activity.info.packageName
11964                                    + " activity: " + intent.activity.className
11965                                    + " priority: " + intent.getPriority());
11966                            }
11967                            // setup wizard gets whatever it wants
11968                            return;
11969                        }
11970                        Slog.w(TAG, "Protected action; cap priority to 0;"
11971                                + " package: " + intent.activity.info.packageName
11972                                + " activity: " + intent.activity.className
11973                                + " origPrio: " + intent.getPriority());
11974                        intent.setPriority(0);
11975                        return;
11976                    }
11977                }
11978                // privileged apps on the system image get whatever priority they request
11979                return;
11980            }
11981
11982            // privileged app unbundled update ... try to find the same activity
11983            final PackageParser.Activity foundActivity =
11984                    findMatchingActivity(systemActivities, activityInfo);
11985            if (foundActivity == null) {
11986                // this is a new activity; it cannot obtain >0 priority
11987                if (DEBUG_FILTERS) {
11988                    Slog.i(TAG, "New activity; cap priority to 0;"
11989                            + " package: " + applicationInfo.packageName
11990                            + " activity: " + intent.activity.className
11991                            + " origPrio: " + intent.getPriority());
11992                }
11993                intent.setPriority(0);
11994                return;
11995            }
11996
11997            // found activity, now check for filter equivalence
11998
11999            // a shallow copy is enough; we modify the list, not its contents
12000            final List<ActivityIntentInfo> intentListCopy =
12001                    new ArrayList<>(foundActivity.intents);
12002            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12003
12004            // find matching action subsets
12005            final Iterator<String> actionsIterator = intent.actionsIterator();
12006            if (actionsIterator != null) {
12007                getIntentListSubset(
12008                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12009                if (intentListCopy.size() == 0) {
12010                    // no more intents to match; we're not equivalent
12011                    if (DEBUG_FILTERS) {
12012                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12013                                + " package: " + applicationInfo.packageName
12014                                + " activity: " + intent.activity.className
12015                                + " origPrio: " + intent.getPriority());
12016                    }
12017                    intent.setPriority(0);
12018                    return;
12019                }
12020            }
12021
12022            // find matching category subsets
12023            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12024            if (categoriesIterator != null) {
12025                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12026                        categoriesIterator);
12027                if (intentListCopy.size() == 0) {
12028                    // no more intents to match; we're not equivalent
12029                    if (DEBUG_FILTERS) {
12030                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12031                                + " package: " + applicationInfo.packageName
12032                                + " activity: " + intent.activity.className
12033                                + " origPrio: " + intent.getPriority());
12034                    }
12035                    intent.setPriority(0);
12036                    return;
12037                }
12038            }
12039
12040            // find matching schemes subsets
12041            final Iterator<String> schemesIterator = intent.schemesIterator();
12042            if (schemesIterator != null) {
12043                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12044                        schemesIterator);
12045                if (intentListCopy.size() == 0) {
12046                    // no more intents to match; we're not equivalent
12047                    if (DEBUG_FILTERS) {
12048                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12049                                + " package: " + applicationInfo.packageName
12050                                + " activity: " + intent.activity.className
12051                                + " origPrio: " + intent.getPriority());
12052                    }
12053                    intent.setPriority(0);
12054                    return;
12055                }
12056            }
12057
12058            // find matching authorities subsets
12059            final Iterator<IntentFilter.AuthorityEntry>
12060                    authoritiesIterator = intent.authoritiesIterator();
12061            if (authoritiesIterator != null) {
12062                getIntentListSubset(intentListCopy,
12063                        new AuthoritiesIterGenerator(),
12064                        authoritiesIterator);
12065                if (intentListCopy.size() == 0) {
12066                    // no more intents to match; we're not equivalent
12067                    if (DEBUG_FILTERS) {
12068                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12069                                + " package: " + applicationInfo.packageName
12070                                + " activity: " + intent.activity.className
12071                                + " origPrio: " + intent.getPriority());
12072                    }
12073                    intent.setPriority(0);
12074                    return;
12075                }
12076            }
12077
12078            // we found matching filter(s); app gets the max priority of all intents
12079            int cappedPriority = 0;
12080            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12081                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12082            }
12083            if (intent.getPriority() > cappedPriority) {
12084                if (DEBUG_FILTERS) {
12085                    Slog.i(TAG, "Found matching filter(s);"
12086                            + " cap priority to " + cappedPriority + ";"
12087                            + " package: " + applicationInfo.packageName
12088                            + " activity: " + intent.activity.className
12089                            + " origPrio: " + intent.getPriority());
12090                }
12091                intent.setPriority(cappedPriority);
12092                return;
12093            }
12094            // all this for nothing; the requested priority was <= what was on the system
12095        }
12096
12097        public final void addActivity(PackageParser.Activity a, String type) {
12098            mActivities.put(a.getComponentName(), a);
12099            if (DEBUG_SHOW_INFO)
12100                Log.v(
12101                TAG, "  " + type + " " +
12102                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12103            if (DEBUG_SHOW_INFO)
12104                Log.v(TAG, "    Class=" + a.info.name);
12105            final int NI = a.intents.size();
12106            for (int j=0; j<NI; j++) {
12107                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12108                if ("activity".equals(type)) {
12109                    final PackageSetting ps =
12110                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12111                    final List<PackageParser.Activity> systemActivities =
12112                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12113                    adjustPriority(systemActivities, intent);
12114                }
12115                if (DEBUG_SHOW_INFO) {
12116                    Log.v(TAG, "    IntentFilter:");
12117                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12118                }
12119                if (!intent.debugCheck()) {
12120                    Log.w(TAG, "==> For Activity " + a.info.name);
12121                }
12122                addFilter(intent);
12123            }
12124        }
12125
12126        public final void removeActivity(PackageParser.Activity a, String type) {
12127            mActivities.remove(a.getComponentName());
12128            if (DEBUG_SHOW_INFO) {
12129                Log.v(TAG, "  " + type + " "
12130                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12131                                : a.info.name) + ":");
12132                Log.v(TAG, "    Class=" + a.info.name);
12133            }
12134            final int NI = a.intents.size();
12135            for (int j=0; j<NI; j++) {
12136                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12137                if (DEBUG_SHOW_INFO) {
12138                    Log.v(TAG, "    IntentFilter:");
12139                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12140                }
12141                removeFilter(intent);
12142            }
12143        }
12144
12145        @Override
12146        protected boolean allowFilterResult(
12147                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12148            ActivityInfo filterAi = filter.activity.info;
12149            for (int i=dest.size()-1; i>=0; i--) {
12150                ActivityInfo destAi = dest.get(i).activityInfo;
12151                if (destAi.name == filterAi.name
12152                        && destAi.packageName == filterAi.packageName) {
12153                    return false;
12154                }
12155            }
12156            return true;
12157        }
12158
12159        @Override
12160        protected ActivityIntentInfo[] newArray(int size) {
12161            return new ActivityIntentInfo[size];
12162        }
12163
12164        @Override
12165        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12166            if (!sUserManager.exists(userId)) return true;
12167            PackageParser.Package p = filter.activity.owner;
12168            if (p != null) {
12169                PackageSetting ps = (PackageSetting)p.mExtras;
12170                if (ps != null) {
12171                    // System apps are never considered stopped for purposes of
12172                    // filtering, because there may be no way for the user to
12173                    // actually re-launch them.
12174                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12175                            && ps.getStopped(userId);
12176                }
12177            }
12178            return false;
12179        }
12180
12181        @Override
12182        protected boolean isPackageForFilter(String packageName,
12183                PackageParser.ActivityIntentInfo info) {
12184            return packageName.equals(info.activity.owner.packageName);
12185        }
12186
12187        @Override
12188        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12189                int match, int userId) {
12190            if (!sUserManager.exists(userId)) return null;
12191            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12192                return null;
12193            }
12194            final PackageParser.Activity activity = info.activity;
12195            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12196            if (ps == null) {
12197                return null;
12198            }
12199            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12200                    ps.readUserState(userId), userId);
12201            if (ai == null) {
12202                return null;
12203            }
12204            final ResolveInfo res = new ResolveInfo();
12205            res.activityInfo = ai;
12206            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12207                res.filter = info;
12208            }
12209            if (info != null) {
12210                res.handleAllWebDataURI = info.handleAllWebDataURI();
12211            }
12212            res.priority = info.getPriority();
12213            res.preferredOrder = activity.owner.mPreferredOrder;
12214            //System.out.println("Result: " + res.activityInfo.className +
12215            //                   " = " + res.priority);
12216            res.match = match;
12217            res.isDefault = info.hasDefault;
12218            res.labelRes = info.labelRes;
12219            res.nonLocalizedLabel = info.nonLocalizedLabel;
12220            if (userNeedsBadging(userId)) {
12221                res.noResourceId = true;
12222            } else {
12223                res.icon = info.icon;
12224            }
12225            res.iconResourceId = info.icon;
12226            res.system = res.activityInfo.applicationInfo.isSystemApp();
12227            return res;
12228        }
12229
12230        @Override
12231        protected void sortResults(List<ResolveInfo> results) {
12232            Collections.sort(results, mResolvePrioritySorter);
12233        }
12234
12235        @Override
12236        protected void dumpFilter(PrintWriter out, String prefix,
12237                PackageParser.ActivityIntentInfo filter) {
12238            out.print(prefix); out.print(
12239                    Integer.toHexString(System.identityHashCode(filter.activity)));
12240                    out.print(' ');
12241                    filter.activity.printComponentShortName(out);
12242                    out.print(" filter ");
12243                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12244        }
12245
12246        @Override
12247        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12248            return filter.activity;
12249        }
12250
12251        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12252            PackageParser.Activity activity = (PackageParser.Activity)label;
12253            out.print(prefix); out.print(
12254                    Integer.toHexString(System.identityHashCode(activity)));
12255                    out.print(' ');
12256                    activity.printComponentShortName(out);
12257            if (count > 1) {
12258                out.print(" ("); out.print(count); out.print(" filters)");
12259            }
12260            out.println();
12261        }
12262
12263        // Keys are String (activity class name), values are Activity.
12264        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12265                = new ArrayMap<ComponentName, PackageParser.Activity>();
12266        private int mFlags;
12267    }
12268
12269    private final class ServiceIntentResolver
12270            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12271        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12272                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12273            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12274            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12275                    isEphemeral, userId);
12276        }
12277
12278        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12279                int userId) {
12280            if (!sUserManager.exists(userId)) return null;
12281            mFlags = flags;
12282            return super.queryIntent(intent, resolvedType,
12283                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12284                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12285                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12286        }
12287
12288        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12289                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12290            if (!sUserManager.exists(userId)) return null;
12291            if (packageServices == null) {
12292                return null;
12293            }
12294            mFlags = flags;
12295            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12296            final boolean vislbleToEphemeral =
12297                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12298            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12299            final int N = packageServices.size();
12300            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12301                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12302
12303            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12304            for (int i = 0; i < N; ++i) {
12305                intentFilters = packageServices.get(i).intents;
12306                if (intentFilters != null && intentFilters.size() > 0) {
12307                    PackageParser.ServiceIntentInfo[] array =
12308                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12309                    intentFilters.toArray(array);
12310                    listCut.add(array);
12311                }
12312            }
12313            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12314                    vislbleToEphemeral, isEphemeral, listCut, userId);
12315        }
12316
12317        public final void addService(PackageParser.Service s) {
12318            mServices.put(s.getComponentName(), s);
12319            if (DEBUG_SHOW_INFO) {
12320                Log.v(TAG, "  "
12321                        + (s.info.nonLocalizedLabel != null
12322                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12323                Log.v(TAG, "    Class=" + s.info.name);
12324            }
12325            final int NI = s.intents.size();
12326            int j;
12327            for (j=0; j<NI; j++) {
12328                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12329                if (DEBUG_SHOW_INFO) {
12330                    Log.v(TAG, "    IntentFilter:");
12331                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12332                }
12333                if (!intent.debugCheck()) {
12334                    Log.w(TAG, "==> For Service " + s.info.name);
12335                }
12336                addFilter(intent);
12337            }
12338        }
12339
12340        public final void removeService(PackageParser.Service s) {
12341            mServices.remove(s.getComponentName());
12342            if (DEBUG_SHOW_INFO) {
12343                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12344                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12345                Log.v(TAG, "    Class=" + s.info.name);
12346            }
12347            final int NI = s.intents.size();
12348            int j;
12349            for (j=0; j<NI; j++) {
12350                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12351                if (DEBUG_SHOW_INFO) {
12352                    Log.v(TAG, "    IntentFilter:");
12353                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12354                }
12355                removeFilter(intent);
12356            }
12357        }
12358
12359        @Override
12360        protected boolean allowFilterResult(
12361                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12362            ServiceInfo filterSi = filter.service.info;
12363            for (int i=dest.size()-1; i>=0; i--) {
12364                ServiceInfo destAi = dest.get(i).serviceInfo;
12365                if (destAi.name == filterSi.name
12366                        && destAi.packageName == filterSi.packageName) {
12367                    return false;
12368                }
12369            }
12370            return true;
12371        }
12372
12373        @Override
12374        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12375            return new PackageParser.ServiceIntentInfo[size];
12376        }
12377
12378        @Override
12379        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12380            if (!sUserManager.exists(userId)) return true;
12381            PackageParser.Package p = filter.service.owner;
12382            if (p != null) {
12383                PackageSetting ps = (PackageSetting)p.mExtras;
12384                if (ps != null) {
12385                    // System apps are never considered stopped for purposes of
12386                    // filtering, because there may be no way for the user to
12387                    // actually re-launch them.
12388                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12389                            && ps.getStopped(userId);
12390                }
12391            }
12392            return false;
12393        }
12394
12395        @Override
12396        protected boolean isPackageForFilter(String packageName,
12397                PackageParser.ServiceIntentInfo info) {
12398            return packageName.equals(info.service.owner.packageName);
12399        }
12400
12401        @Override
12402        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12403                int match, int userId) {
12404            if (!sUserManager.exists(userId)) return null;
12405            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12406            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12407                return null;
12408            }
12409            final PackageParser.Service service = info.service;
12410            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12411            if (ps == null) {
12412                return null;
12413            }
12414            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12415                    ps.readUserState(userId), userId);
12416            if (si == null) {
12417                return null;
12418            }
12419            final ResolveInfo res = new ResolveInfo();
12420            res.serviceInfo = si;
12421            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12422                res.filter = filter;
12423            }
12424            res.priority = info.getPriority();
12425            res.preferredOrder = service.owner.mPreferredOrder;
12426            res.match = match;
12427            res.isDefault = info.hasDefault;
12428            res.labelRes = info.labelRes;
12429            res.nonLocalizedLabel = info.nonLocalizedLabel;
12430            res.icon = info.icon;
12431            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12432            return res;
12433        }
12434
12435        @Override
12436        protected void sortResults(List<ResolveInfo> results) {
12437            Collections.sort(results, mResolvePrioritySorter);
12438        }
12439
12440        @Override
12441        protected void dumpFilter(PrintWriter out, String prefix,
12442                PackageParser.ServiceIntentInfo filter) {
12443            out.print(prefix); out.print(
12444                    Integer.toHexString(System.identityHashCode(filter.service)));
12445                    out.print(' ');
12446                    filter.service.printComponentShortName(out);
12447                    out.print(" filter ");
12448                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12449        }
12450
12451        @Override
12452        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12453            return filter.service;
12454        }
12455
12456        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12457            PackageParser.Service service = (PackageParser.Service)label;
12458            out.print(prefix); out.print(
12459                    Integer.toHexString(System.identityHashCode(service)));
12460                    out.print(' ');
12461                    service.printComponentShortName(out);
12462            if (count > 1) {
12463                out.print(" ("); out.print(count); out.print(" filters)");
12464            }
12465            out.println();
12466        }
12467
12468//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12469//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12470//            final List<ResolveInfo> retList = Lists.newArrayList();
12471//            while (i.hasNext()) {
12472//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12473//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12474//                    retList.add(resolveInfo);
12475//                }
12476//            }
12477//            return retList;
12478//        }
12479
12480        // Keys are String (activity class name), values are Activity.
12481        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12482                = new ArrayMap<ComponentName, PackageParser.Service>();
12483        private int mFlags;
12484    }
12485
12486    private final class ProviderIntentResolver
12487            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12488        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12489                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12490            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12491            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12492                    isEphemeral, userId);
12493        }
12494
12495        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12496                int userId) {
12497            if (!sUserManager.exists(userId))
12498                return null;
12499            mFlags = flags;
12500            return super.queryIntent(intent, resolvedType,
12501                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12502                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12503                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12504        }
12505
12506        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12507                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12508            if (!sUserManager.exists(userId))
12509                return null;
12510            if (packageProviders == null) {
12511                return null;
12512            }
12513            mFlags = flags;
12514            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12515            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12516            final boolean vislbleToEphemeral =
12517                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12518            final int N = packageProviders.size();
12519            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12520                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12521
12522            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12523            for (int i = 0; i < N; ++i) {
12524                intentFilters = packageProviders.get(i).intents;
12525                if (intentFilters != null && intentFilters.size() > 0) {
12526                    PackageParser.ProviderIntentInfo[] array =
12527                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12528                    intentFilters.toArray(array);
12529                    listCut.add(array);
12530                }
12531            }
12532            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12533                    vislbleToEphemeral, isEphemeral, listCut, userId);
12534        }
12535
12536        public final void addProvider(PackageParser.Provider p) {
12537            if (mProviders.containsKey(p.getComponentName())) {
12538                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12539                return;
12540            }
12541
12542            mProviders.put(p.getComponentName(), p);
12543            if (DEBUG_SHOW_INFO) {
12544                Log.v(TAG, "  "
12545                        + (p.info.nonLocalizedLabel != null
12546                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12547                Log.v(TAG, "    Class=" + p.info.name);
12548            }
12549            final int NI = p.intents.size();
12550            int j;
12551            for (j = 0; j < NI; j++) {
12552                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12553                if (DEBUG_SHOW_INFO) {
12554                    Log.v(TAG, "    IntentFilter:");
12555                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12556                }
12557                if (!intent.debugCheck()) {
12558                    Log.w(TAG, "==> For Provider " + p.info.name);
12559                }
12560                addFilter(intent);
12561            }
12562        }
12563
12564        public final void removeProvider(PackageParser.Provider p) {
12565            mProviders.remove(p.getComponentName());
12566            if (DEBUG_SHOW_INFO) {
12567                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12568                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12569                Log.v(TAG, "    Class=" + p.info.name);
12570            }
12571            final int NI = p.intents.size();
12572            int j;
12573            for (j = 0; j < NI; j++) {
12574                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12575                if (DEBUG_SHOW_INFO) {
12576                    Log.v(TAG, "    IntentFilter:");
12577                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12578                }
12579                removeFilter(intent);
12580            }
12581        }
12582
12583        @Override
12584        protected boolean allowFilterResult(
12585                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12586            ProviderInfo filterPi = filter.provider.info;
12587            for (int i = dest.size() - 1; i >= 0; i--) {
12588                ProviderInfo destPi = dest.get(i).providerInfo;
12589                if (destPi.name == filterPi.name
12590                        && destPi.packageName == filterPi.packageName) {
12591                    return false;
12592                }
12593            }
12594            return true;
12595        }
12596
12597        @Override
12598        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12599            return new PackageParser.ProviderIntentInfo[size];
12600        }
12601
12602        @Override
12603        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12604            if (!sUserManager.exists(userId))
12605                return true;
12606            PackageParser.Package p = filter.provider.owner;
12607            if (p != null) {
12608                PackageSetting ps = (PackageSetting) p.mExtras;
12609                if (ps != null) {
12610                    // System apps are never considered stopped for purposes of
12611                    // filtering, because there may be no way for the user to
12612                    // actually re-launch them.
12613                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12614                            && ps.getStopped(userId);
12615                }
12616            }
12617            return false;
12618        }
12619
12620        @Override
12621        protected boolean isPackageForFilter(String packageName,
12622                PackageParser.ProviderIntentInfo info) {
12623            return packageName.equals(info.provider.owner.packageName);
12624        }
12625
12626        @Override
12627        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12628                int match, int userId) {
12629            if (!sUserManager.exists(userId))
12630                return null;
12631            final PackageParser.ProviderIntentInfo info = filter;
12632            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12633                return null;
12634            }
12635            final PackageParser.Provider provider = info.provider;
12636            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12637            if (ps == null) {
12638                return null;
12639            }
12640            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12641                    ps.readUserState(userId), userId);
12642            if (pi == null) {
12643                return null;
12644            }
12645            final ResolveInfo res = new ResolveInfo();
12646            res.providerInfo = pi;
12647            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12648                res.filter = filter;
12649            }
12650            res.priority = info.getPriority();
12651            res.preferredOrder = provider.owner.mPreferredOrder;
12652            res.match = match;
12653            res.isDefault = info.hasDefault;
12654            res.labelRes = info.labelRes;
12655            res.nonLocalizedLabel = info.nonLocalizedLabel;
12656            res.icon = info.icon;
12657            res.system = res.providerInfo.applicationInfo.isSystemApp();
12658            return res;
12659        }
12660
12661        @Override
12662        protected void sortResults(List<ResolveInfo> results) {
12663            Collections.sort(results, mResolvePrioritySorter);
12664        }
12665
12666        @Override
12667        protected void dumpFilter(PrintWriter out, String prefix,
12668                PackageParser.ProviderIntentInfo filter) {
12669            out.print(prefix);
12670            out.print(
12671                    Integer.toHexString(System.identityHashCode(filter.provider)));
12672            out.print(' ');
12673            filter.provider.printComponentShortName(out);
12674            out.print(" filter ");
12675            out.println(Integer.toHexString(System.identityHashCode(filter)));
12676        }
12677
12678        @Override
12679        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12680            return filter.provider;
12681        }
12682
12683        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12684            PackageParser.Provider provider = (PackageParser.Provider)label;
12685            out.print(prefix); out.print(
12686                    Integer.toHexString(System.identityHashCode(provider)));
12687                    out.print(' ');
12688                    provider.printComponentShortName(out);
12689            if (count > 1) {
12690                out.print(" ("); out.print(count); out.print(" filters)");
12691            }
12692            out.println();
12693        }
12694
12695        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12696                = new ArrayMap<ComponentName, PackageParser.Provider>();
12697        private int mFlags;
12698    }
12699
12700    static final class EphemeralIntentResolver
12701            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12702        /**
12703         * The result that has the highest defined order. Ordering applies on a
12704         * per-package basis. Mapping is from package name to Pair of order and
12705         * EphemeralResolveInfo.
12706         * <p>
12707         * NOTE: This is implemented as a field variable for convenience and efficiency.
12708         * By having a field variable, we're able to track filter ordering as soon as
12709         * a non-zero order is defined. Otherwise, multiple loops across the result set
12710         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12711         * this needs to be contained entirely within {@link #filterResults()}.
12712         */
12713        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12714
12715        @Override
12716        protected EphemeralResponse[] newArray(int size) {
12717            return new EphemeralResponse[size];
12718        }
12719
12720        @Override
12721        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12722            return true;
12723        }
12724
12725        @Override
12726        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12727                int userId) {
12728            if (!sUserManager.exists(userId)) {
12729                return null;
12730            }
12731            final String packageName = responseObj.resolveInfo.getPackageName();
12732            final Integer order = responseObj.getOrder();
12733            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12734                    mOrderResult.get(packageName);
12735            // ordering is enabled and this item's order isn't high enough
12736            if (lastOrderResult != null && lastOrderResult.first >= order) {
12737                return null;
12738            }
12739            final EphemeralResolveInfo res = responseObj.resolveInfo;
12740            if (order > 0) {
12741                // non-zero order, enable ordering
12742                mOrderResult.put(packageName, new Pair<>(order, res));
12743            }
12744            return responseObj;
12745        }
12746
12747        @Override
12748        protected void filterResults(List<EphemeralResponse> results) {
12749            // only do work if ordering is enabled [most of the time it won't be]
12750            if (mOrderResult.size() == 0) {
12751                return;
12752            }
12753            int resultSize = results.size();
12754            for (int i = 0; i < resultSize; i++) {
12755                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12756                final String packageName = info.getPackageName();
12757                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12758                if (savedInfo == null) {
12759                    // package doesn't having ordering
12760                    continue;
12761                }
12762                if (savedInfo.second == info) {
12763                    // circled back to the highest ordered item; remove from order list
12764                    mOrderResult.remove(savedInfo);
12765                    if (mOrderResult.size() == 0) {
12766                        // no more ordered items
12767                        break;
12768                    }
12769                    continue;
12770                }
12771                // item has a worse order, remove it from the result list
12772                results.remove(i);
12773                resultSize--;
12774                i--;
12775            }
12776        }
12777    }
12778
12779    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12780            new Comparator<ResolveInfo>() {
12781        public int compare(ResolveInfo r1, ResolveInfo r2) {
12782            int v1 = r1.priority;
12783            int v2 = r2.priority;
12784            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12785            if (v1 != v2) {
12786                return (v1 > v2) ? -1 : 1;
12787            }
12788            v1 = r1.preferredOrder;
12789            v2 = r2.preferredOrder;
12790            if (v1 != v2) {
12791                return (v1 > v2) ? -1 : 1;
12792            }
12793            if (r1.isDefault != r2.isDefault) {
12794                return r1.isDefault ? -1 : 1;
12795            }
12796            v1 = r1.match;
12797            v2 = r2.match;
12798            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12799            if (v1 != v2) {
12800                return (v1 > v2) ? -1 : 1;
12801            }
12802            if (r1.system != r2.system) {
12803                return r1.system ? -1 : 1;
12804            }
12805            if (r1.activityInfo != null) {
12806                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12807            }
12808            if (r1.serviceInfo != null) {
12809                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12810            }
12811            if (r1.providerInfo != null) {
12812                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12813            }
12814            return 0;
12815        }
12816    };
12817
12818    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12819            new Comparator<ProviderInfo>() {
12820        public int compare(ProviderInfo p1, ProviderInfo p2) {
12821            final int v1 = p1.initOrder;
12822            final int v2 = p2.initOrder;
12823            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12824        }
12825    };
12826
12827    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12828            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12829            final int[] userIds) {
12830        mHandler.post(new Runnable() {
12831            @Override
12832            public void run() {
12833                try {
12834                    final IActivityManager am = ActivityManager.getService();
12835                    if (am == null) return;
12836                    final int[] resolvedUserIds;
12837                    if (userIds == null) {
12838                        resolvedUserIds = am.getRunningUserIds();
12839                    } else {
12840                        resolvedUserIds = userIds;
12841                    }
12842                    for (int id : resolvedUserIds) {
12843                        final Intent intent = new Intent(action,
12844                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12845                        if (extras != null) {
12846                            intent.putExtras(extras);
12847                        }
12848                        if (targetPkg != null) {
12849                            intent.setPackage(targetPkg);
12850                        }
12851                        // Modify the UID when posting to other users
12852                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12853                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12854                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12855                            intent.putExtra(Intent.EXTRA_UID, uid);
12856                        }
12857                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12858                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12859                        if (DEBUG_BROADCASTS) {
12860                            RuntimeException here = new RuntimeException("here");
12861                            here.fillInStackTrace();
12862                            Slog.d(TAG, "Sending to user " + id + ": "
12863                                    + intent.toShortString(false, true, false, false)
12864                                    + " " + intent.getExtras(), here);
12865                        }
12866                        am.broadcastIntent(null, intent, null, finishedReceiver,
12867                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12868                                null, finishedReceiver != null, false, id);
12869                    }
12870                } catch (RemoteException ex) {
12871                }
12872            }
12873        });
12874    }
12875
12876    /**
12877     * Check if the external storage media is available. This is true if there
12878     * is a mounted external storage medium or if the external storage is
12879     * emulated.
12880     */
12881    private boolean isExternalMediaAvailable() {
12882        return mMediaMounted || Environment.isExternalStorageEmulated();
12883    }
12884
12885    @Override
12886    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12887        // writer
12888        synchronized (mPackages) {
12889            if (!isExternalMediaAvailable()) {
12890                // If the external storage is no longer mounted at this point,
12891                // the caller may not have been able to delete all of this
12892                // packages files and can not delete any more.  Bail.
12893                return null;
12894            }
12895            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12896            if (lastPackage != null) {
12897                pkgs.remove(lastPackage);
12898            }
12899            if (pkgs.size() > 0) {
12900                return pkgs.get(0);
12901            }
12902        }
12903        return null;
12904    }
12905
12906    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12907        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12908                userId, andCode ? 1 : 0, packageName);
12909        if (mSystemReady) {
12910            msg.sendToTarget();
12911        } else {
12912            if (mPostSystemReadyMessages == null) {
12913                mPostSystemReadyMessages = new ArrayList<>();
12914            }
12915            mPostSystemReadyMessages.add(msg);
12916        }
12917    }
12918
12919    void startCleaningPackages() {
12920        // reader
12921        if (!isExternalMediaAvailable()) {
12922            return;
12923        }
12924        synchronized (mPackages) {
12925            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12926                return;
12927            }
12928        }
12929        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12930        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12931        IActivityManager am = ActivityManager.getService();
12932        if (am != null) {
12933            try {
12934                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12935                        UserHandle.USER_SYSTEM);
12936            } catch (RemoteException e) {
12937            }
12938        }
12939    }
12940
12941    @Override
12942    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12943            int installFlags, String installerPackageName, int userId) {
12944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12945
12946        final int callingUid = Binder.getCallingUid();
12947        enforceCrossUserPermission(callingUid, userId,
12948                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12949
12950        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12951            try {
12952                if (observer != null) {
12953                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12954                }
12955            } catch (RemoteException re) {
12956            }
12957            return;
12958        }
12959
12960        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12961            installFlags |= PackageManager.INSTALL_FROM_ADB;
12962
12963        } else {
12964            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12965            // about installerPackageName.
12966
12967            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12968            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12969        }
12970
12971        UserHandle user;
12972        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12973            user = UserHandle.ALL;
12974        } else {
12975            user = new UserHandle(userId);
12976        }
12977
12978        // Only system components can circumvent runtime permissions when installing.
12979        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12980                && mContext.checkCallingOrSelfPermission(Manifest.permission
12981                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12982            throw new SecurityException("You need the "
12983                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12984                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12985        }
12986
12987        final File originFile = new File(originPath);
12988        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12989
12990        final Message msg = mHandler.obtainMessage(INIT_COPY);
12991        final VerificationInfo verificationInfo = new VerificationInfo(
12992                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12993        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12994                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12995                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12996                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12997        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12998        msg.obj = params;
12999
13000        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13001                System.identityHashCode(msg.obj));
13002        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13003                System.identityHashCode(msg.obj));
13004
13005        mHandler.sendMessage(msg);
13006    }
13007
13008
13009    /**
13010     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13011     * it is acting on behalf on an enterprise or the user).
13012     *
13013     * Note that the ordering of the conditionals in this method is important. The checks we perform
13014     * are as follows, in this order:
13015     *
13016     * 1) If the install is being performed by a system app, we can trust the app to have set the
13017     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13018     *    what it is.
13019     * 2) If the install is being performed by a device or profile owner app, the install reason
13020     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13021     *    set the install reason correctly. If the app targets an older SDK version where install
13022     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13023     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13024     * 3) In all other cases, the install is being performed by a regular app that is neither part
13025     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13026     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13027     *    set to enterprise policy and if so, change it to unknown instead.
13028     */
13029    private int fixUpInstallReason(String installerPackageName, int installerUid,
13030            int installReason) {
13031        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13032                == PERMISSION_GRANTED) {
13033            // If the install is being performed by a system app, we trust that app to have set the
13034            // install reason correctly.
13035            return installReason;
13036        }
13037
13038        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13039            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13040        if (dpm != null) {
13041            ComponentName owner = null;
13042            try {
13043                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13044                if (owner == null) {
13045                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13046                }
13047            } catch (RemoteException e) {
13048            }
13049            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13050                // If the install is being performed by a device or profile owner, the install
13051                // reason should be enterprise policy.
13052                return PackageManager.INSTALL_REASON_POLICY;
13053            }
13054        }
13055
13056        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13057            // If the install is being performed by a regular app (i.e. neither system app nor
13058            // device or profile owner), we have no reason to believe that the app is acting on
13059            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13060            // change it to unknown instead.
13061            return PackageManager.INSTALL_REASON_UNKNOWN;
13062        }
13063
13064        // If the install is being performed by a regular app and the install reason was set to any
13065        // value but enterprise policy, leave the install reason unchanged.
13066        return installReason;
13067    }
13068
13069    void installStage(String packageName, File stagedDir, String stagedCid,
13070            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13071            String installerPackageName, int installerUid, UserHandle user,
13072            Certificate[][] certificates) {
13073        if (DEBUG_EPHEMERAL) {
13074            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13075                Slog.d(TAG, "Ephemeral install of " + packageName);
13076            }
13077        }
13078        final VerificationInfo verificationInfo = new VerificationInfo(
13079                sessionParams.originatingUri, sessionParams.referrerUri,
13080                sessionParams.originatingUid, installerUid);
13081
13082        final OriginInfo origin;
13083        if (stagedDir != null) {
13084            origin = OriginInfo.fromStagedFile(stagedDir);
13085        } else {
13086            origin = OriginInfo.fromStagedContainer(stagedCid);
13087        }
13088
13089        final Message msg = mHandler.obtainMessage(INIT_COPY);
13090        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13091                sessionParams.installReason);
13092        final InstallParams params = new InstallParams(origin, null, observer,
13093                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13094                verificationInfo, user, sessionParams.abiOverride,
13095                sessionParams.grantedRuntimePermissions, certificates, installReason);
13096        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13097        msg.obj = params;
13098
13099        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13100                System.identityHashCode(msg.obj));
13101        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13102                System.identityHashCode(msg.obj));
13103
13104        mHandler.sendMessage(msg);
13105    }
13106
13107    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13108            int userId) {
13109        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13110        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13111    }
13112
13113    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13114            int appId, int... userIds) {
13115        if (ArrayUtils.isEmpty(userIds)) {
13116            return;
13117        }
13118        Bundle extras = new Bundle(1);
13119        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13120        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13121
13122        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13123                packageName, extras, 0, null, null, userIds);
13124        if (isSystem) {
13125            mHandler.post(() -> {
13126                        for (int userId : userIds) {
13127                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13128                        }
13129                    }
13130            );
13131        }
13132    }
13133
13134    /**
13135     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13136     * automatically without needing an explicit launch.
13137     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13138     */
13139    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13140        // If user is not running, the app didn't miss any broadcast
13141        if (!mUserManagerInternal.isUserRunning(userId)) {
13142            return;
13143        }
13144        final IActivityManager am = ActivityManager.getService();
13145        try {
13146            // Deliver LOCKED_BOOT_COMPLETED first
13147            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13148                    .setPackage(packageName);
13149            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13150            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13151                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13152
13153            // Deliver BOOT_COMPLETED only if user is unlocked
13154            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13155                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13156                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13157                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13158            }
13159        } catch (RemoteException e) {
13160            throw e.rethrowFromSystemServer();
13161        }
13162    }
13163
13164    @Override
13165    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13166            int userId) {
13167        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13168        PackageSetting pkgSetting;
13169        final int uid = Binder.getCallingUid();
13170        enforceCrossUserPermission(uid, userId,
13171                true /* requireFullPermission */, true /* checkShell */,
13172                "setApplicationHiddenSetting for user " + userId);
13173
13174        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13175            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13176            return false;
13177        }
13178
13179        long callingId = Binder.clearCallingIdentity();
13180        try {
13181            boolean sendAdded = false;
13182            boolean sendRemoved = false;
13183            // writer
13184            synchronized (mPackages) {
13185                pkgSetting = mSettings.mPackages.get(packageName);
13186                if (pkgSetting == null) {
13187                    return false;
13188                }
13189                // Do not allow "android" is being disabled
13190                if ("android".equals(packageName)) {
13191                    Slog.w(TAG, "Cannot hide package: android");
13192                    return false;
13193                }
13194                // Cannot hide static shared libs as they are considered
13195                // a part of the using app (emulating static linking). Also
13196                // static libs are installed always on internal storage.
13197                PackageParser.Package pkg = mPackages.get(packageName);
13198                if (pkg != null && pkg.staticSharedLibName != null) {
13199                    Slog.w(TAG, "Cannot hide package: " + packageName
13200                            + " providing static shared library: "
13201                            + pkg.staticSharedLibName);
13202                    return false;
13203                }
13204                // Only allow protected packages to hide themselves.
13205                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13206                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13207                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13208                    return false;
13209                }
13210
13211                if (pkgSetting.getHidden(userId) != hidden) {
13212                    pkgSetting.setHidden(hidden, userId);
13213                    mSettings.writePackageRestrictionsLPr(userId);
13214                    if (hidden) {
13215                        sendRemoved = true;
13216                    } else {
13217                        sendAdded = true;
13218                    }
13219                }
13220            }
13221            if (sendAdded) {
13222                sendPackageAddedForUser(packageName, pkgSetting, userId);
13223                return true;
13224            }
13225            if (sendRemoved) {
13226                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13227                        "hiding pkg");
13228                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13229                return true;
13230            }
13231        } finally {
13232            Binder.restoreCallingIdentity(callingId);
13233        }
13234        return false;
13235    }
13236
13237    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13238            int userId) {
13239        final PackageRemovedInfo info = new PackageRemovedInfo();
13240        info.removedPackage = packageName;
13241        info.removedUsers = new int[] {userId};
13242        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13243        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13244    }
13245
13246    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13247        if (pkgList.length > 0) {
13248            Bundle extras = new Bundle(1);
13249            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13250
13251            sendPackageBroadcast(
13252                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13253                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13254                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13255                    new int[] {userId});
13256        }
13257    }
13258
13259    /**
13260     * Returns true if application is not found or there was an error. Otherwise it returns
13261     * the hidden state of the package for the given user.
13262     */
13263    @Override
13264    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13265        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13267                true /* requireFullPermission */, false /* checkShell */,
13268                "getApplicationHidden for user " + userId);
13269        PackageSetting pkgSetting;
13270        long callingId = Binder.clearCallingIdentity();
13271        try {
13272            // writer
13273            synchronized (mPackages) {
13274                pkgSetting = mSettings.mPackages.get(packageName);
13275                if (pkgSetting == null) {
13276                    return true;
13277                }
13278                return pkgSetting.getHidden(userId);
13279            }
13280        } finally {
13281            Binder.restoreCallingIdentity(callingId);
13282        }
13283    }
13284
13285    /**
13286     * @hide
13287     */
13288    @Override
13289    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13290        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13291                null);
13292        PackageSetting pkgSetting;
13293        final int uid = Binder.getCallingUid();
13294        enforceCrossUserPermission(uid, userId,
13295                true /* requireFullPermission */, true /* checkShell */,
13296                "installExistingPackage for user " + userId);
13297        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13298            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13299        }
13300
13301        long callingId = Binder.clearCallingIdentity();
13302        try {
13303            boolean installed = false;
13304
13305            // writer
13306            synchronized (mPackages) {
13307                pkgSetting = mSettings.mPackages.get(packageName);
13308                if (pkgSetting == null) {
13309                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13310                }
13311                if (!pkgSetting.getInstalled(userId)) {
13312                    pkgSetting.setInstalled(true, userId);
13313                    pkgSetting.setHidden(false, userId);
13314                    pkgSetting.setInstallReason(installReason, userId);
13315                    mSettings.writePackageRestrictionsLPr(userId);
13316                    installed = true;
13317                }
13318            }
13319
13320            if (installed) {
13321                if (pkgSetting.pkg != null) {
13322                    synchronized (mInstallLock) {
13323                        // We don't need to freeze for a brand new install
13324                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13325                    }
13326                }
13327                sendPackageAddedForUser(packageName, pkgSetting, userId);
13328                synchronized (mPackages) {
13329                    updateSequenceNumberLP(packageName, new int[]{ userId });
13330                }
13331            }
13332        } finally {
13333            Binder.restoreCallingIdentity(callingId);
13334        }
13335
13336        return PackageManager.INSTALL_SUCCEEDED;
13337    }
13338
13339    boolean isUserRestricted(int userId, String restrictionKey) {
13340        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13341        if (restrictions.getBoolean(restrictionKey, false)) {
13342            Log.w(TAG, "User is restricted: " + restrictionKey);
13343            return true;
13344        }
13345        return false;
13346    }
13347
13348    @Override
13349    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13350            int userId) {
13351        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13352        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13353                true /* requireFullPermission */, true /* checkShell */,
13354                "setPackagesSuspended for user " + userId);
13355
13356        if (ArrayUtils.isEmpty(packageNames)) {
13357            return packageNames;
13358        }
13359
13360        // List of package names for whom the suspended state has changed.
13361        List<String> changedPackages = new ArrayList<>(packageNames.length);
13362        // List of package names for whom the suspended state is not set as requested in this
13363        // method.
13364        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13365        long callingId = Binder.clearCallingIdentity();
13366        try {
13367            for (int i = 0; i < packageNames.length; i++) {
13368                String packageName = packageNames[i];
13369                boolean changed = false;
13370                final int appId;
13371                synchronized (mPackages) {
13372                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13373                    if (pkgSetting == null) {
13374                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13375                                + "\". Skipping suspending/un-suspending.");
13376                        unactionedPackages.add(packageName);
13377                        continue;
13378                    }
13379                    appId = pkgSetting.appId;
13380                    if (pkgSetting.getSuspended(userId) != suspended) {
13381                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13382                            unactionedPackages.add(packageName);
13383                            continue;
13384                        }
13385                        pkgSetting.setSuspended(suspended, userId);
13386                        mSettings.writePackageRestrictionsLPr(userId);
13387                        changed = true;
13388                        changedPackages.add(packageName);
13389                    }
13390                }
13391
13392                if (changed && suspended) {
13393                    killApplication(packageName, UserHandle.getUid(userId, appId),
13394                            "suspending package");
13395                }
13396            }
13397        } finally {
13398            Binder.restoreCallingIdentity(callingId);
13399        }
13400
13401        if (!changedPackages.isEmpty()) {
13402            sendPackagesSuspendedForUser(changedPackages.toArray(
13403                    new String[changedPackages.size()]), userId, suspended);
13404        }
13405
13406        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13407    }
13408
13409    @Override
13410    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13412                true /* requireFullPermission */, false /* checkShell */,
13413                "isPackageSuspendedForUser for user " + userId);
13414        synchronized (mPackages) {
13415            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13416            if (pkgSetting == null) {
13417                throw new IllegalArgumentException("Unknown target package: " + packageName);
13418            }
13419            return pkgSetting.getSuspended(userId);
13420        }
13421    }
13422
13423    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13424        if (isPackageDeviceAdmin(packageName, userId)) {
13425            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13426                    + "\": has an active device admin");
13427            return false;
13428        }
13429
13430        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13431        if (packageName.equals(activeLauncherPackageName)) {
13432            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13433                    + "\": contains the active launcher");
13434            return false;
13435        }
13436
13437        if (packageName.equals(mRequiredInstallerPackage)) {
13438            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13439                    + "\": required for package installation");
13440            return false;
13441        }
13442
13443        if (packageName.equals(mRequiredUninstallerPackage)) {
13444            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13445                    + "\": required for package uninstallation");
13446            return false;
13447        }
13448
13449        if (packageName.equals(mRequiredVerifierPackage)) {
13450            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13451                    + "\": required for package verification");
13452            return false;
13453        }
13454
13455        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13456            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13457                    + "\": is the default dialer");
13458            return false;
13459        }
13460
13461        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13462            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13463                    + "\": protected package");
13464            return false;
13465        }
13466
13467        // Cannot suspend static shared libs as they are considered
13468        // a part of the using app (emulating static linking). Also
13469        // static libs are installed always on internal storage.
13470        PackageParser.Package pkg = mPackages.get(packageName);
13471        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13472            Slog.w(TAG, "Cannot suspend package: " + packageName
13473                    + " providing static shared library: "
13474                    + pkg.staticSharedLibName);
13475            return false;
13476        }
13477
13478        return true;
13479    }
13480
13481    private String getActiveLauncherPackageName(int userId) {
13482        Intent intent = new Intent(Intent.ACTION_MAIN);
13483        intent.addCategory(Intent.CATEGORY_HOME);
13484        ResolveInfo resolveInfo = resolveIntent(
13485                intent,
13486                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13487                PackageManager.MATCH_DEFAULT_ONLY,
13488                userId);
13489
13490        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13491    }
13492
13493    private String getDefaultDialerPackageName(int userId) {
13494        synchronized (mPackages) {
13495            return mSettings.getDefaultDialerPackageNameLPw(userId);
13496        }
13497    }
13498
13499    @Override
13500    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13501        mContext.enforceCallingOrSelfPermission(
13502                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13503                "Only package verification agents can verify applications");
13504
13505        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13506        final PackageVerificationResponse response = new PackageVerificationResponse(
13507                verificationCode, Binder.getCallingUid());
13508        msg.arg1 = id;
13509        msg.obj = response;
13510        mHandler.sendMessage(msg);
13511    }
13512
13513    @Override
13514    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13515            long millisecondsToDelay) {
13516        mContext.enforceCallingOrSelfPermission(
13517                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13518                "Only package verification agents can extend verification timeouts");
13519
13520        final PackageVerificationState state = mPendingVerification.get(id);
13521        final PackageVerificationResponse response = new PackageVerificationResponse(
13522                verificationCodeAtTimeout, Binder.getCallingUid());
13523
13524        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13525            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13526        }
13527        if (millisecondsToDelay < 0) {
13528            millisecondsToDelay = 0;
13529        }
13530        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13531                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13532            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13533        }
13534
13535        if ((state != null) && !state.timeoutExtended()) {
13536            state.extendTimeout();
13537
13538            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13539            msg.arg1 = id;
13540            msg.obj = response;
13541            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13542        }
13543    }
13544
13545    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13546            int verificationCode, UserHandle user) {
13547        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13548        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13549        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13550        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13551        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13552
13553        mContext.sendBroadcastAsUser(intent, user,
13554                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13555    }
13556
13557    private ComponentName matchComponentForVerifier(String packageName,
13558            List<ResolveInfo> receivers) {
13559        ActivityInfo targetReceiver = null;
13560
13561        final int NR = receivers.size();
13562        for (int i = 0; i < NR; i++) {
13563            final ResolveInfo info = receivers.get(i);
13564            if (info.activityInfo == null) {
13565                continue;
13566            }
13567
13568            if (packageName.equals(info.activityInfo.packageName)) {
13569                targetReceiver = info.activityInfo;
13570                break;
13571            }
13572        }
13573
13574        if (targetReceiver == null) {
13575            return null;
13576        }
13577
13578        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13579    }
13580
13581    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13582            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13583        if (pkgInfo.verifiers.length == 0) {
13584            return null;
13585        }
13586
13587        final int N = pkgInfo.verifiers.length;
13588        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13589        for (int i = 0; i < N; i++) {
13590            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13591
13592            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13593                    receivers);
13594            if (comp == null) {
13595                continue;
13596            }
13597
13598            final int verifierUid = getUidForVerifier(verifierInfo);
13599            if (verifierUid == -1) {
13600                continue;
13601            }
13602
13603            if (DEBUG_VERIFY) {
13604                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13605                        + " with the correct signature");
13606            }
13607            sufficientVerifiers.add(comp);
13608            verificationState.addSufficientVerifier(verifierUid);
13609        }
13610
13611        return sufficientVerifiers;
13612    }
13613
13614    private int getUidForVerifier(VerifierInfo verifierInfo) {
13615        synchronized (mPackages) {
13616            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13617            if (pkg == null) {
13618                return -1;
13619            } else if (pkg.mSignatures.length != 1) {
13620                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13621                        + " has more than one signature; ignoring");
13622                return -1;
13623            }
13624
13625            /*
13626             * If the public key of the package's signature does not match
13627             * our expected public key, then this is a different package and
13628             * we should skip.
13629             */
13630
13631            final byte[] expectedPublicKey;
13632            try {
13633                final Signature verifierSig = pkg.mSignatures[0];
13634                final PublicKey publicKey = verifierSig.getPublicKey();
13635                expectedPublicKey = publicKey.getEncoded();
13636            } catch (CertificateException e) {
13637                return -1;
13638            }
13639
13640            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13641
13642            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13643                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13644                        + " does not have the expected public key; ignoring");
13645                return -1;
13646            }
13647
13648            return pkg.applicationInfo.uid;
13649        }
13650    }
13651
13652    @Override
13653    public void finishPackageInstall(int token, boolean didLaunch) {
13654        enforceSystemOrRoot("Only the system is allowed to finish installs");
13655
13656        if (DEBUG_INSTALL) {
13657            Slog.v(TAG, "BM finishing package install for " + token);
13658        }
13659        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13660
13661        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13662        mHandler.sendMessage(msg);
13663    }
13664
13665    /**
13666     * Get the verification agent timeout.
13667     *
13668     * @return verification timeout in milliseconds
13669     */
13670    private long getVerificationTimeout() {
13671        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13672                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13673                DEFAULT_VERIFICATION_TIMEOUT);
13674    }
13675
13676    /**
13677     * Get the default verification agent response code.
13678     *
13679     * @return default verification response code
13680     */
13681    private int getDefaultVerificationResponse() {
13682        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13683                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13684                DEFAULT_VERIFICATION_RESPONSE);
13685    }
13686
13687    /**
13688     * Check whether or not package verification has been enabled.
13689     *
13690     * @return true if verification should be performed
13691     */
13692    private boolean isVerificationEnabled(int userId, int installFlags) {
13693        if (!DEFAULT_VERIFY_ENABLE) {
13694            return false;
13695        }
13696        // Ephemeral apps don't get the full verification treatment
13697        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13698            if (DEBUG_EPHEMERAL) {
13699                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13700            }
13701            return false;
13702        }
13703
13704        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13705
13706        // Check if installing from ADB
13707        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13708            // Do not run verification in a test harness environment
13709            if (ActivityManager.isRunningInTestHarness()) {
13710                return false;
13711            }
13712            if (ensureVerifyAppsEnabled) {
13713                return true;
13714            }
13715            // Check if the developer does not want package verification for ADB installs
13716            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13717                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13718                return false;
13719            }
13720        }
13721
13722        if (ensureVerifyAppsEnabled) {
13723            return true;
13724        }
13725
13726        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13727                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13728    }
13729
13730    @Override
13731    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13732            throws RemoteException {
13733        mContext.enforceCallingOrSelfPermission(
13734                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13735                "Only intentfilter verification agents can verify applications");
13736
13737        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13738        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13739                Binder.getCallingUid(), verificationCode, failedDomains);
13740        msg.arg1 = id;
13741        msg.obj = response;
13742        mHandler.sendMessage(msg);
13743    }
13744
13745    @Override
13746    public int getIntentVerificationStatus(String packageName, int userId) {
13747        synchronized (mPackages) {
13748            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13749        }
13750    }
13751
13752    @Override
13753    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13754        mContext.enforceCallingOrSelfPermission(
13755                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13756
13757        boolean result = false;
13758        synchronized (mPackages) {
13759            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13760        }
13761        if (result) {
13762            scheduleWritePackageRestrictionsLocked(userId);
13763        }
13764        return result;
13765    }
13766
13767    @Override
13768    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13769            String packageName) {
13770        synchronized (mPackages) {
13771            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13772        }
13773    }
13774
13775    @Override
13776    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13777        if (TextUtils.isEmpty(packageName)) {
13778            return ParceledListSlice.emptyList();
13779        }
13780        synchronized (mPackages) {
13781            PackageParser.Package pkg = mPackages.get(packageName);
13782            if (pkg == null || pkg.activities == null) {
13783                return ParceledListSlice.emptyList();
13784            }
13785            final int count = pkg.activities.size();
13786            ArrayList<IntentFilter> result = new ArrayList<>();
13787            for (int n=0; n<count; n++) {
13788                PackageParser.Activity activity = pkg.activities.get(n);
13789                if (activity.intents != null && activity.intents.size() > 0) {
13790                    result.addAll(activity.intents);
13791                }
13792            }
13793            return new ParceledListSlice<>(result);
13794        }
13795    }
13796
13797    @Override
13798    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13799        mContext.enforceCallingOrSelfPermission(
13800                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13801
13802        synchronized (mPackages) {
13803            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13804            if (packageName != null) {
13805                result |= updateIntentVerificationStatus(packageName,
13806                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13807                        userId);
13808                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13809                        packageName, userId);
13810            }
13811            return result;
13812        }
13813    }
13814
13815    @Override
13816    public String getDefaultBrowserPackageName(int userId) {
13817        synchronized (mPackages) {
13818            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13819        }
13820    }
13821
13822    /**
13823     * Get the "allow unknown sources" setting.
13824     *
13825     * @return the current "allow unknown sources" setting
13826     */
13827    private int getUnknownSourcesSettings() {
13828        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13829                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13830                -1);
13831    }
13832
13833    @Override
13834    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13835        final int uid = Binder.getCallingUid();
13836        // writer
13837        synchronized (mPackages) {
13838            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13839            if (targetPackageSetting == null) {
13840                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13841            }
13842
13843            PackageSetting installerPackageSetting;
13844            if (installerPackageName != null) {
13845                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13846                if (installerPackageSetting == null) {
13847                    throw new IllegalArgumentException("Unknown installer package: "
13848                            + installerPackageName);
13849                }
13850            } else {
13851                installerPackageSetting = null;
13852            }
13853
13854            Signature[] callerSignature;
13855            Object obj = mSettings.getUserIdLPr(uid);
13856            if (obj != null) {
13857                if (obj instanceof SharedUserSetting) {
13858                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13859                } else if (obj instanceof PackageSetting) {
13860                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13861                } else {
13862                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13863                }
13864            } else {
13865                throw new SecurityException("Unknown calling UID: " + uid);
13866            }
13867
13868            // Verify: can't set installerPackageName to a package that is
13869            // not signed with the same cert as the caller.
13870            if (installerPackageSetting != null) {
13871                if (compareSignatures(callerSignature,
13872                        installerPackageSetting.signatures.mSignatures)
13873                        != PackageManager.SIGNATURE_MATCH) {
13874                    throw new SecurityException(
13875                            "Caller does not have same cert as new installer package "
13876                            + installerPackageName);
13877                }
13878            }
13879
13880            // Verify: if target already has an installer package, it must
13881            // be signed with the same cert as the caller.
13882            if (targetPackageSetting.installerPackageName != null) {
13883                PackageSetting setting = mSettings.mPackages.get(
13884                        targetPackageSetting.installerPackageName);
13885                // If the currently set package isn't valid, then it's always
13886                // okay to change it.
13887                if (setting != null) {
13888                    if (compareSignatures(callerSignature,
13889                            setting.signatures.mSignatures)
13890                            != PackageManager.SIGNATURE_MATCH) {
13891                        throw new SecurityException(
13892                                "Caller does not have same cert as old installer package "
13893                                + targetPackageSetting.installerPackageName);
13894                    }
13895                }
13896            }
13897
13898            // Okay!
13899            targetPackageSetting.installerPackageName = installerPackageName;
13900            if (installerPackageName != null) {
13901                mSettings.mInstallerPackages.add(installerPackageName);
13902            }
13903            scheduleWriteSettingsLocked();
13904        }
13905    }
13906
13907    @Override
13908    public void setApplicationCategoryHint(String packageName, int categoryHint,
13909            String callerPackageName) {
13910        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13911                callerPackageName);
13912        synchronized (mPackages) {
13913            PackageSetting ps = mSettings.mPackages.get(packageName);
13914            if (ps == null) {
13915                throw new IllegalArgumentException("Unknown target package " + packageName);
13916            }
13917
13918            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13919                throw new IllegalArgumentException("Calling package " + callerPackageName
13920                        + " is not installer for " + packageName);
13921            }
13922
13923            if (ps.categoryHint != categoryHint) {
13924                ps.categoryHint = categoryHint;
13925                scheduleWriteSettingsLocked();
13926            }
13927        }
13928    }
13929
13930    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13931        // Queue up an async operation since the package installation may take a little while.
13932        mHandler.post(new Runnable() {
13933            public void run() {
13934                mHandler.removeCallbacks(this);
13935                 // Result object to be returned
13936                PackageInstalledInfo res = new PackageInstalledInfo();
13937                res.setReturnCode(currentStatus);
13938                res.uid = -1;
13939                res.pkg = null;
13940                res.removedInfo = null;
13941                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13942                    args.doPreInstall(res.returnCode);
13943                    synchronized (mInstallLock) {
13944                        installPackageTracedLI(args, res);
13945                    }
13946                    args.doPostInstall(res.returnCode, res.uid);
13947                }
13948
13949                // A restore should be performed at this point if (a) the install
13950                // succeeded, (b) the operation is not an update, and (c) the new
13951                // package has not opted out of backup participation.
13952                final boolean update = res.removedInfo != null
13953                        && res.removedInfo.removedPackage != null;
13954                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13955                boolean doRestore = !update
13956                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13957
13958                // Set up the post-install work request bookkeeping.  This will be used
13959                // and cleaned up by the post-install event handling regardless of whether
13960                // there's a restore pass performed.  Token values are >= 1.
13961                int token;
13962                if (mNextInstallToken < 0) mNextInstallToken = 1;
13963                token = mNextInstallToken++;
13964
13965                PostInstallData data = new PostInstallData(args, res);
13966                mRunningInstalls.put(token, data);
13967                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13968
13969                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13970                    // Pass responsibility to the Backup Manager.  It will perform a
13971                    // restore if appropriate, then pass responsibility back to the
13972                    // Package Manager to run the post-install observer callbacks
13973                    // and broadcasts.
13974                    IBackupManager bm = IBackupManager.Stub.asInterface(
13975                            ServiceManager.getService(Context.BACKUP_SERVICE));
13976                    if (bm != null) {
13977                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13978                                + " to BM for possible restore");
13979                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13980                        try {
13981                            // TODO: http://b/22388012
13982                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13983                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13984                            } else {
13985                                doRestore = false;
13986                            }
13987                        } catch (RemoteException e) {
13988                            // can't happen; the backup manager is local
13989                        } catch (Exception e) {
13990                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13991                            doRestore = false;
13992                        }
13993                    } else {
13994                        Slog.e(TAG, "Backup Manager not found!");
13995                        doRestore = false;
13996                    }
13997                }
13998
13999                if (!doRestore) {
14000                    // No restore possible, or the Backup Manager was mysteriously not
14001                    // available -- just fire the post-install work request directly.
14002                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14003
14004                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14005
14006                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14007                    mHandler.sendMessage(msg);
14008                }
14009            }
14010        });
14011    }
14012
14013    /**
14014     * Callback from PackageSettings whenever an app is first transitioned out of the
14015     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14016     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14017     * here whether the app is the target of an ongoing install, and only send the
14018     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14019     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14020     * handling.
14021     */
14022    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14023        // Serialize this with the rest of the install-process message chain.  In the
14024        // restore-at-install case, this Runnable will necessarily run before the
14025        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14026        // are coherent.  In the non-restore case, the app has already completed install
14027        // and been launched through some other means, so it is not in a problematic
14028        // state for observers to see the FIRST_LAUNCH signal.
14029        mHandler.post(new Runnable() {
14030            @Override
14031            public void run() {
14032                for (int i = 0; i < mRunningInstalls.size(); i++) {
14033                    final PostInstallData data = mRunningInstalls.valueAt(i);
14034                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14035                        continue;
14036                    }
14037                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14038                        // right package; but is it for the right user?
14039                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14040                            if (userId == data.res.newUsers[uIndex]) {
14041                                if (DEBUG_BACKUP) {
14042                                    Slog.i(TAG, "Package " + pkgName
14043                                            + " being restored so deferring FIRST_LAUNCH");
14044                                }
14045                                return;
14046                            }
14047                        }
14048                    }
14049                }
14050                // didn't find it, so not being restored
14051                if (DEBUG_BACKUP) {
14052                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14053                }
14054                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14055            }
14056        });
14057    }
14058
14059    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14060        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14061                installerPkg, null, userIds);
14062    }
14063
14064    private abstract class HandlerParams {
14065        private static final int MAX_RETRIES = 4;
14066
14067        /**
14068         * Number of times startCopy() has been attempted and had a non-fatal
14069         * error.
14070         */
14071        private int mRetries = 0;
14072
14073        /** User handle for the user requesting the information or installation. */
14074        private final UserHandle mUser;
14075        String traceMethod;
14076        int traceCookie;
14077
14078        HandlerParams(UserHandle user) {
14079            mUser = user;
14080        }
14081
14082        UserHandle getUser() {
14083            return mUser;
14084        }
14085
14086        HandlerParams setTraceMethod(String traceMethod) {
14087            this.traceMethod = traceMethod;
14088            return this;
14089        }
14090
14091        HandlerParams setTraceCookie(int traceCookie) {
14092            this.traceCookie = traceCookie;
14093            return this;
14094        }
14095
14096        final boolean startCopy() {
14097            boolean res;
14098            try {
14099                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14100
14101                if (++mRetries > MAX_RETRIES) {
14102                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14103                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14104                    handleServiceError();
14105                    return false;
14106                } else {
14107                    handleStartCopy();
14108                    res = true;
14109                }
14110            } catch (RemoteException e) {
14111                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14112                mHandler.sendEmptyMessage(MCS_RECONNECT);
14113                res = false;
14114            }
14115            handleReturnCode();
14116            return res;
14117        }
14118
14119        final void serviceError() {
14120            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14121            handleServiceError();
14122            handleReturnCode();
14123        }
14124
14125        abstract void handleStartCopy() throws RemoteException;
14126        abstract void handleServiceError();
14127        abstract void handleReturnCode();
14128    }
14129
14130    class MeasureParams extends HandlerParams {
14131        private final PackageStats mStats;
14132        private boolean mSuccess;
14133
14134        private final IPackageStatsObserver mObserver;
14135
14136        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14137            super(new UserHandle(stats.userHandle));
14138            mObserver = observer;
14139            mStats = stats;
14140        }
14141
14142        @Override
14143        public String toString() {
14144            return "MeasureParams{"
14145                + Integer.toHexString(System.identityHashCode(this))
14146                + " " + mStats.packageName + "}";
14147        }
14148
14149        @Override
14150        void handleStartCopy() throws RemoteException {
14151            synchronized (mInstallLock) {
14152                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14153            }
14154
14155            if (mSuccess) {
14156                boolean mounted = false;
14157                try {
14158                    final String status = Environment.getExternalStorageState();
14159                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14160                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14161                } catch (Exception e) {
14162                }
14163
14164                if (mounted) {
14165                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14166
14167                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14168                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14169
14170                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14171                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14172
14173                    // Always subtract cache size, since it's a subdirectory
14174                    mStats.externalDataSize -= mStats.externalCacheSize;
14175
14176                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14177                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14178
14179                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14180                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14181                }
14182            }
14183        }
14184
14185        @Override
14186        void handleReturnCode() {
14187            if (mObserver != null) {
14188                try {
14189                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14190                } catch (RemoteException e) {
14191                    Slog.i(TAG, "Observer no longer exists.");
14192                }
14193            }
14194        }
14195
14196        @Override
14197        void handleServiceError() {
14198            Slog.e(TAG, "Could not measure application " + mStats.packageName
14199                            + " external storage");
14200        }
14201    }
14202
14203    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14204            throws RemoteException {
14205        long result = 0;
14206        for (File path : paths) {
14207            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14208        }
14209        return result;
14210    }
14211
14212    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14213        for (File path : paths) {
14214            try {
14215                mcs.clearDirectory(path.getAbsolutePath());
14216            } catch (RemoteException e) {
14217            }
14218        }
14219    }
14220
14221    static class OriginInfo {
14222        /**
14223         * Location where install is coming from, before it has been
14224         * copied/renamed into place. This could be a single monolithic APK
14225         * file, or a cluster directory. This location may be untrusted.
14226         */
14227        final File file;
14228        final String cid;
14229
14230        /**
14231         * Flag indicating that {@link #file} or {@link #cid} has already been
14232         * staged, meaning downstream users don't need to defensively copy the
14233         * contents.
14234         */
14235        final boolean staged;
14236
14237        /**
14238         * Flag indicating that {@link #file} or {@link #cid} is an already
14239         * installed app that is being moved.
14240         */
14241        final boolean existing;
14242
14243        final String resolvedPath;
14244        final File resolvedFile;
14245
14246        static OriginInfo fromNothing() {
14247            return new OriginInfo(null, null, false, false);
14248        }
14249
14250        static OriginInfo fromUntrustedFile(File file) {
14251            return new OriginInfo(file, null, false, false);
14252        }
14253
14254        static OriginInfo fromExistingFile(File file) {
14255            return new OriginInfo(file, null, false, true);
14256        }
14257
14258        static OriginInfo fromStagedFile(File file) {
14259            return new OriginInfo(file, null, true, false);
14260        }
14261
14262        static OriginInfo fromStagedContainer(String cid) {
14263            return new OriginInfo(null, cid, true, false);
14264        }
14265
14266        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14267            this.file = file;
14268            this.cid = cid;
14269            this.staged = staged;
14270            this.existing = existing;
14271
14272            if (cid != null) {
14273                resolvedPath = PackageHelper.getSdDir(cid);
14274                resolvedFile = new File(resolvedPath);
14275            } else if (file != null) {
14276                resolvedPath = file.getAbsolutePath();
14277                resolvedFile = file;
14278            } else {
14279                resolvedPath = null;
14280                resolvedFile = null;
14281            }
14282        }
14283    }
14284
14285    static class MoveInfo {
14286        final int moveId;
14287        final String fromUuid;
14288        final String toUuid;
14289        final String packageName;
14290        final String dataAppName;
14291        final int appId;
14292        final String seinfo;
14293        final int targetSdkVersion;
14294
14295        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14296                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14297            this.moveId = moveId;
14298            this.fromUuid = fromUuid;
14299            this.toUuid = toUuid;
14300            this.packageName = packageName;
14301            this.dataAppName = dataAppName;
14302            this.appId = appId;
14303            this.seinfo = seinfo;
14304            this.targetSdkVersion = targetSdkVersion;
14305        }
14306    }
14307
14308    static class VerificationInfo {
14309        /** A constant used to indicate that a uid value is not present. */
14310        public static final int NO_UID = -1;
14311
14312        /** URI referencing where the package was downloaded from. */
14313        final Uri originatingUri;
14314
14315        /** HTTP referrer URI associated with the originatingURI. */
14316        final Uri referrer;
14317
14318        /** UID of the application that the install request originated from. */
14319        final int originatingUid;
14320
14321        /** UID of application requesting the install */
14322        final int installerUid;
14323
14324        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14325            this.originatingUri = originatingUri;
14326            this.referrer = referrer;
14327            this.originatingUid = originatingUid;
14328            this.installerUid = installerUid;
14329        }
14330    }
14331
14332    class InstallParams extends HandlerParams {
14333        final OriginInfo origin;
14334        final MoveInfo move;
14335        final IPackageInstallObserver2 observer;
14336        int installFlags;
14337        final String installerPackageName;
14338        final String volumeUuid;
14339        private InstallArgs mArgs;
14340        private int mRet;
14341        final String packageAbiOverride;
14342        final String[] grantedRuntimePermissions;
14343        final VerificationInfo verificationInfo;
14344        final Certificate[][] certificates;
14345        final int installReason;
14346
14347        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14348                int installFlags, String installerPackageName, String volumeUuid,
14349                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14350                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14351            super(user);
14352            this.origin = origin;
14353            this.move = move;
14354            this.observer = observer;
14355            this.installFlags = installFlags;
14356            this.installerPackageName = installerPackageName;
14357            this.volumeUuid = volumeUuid;
14358            this.verificationInfo = verificationInfo;
14359            this.packageAbiOverride = packageAbiOverride;
14360            this.grantedRuntimePermissions = grantedPermissions;
14361            this.certificates = certificates;
14362            this.installReason = installReason;
14363        }
14364
14365        @Override
14366        public String toString() {
14367            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14368                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14369        }
14370
14371        private int installLocationPolicy(PackageInfoLite pkgLite) {
14372            String packageName = pkgLite.packageName;
14373            int installLocation = pkgLite.installLocation;
14374            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14375            // reader
14376            synchronized (mPackages) {
14377                // Currently installed package which the new package is attempting to replace or
14378                // null if no such package is installed.
14379                PackageParser.Package installedPkg = mPackages.get(packageName);
14380                // Package which currently owns the data which the new package will own if installed.
14381                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14382                // will be null whereas dataOwnerPkg will contain information about the package
14383                // which was uninstalled while keeping its data.
14384                PackageParser.Package dataOwnerPkg = installedPkg;
14385                if (dataOwnerPkg  == null) {
14386                    PackageSetting ps = mSettings.mPackages.get(packageName);
14387                    if (ps != null) {
14388                        dataOwnerPkg = ps.pkg;
14389                    }
14390                }
14391
14392                if (dataOwnerPkg != null) {
14393                    // If installed, the package will get access to data left on the device by its
14394                    // predecessor. As a security measure, this is permited only if this is not a
14395                    // version downgrade or if the predecessor package is marked as debuggable and
14396                    // a downgrade is explicitly requested.
14397                    //
14398                    // On debuggable platform builds, downgrades are permitted even for
14399                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14400                    // not offer security guarantees and thus it's OK to disable some security
14401                    // mechanisms to make debugging/testing easier on those builds. However, even on
14402                    // debuggable builds downgrades of packages are permitted only if requested via
14403                    // installFlags. This is because we aim to keep the behavior of debuggable
14404                    // platform builds as close as possible to the behavior of non-debuggable
14405                    // platform builds.
14406                    final boolean downgradeRequested =
14407                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14408                    final boolean packageDebuggable =
14409                                (dataOwnerPkg.applicationInfo.flags
14410                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14411                    final boolean downgradePermitted =
14412                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14413                    if (!downgradePermitted) {
14414                        try {
14415                            checkDowngrade(dataOwnerPkg, pkgLite);
14416                        } catch (PackageManagerException e) {
14417                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14418                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14419                        }
14420                    }
14421                }
14422
14423                if (installedPkg != null) {
14424                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14425                        // Check for updated system application.
14426                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14427                            if (onSd) {
14428                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14429                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14430                            }
14431                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14432                        } else {
14433                            if (onSd) {
14434                                // Install flag overrides everything.
14435                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14436                            }
14437                            // If current upgrade specifies particular preference
14438                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14439                                // Application explicitly specified internal.
14440                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14441                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14442                                // App explictly prefers external. Let policy decide
14443                            } else {
14444                                // Prefer previous location
14445                                if (isExternal(installedPkg)) {
14446                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14447                                }
14448                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14449                            }
14450                        }
14451                    } else {
14452                        // Invalid install. Return error code
14453                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14454                    }
14455                }
14456            }
14457            // All the special cases have been taken care of.
14458            // Return result based on recommended install location.
14459            if (onSd) {
14460                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14461            }
14462            return pkgLite.recommendedInstallLocation;
14463        }
14464
14465        /*
14466         * Invoke remote method to get package information and install
14467         * location values. Override install location based on default
14468         * policy if needed and then create install arguments based
14469         * on the install location.
14470         */
14471        public void handleStartCopy() throws RemoteException {
14472            int ret = PackageManager.INSTALL_SUCCEEDED;
14473
14474            // If we're already staged, we've firmly committed to an install location
14475            if (origin.staged) {
14476                if (origin.file != null) {
14477                    installFlags |= PackageManager.INSTALL_INTERNAL;
14478                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14479                } else if (origin.cid != null) {
14480                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14481                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14482                } else {
14483                    throw new IllegalStateException("Invalid stage location");
14484                }
14485            }
14486
14487            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14488            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14489            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14490            PackageInfoLite pkgLite = null;
14491
14492            if (onInt && onSd) {
14493                // Check if both bits are set.
14494                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14495                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14496            } else if (onSd && ephemeral) {
14497                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14498                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14499            } else {
14500                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14501                        packageAbiOverride);
14502
14503                if (DEBUG_EPHEMERAL && ephemeral) {
14504                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14505                }
14506
14507                /*
14508                 * If we have too little free space, try to free cache
14509                 * before giving up.
14510                 */
14511                if (!origin.staged && pkgLite.recommendedInstallLocation
14512                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14513                    // TODO: focus freeing disk space on the target device
14514                    final StorageManager storage = StorageManager.from(mContext);
14515                    final long lowThreshold = storage.getStorageLowBytes(
14516                            Environment.getDataDirectory());
14517
14518                    final long sizeBytes = mContainerService.calculateInstalledSize(
14519                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14520
14521                    try {
14522                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14523                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14524                                installFlags, packageAbiOverride);
14525                    } catch (InstallerException e) {
14526                        Slog.w(TAG, "Failed to free cache", e);
14527                    }
14528
14529                    /*
14530                     * The cache free must have deleted the file we
14531                     * downloaded to install.
14532                     *
14533                     * TODO: fix the "freeCache" call to not delete
14534                     *       the file we care about.
14535                     */
14536                    if (pkgLite.recommendedInstallLocation
14537                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14538                        pkgLite.recommendedInstallLocation
14539                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14540                    }
14541                }
14542            }
14543
14544            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14545                int loc = pkgLite.recommendedInstallLocation;
14546                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14547                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14548                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14549                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14550                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14551                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14552                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14553                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14554                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14555                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14556                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14557                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14558                } else {
14559                    // Override with defaults if needed.
14560                    loc = installLocationPolicy(pkgLite);
14561                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14562                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14563                    } else if (!onSd && !onInt) {
14564                        // Override install location with flags
14565                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14566                            // Set the flag to install on external media.
14567                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14568                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14569                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14570                            if (DEBUG_EPHEMERAL) {
14571                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14572                            }
14573                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14574                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14575                                    |PackageManager.INSTALL_INTERNAL);
14576                        } else {
14577                            // Make sure the flag for installing on external
14578                            // media is unset
14579                            installFlags |= PackageManager.INSTALL_INTERNAL;
14580                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14581                        }
14582                    }
14583                }
14584            }
14585
14586            final InstallArgs args = createInstallArgs(this);
14587            mArgs = args;
14588
14589            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14590                // TODO: http://b/22976637
14591                // Apps installed for "all" users use the device owner to verify the app
14592                UserHandle verifierUser = getUser();
14593                if (verifierUser == UserHandle.ALL) {
14594                    verifierUser = UserHandle.SYSTEM;
14595                }
14596
14597                /*
14598                 * Determine if we have any installed package verifiers. If we
14599                 * do, then we'll defer to them to verify the packages.
14600                 */
14601                final int requiredUid = mRequiredVerifierPackage == null ? -1
14602                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14603                                verifierUser.getIdentifier());
14604                if (!origin.existing && requiredUid != -1
14605                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14606                    final Intent verification = new Intent(
14607                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14608                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14609                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14610                            PACKAGE_MIME_TYPE);
14611                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14612
14613                    // Query all live verifiers based on current user state
14614                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14615                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14616
14617                    if (DEBUG_VERIFY) {
14618                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14619                                + verification.toString() + " with " + pkgLite.verifiers.length
14620                                + " optional verifiers");
14621                    }
14622
14623                    final int verificationId = mPendingVerificationToken++;
14624
14625                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14626
14627                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14628                            installerPackageName);
14629
14630                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14631                            installFlags);
14632
14633                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14634                            pkgLite.packageName);
14635
14636                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14637                            pkgLite.versionCode);
14638
14639                    if (verificationInfo != null) {
14640                        if (verificationInfo.originatingUri != null) {
14641                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14642                                    verificationInfo.originatingUri);
14643                        }
14644                        if (verificationInfo.referrer != null) {
14645                            verification.putExtra(Intent.EXTRA_REFERRER,
14646                                    verificationInfo.referrer);
14647                        }
14648                        if (verificationInfo.originatingUid >= 0) {
14649                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14650                                    verificationInfo.originatingUid);
14651                        }
14652                        if (verificationInfo.installerUid >= 0) {
14653                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14654                                    verificationInfo.installerUid);
14655                        }
14656                    }
14657
14658                    final PackageVerificationState verificationState = new PackageVerificationState(
14659                            requiredUid, args);
14660
14661                    mPendingVerification.append(verificationId, verificationState);
14662
14663                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14664                            receivers, verificationState);
14665
14666                    /*
14667                     * If any sufficient verifiers were listed in the package
14668                     * manifest, attempt to ask them.
14669                     */
14670                    if (sufficientVerifiers != null) {
14671                        final int N = sufficientVerifiers.size();
14672                        if (N == 0) {
14673                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14674                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14675                        } else {
14676                            for (int i = 0; i < N; i++) {
14677                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14678
14679                                final Intent sufficientIntent = new Intent(verification);
14680                                sufficientIntent.setComponent(verifierComponent);
14681                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14682                            }
14683                        }
14684                    }
14685
14686                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14687                            mRequiredVerifierPackage, receivers);
14688                    if (ret == PackageManager.INSTALL_SUCCEEDED
14689                            && mRequiredVerifierPackage != null) {
14690                        Trace.asyncTraceBegin(
14691                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14692                        /*
14693                         * Send the intent to the required verification agent,
14694                         * but only start the verification timeout after the
14695                         * target BroadcastReceivers have run.
14696                         */
14697                        verification.setComponent(requiredVerifierComponent);
14698                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14699                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14700                                new BroadcastReceiver() {
14701                                    @Override
14702                                    public void onReceive(Context context, Intent intent) {
14703                                        final Message msg = mHandler
14704                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14705                                        msg.arg1 = verificationId;
14706                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14707                                    }
14708                                }, null, 0, null, null);
14709
14710                        /*
14711                         * We don't want the copy to proceed until verification
14712                         * succeeds, so null out this field.
14713                         */
14714                        mArgs = null;
14715                    }
14716                } else {
14717                    /*
14718                     * No package verification is enabled, so immediately start
14719                     * the remote call to initiate copy using temporary file.
14720                     */
14721                    ret = args.copyApk(mContainerService, true);
14722                }
14723            }
14724
14725            mRet = ret;
14726        }
14727
14728        @Override
14729        void handleReturnCode() {
14730            // If mArgs is null, then MCS couldn't be reached. When it
14731            // reconnects, it will try again to install. At that point, this
14732            // will succeed.
14733            if (mArgs != null) {
14734                processPendingInstall(mArgs, mRet);
14735            }
14736        }
14737
14738        @Override
14739        void handleServiceError() {
14740            mArgs = createInstallArgs(this);
14741            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14742        }
14743
14744        public boolean isForwardLocked() {
14745            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14746        }
14747    }
14748
14749    /**
14750     * Used during creation of InstallArgs
14751     *
14752     * @param installFlags package installation flags
14753     * @return true if should be installed on external storage
14754     */
14755    private static boolean installOnExternalAsec(int installFlags) {
14756        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14757            return false;
14758        }
14759        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14760            return true;
14761        }
14762        return false;
14763    }
14764
14765    /**
14766     * Used during creation of InstallArgs
14767     *
14768     * @param installFlags package installation flags
14769     * @return true if should be installed as forward locked
14770     */
14771    private static boolean installForwardLocked(int installFlags) {
14772        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14773    }
14774
14775    private InstallArgs createInstallArgs(InstallParams params) {
14776        if (params.move != null) {
14777            return new MoveInstallArgs(params);
14778        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14779            return new AsecInstallArgs(params);
14780        } else {
14781            return new FileInstallArgs(params);
14782        }
14783    }
14784
14785    /**
14786     * Create args that describe an existing installed package. Typically used
14787     * when cleaning up old installs, or used as a move source.
14788     */
14789    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14790            String resourcePath, String[] instructionSets) {
14791        final boolean isInAsec;
14792        if (installOnExternalAsec(installFlags)) {
14793            /* Apps on SD card are always in ASEC containers. */
14794            isInAsec = true;
14795        } else if (installForwardLocked(installFlags)
14796                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14797            /*
14798             * Forward-locked apps are only in ASEC containers if they're the
14799             * new style
14800             */
14801            isInAsec = true;
14802        } else {
14803            isInAsec = false;
14804        }
14805
14806        if (isInAsec) {
14807            return new AsecInstallArgs(codePath, instructionSets,
14808                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14809        } else {
14810            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14811        }
14812    }
14813
14814    static abstract class InstallArgs {
14815        /** @see InstallParams#origin */
14816        final OriginInfo origin;
14817        /** @see InstallParams#move */
14818        final MoveInfo move;
14819
14820        final IPackageInstallObserver2 observer;
14821        // Always refers to PackageManager flags only
14822        final int installFlags;
14823        final String installerPackageName;
14824        final String volumeUuid;
14825        final UserHandle user;
14826        final String abiOverride;
14827        final String[] installGrantPermissions;
14828        /** If non-null, drop an async trace when the install completes */
14829        final String traceMethod;
14830        final int traceCookie;
14831        final Certificate[][] certificates;
14832        final int installReason;
14833
14834        // The list of instruction sets supported by this app. This is currently
14835        // only used during the rmdex() phase to clean up resources. We can get rid of this
14836        // if we move dex files under the common app path.
14837        /* nullable */ String[] instructionSets;
14838
14839        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14840                int installFlags, String installerPackageName, String volumeUuid,
14841                UserHandle user, String[] instructionSets,
14842                String abiOverride, String[] installGrantPermissions,
14843                String traceMethod, int traceCookie, Certificate[][] certificates,
14844                int installReason) {
14845            this.origin = origin;
14846            this.move = move;
14847            this.installFlags = installFlags;
14848            this.observer = observer;
14849            this.installerPackageName = installerPackageName;
14850            this.volumeUuid = volumeUuid;
14851            this.user = user;
14852            this.instructionSets = instructionSets;
14853            this.abiOverride = abiOverride;
14854            this.installGrantPermissions = installGrantPermissions;
14855            this.traceMethod = traceMethod;
14856            this.traceCookie = traceCookie;
14857            this.certificates = certificates;
14858            this.installReason = installReason;
14859        }
14860
14861        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14862        abstract int doPreInstall(int status);
14863
14864        /**
14865         * Rename package into final resting place. All paths on the given
14866         * scanned package should be updated to reflect the rename.
14867         */
14868        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14869        abstract int doPostInstall(int status, int uid);
14870
14871        /** @see PackageSettingBase#codePathString */
14872        abstract String getCodePath();
14873        /** @see PackageSettingBase#resourcePathString */
14874        abstract String getResourcePath();
14875
14876        // Need installer lock especially for dex file removal.
14877        abstract void cleanUpResourcesLI();
14878        abstract boolean doPostDeleteLI(boolean delete);
14879
14880        /**
14881         * Called before the source arguments are copied. This is used mostly
14882         * for MoveParams when it needs to read the source file to put it in the
14883         * destination.
14884         */
14885        int doPreCopy() {
14886            return PackageManager.INSTALL_SUCCEEDED;
14887        }
14888
14889        /**
14890         * Called after the source arguments are copied. This is used mostly for
14891         * MoveParams when it needs to read the source file to put it in the
14892         * destination.
14893         */
14894        int doPostCopy(int uid) {
14895            return PackageManager.INSTALL_SUCCEEDED;
14896        }
14897
14898        protected boolean isFwdLocked() {
14899            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14900        }
14901
14902        protected boolean isExternalAsec() {
14903            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14904        }
14905
14906        protected boolean isEphemeral() {
14907            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14908        }
14909
14910        UserHandle getUser() {
14911            return user;
14912        }
14913    }
14914
14915    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14916        if (!allCodePaths.isEmpty()) {
14917            if (instructionSets == null) {
14918                throw new IllegalStateException("instructionSet == null");
14919            }
14920            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14921            for (String codePath : allCodePaths) {
14922                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14923                    try {
14924                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14925                    } catch (InstallerException ignored) {
14926                    }
14927                }
14928            }
14929        }
14930    }
14931
14932    /**
14933     * Logic to handle installation of non-ASEC applications, including copying
14934     * and renaming logic.
14935     */
14936    class FileInstallArgs extends InstallArgs {
14937        private File codeFile;
14938        private File resourceFile;
14939
14940        // Example topology:
14941        // /data/app/com.example/base.apk
14942        // /data/app/com.example/split_foo.apk
14943        // /data/app/com.example/lib/arm/libfoo.so
14944        // /data/app/com.example/lib/arm64/libfoo.so
14945        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14946
14947        /** New install */
14948        FileInstallArgs(InstallParams params) {
14949            super(params.origin, params.move, params.observer, params.installFlags,
14950                    params.installerPackageName, params.volumeUuid,
14951                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14952                    params.grantedRuntimePermissions,
14953                    params.traceMethod, params.traceCookie, params.certificates,
14954                    params.installReason);
14955            if (isFwdLocked()) {
14956                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14957            }
14958        }
14959
14960        /** Existing install */
14961        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14962            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14963                    null, null, null, 0, null /*certificates*/,
14964                    PackageManager.INSTALL_REASON_UNKNOWN);
14965            this.codeFile = (codePath != null) ? new File(codePath) : null;
14966            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14967        }
14968
14969        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14970            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14971            try {
14972                return doCopyApk(imcs, temp);
14973            } finally {
14974                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14975            }
14976        }
14977
14978        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14979            if (origin.staged) {
14980                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14981                codeFile = origin.file;
14982                resourceFile = origin.file;
14983                return PackageManager.INSTALL_SUCCEEDED;
14984            }
14985
14986            try {
14987                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14988                final File tempDir =
14989                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14990                codeFile = tempDir;
14991                resourceFile = tempDir;
14992            } catch (IOException e) {
14993                Slog.w(TAG, "Failed to create copy file: " + e);
14994                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14995            }
14996
14997            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14998                @Override
14999                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15000                    if (!FileUtils.isValidExtFilename(name)) {
15001                        throw new IllegalArgumentException("Invalid filename: " + name);
15002                    }
15003                    try {
15004                        final File file = new File(codeFile, name);
15005                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15006                                O_RDWR | O_CREAT, 0644);
15007                        Os.chmod(file.getAbsolutePath(), 0644);
15008                        return new ParcelFileDescriptor(fd);
15009                    } catch (ErrnoException e) {
15010                        throw new RemoteException("Failed to open: " + e.getMessage());
15011                    }
15012                }
15013            };
15014
15015            int ret = PackageManager.INSTALL_SUCCEEDED;
15016            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15017            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15018                Slog.e(TAG, "Failed to copy package");
15019                return ret;
15020            }
15021
15022            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15023            NativeLibraryHelper.Handle handle = null;
15024            try {
15025                handle = NativeLibraryHelper.Handle.create(codeFile);
15026                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15027                        abiOverride);
15028            } catch (IOException e) {
15029                Slog.e(TAG, "Copying native libraries failed", e);
15030                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15031            } finally {
15032                IoUtils.closeQuietly(handle);
15033            }
15034
15035            return ret;
15036        }
15037
15038        int doPreInstall(int status) {
15039            if (status != PackageManager.INSTALL_SUCCEEDED) {
15040                cleanUp();
15041            }
15042            return status;
15043        }
15044
15045        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15046            if (status != PackageManager.INSTALL_SUCCEEDED) {
15047                cleanUp();
15048                return false;
15049            }
15050
15051            final File targetDir = codeFile.getParentFile();
15052            final File beforeCodeFile = codeFile;
15053            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15054
15055            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15056            try {
15057                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15058            } catch (ErrnoException e) {
15059                Slog.w(TAG, "Failed to rename", e);
15060                return false;
15061            }
15062
15063            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15064                Slog.w(TAG, "Failed to restorecon");
15065                return false;
15066            }
15067
15068            // Reflect the rename internally
15069            codeFile = afterCodeFile;
15070            resourceFile = afterCodeFile;
15071
15072            // Reflect the rename in scanned details
15073            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15074            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15075                    afterCodeFile, pkg.baseCodePath));
15076            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15077                    afterCodeFile, pkg.splitCodePaths));
15078
15079            // Reflect the rename in app info
15080            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15081            pkg.setApplicationInfoCodePath(pkg.codePath);
15082            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15083            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15084            pkg.setApplicationInfoResourcePath(pkg.codePath);
15085            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15086            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15087
15088            return true;
15089        }
15090
15091        int doPostInstall(int status, int uid) {
15092            if (status != PackageManager.INSTALL_SUCCEEDED) {
15093                cleanUp();
15094            }
15095            return status;
15096        }
15097
15098        @Override
15099        String getCodePath() {
15100            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15101        }
15102
15103        @Override
15104        String getResourcePath() {
15105            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15106        }
15107
15108        private boolean cleanUp() {
15109            if (codeFile == null || !codeFile.exists()) {
15110                return false;
15111            }
15112
15113            removeCodePathLI(codeFile);
15114
15115            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15116                resourceFile.delete();
15117            }
15118
15119            return true;
15120        }
15121
15122        void cleanUpResourcesLI() {
15123            // Try enumerating all code paths before deleting
15124            List<String> allCodePaths = Collections.EMPTY_LIST;
15125            if (codeFile != null && codeFile.exists()) {
15126                try {
15127                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15128                    allCodePaths = pkg.getAllCodePaths();
15129                } catch (PackageParserException e) {
15130                    // Ignored; we tried our best
15131                }
15132            }
15133
15134            cleanUp();
15135            removeDexFiles(allCodePaths, instructionSets);
15136        }
15137
15138        boolean doPostDeleteLI(boolean delete) {
15139            // XXX err, shouldn't we respect the delete flag?
15140            cleanUpResourcesLI();
15141            return true;
15142        }
15143    }
15144
15145    private boolean isAsecExternal(String cid) {
15146        final String asecPath = PackageHelper.getSdFilesystem(cid);
15147        return !asecPath.startsWith(mAsecInternalPath);
15148    }
15149
15150    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15151            PackageManagerException {
15152        if (copyRet < 0) {
15153            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15154                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15155                throw new PackageManagerException(copyRet, message);
15156            }
15157        }
15158    }
15159
15160    /**
15161     * Extract the StorageManagerService "container ID" from the full code path of an
15162     * .apk.
15163     */
15164    static String cidFromCodePath(String fullCodePath) {
15165        int eidx = fullCodePath.lastIndexOf("/");
15166        String subStr1 = fullCodePath.substring(0, eidx);
15167        int sidx = subStr1.lastIndexOf("/");
15168        return subStr1.substring(sidx+1, eidx);
15169    }
15170
15171    /**
15172     * Logic to handle installation of ASEC applications, including copying and
15173     * renaming logic.
15174     */
15175    class AsecInstallArgs extends InstallArgs {
15176        static final String RES_FILE_NAME = "pkg.apk";
15177        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15178
15179        String cid;
15180        String packagePath;
15181        String resourcePath;
15182
15183        /** New install */
15184        AsecInstallArgs(InstallParams params) {
15185            super(params.origin, params.move, params.observer, params.installFlags,
15186                    params.installerPackageName, params.volumeUuid,
15187                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15188                    params.grantedRuntimePermissions,
15189                    params.traceMethod, params.traceCookie, params.certificates,
15190                    params.installReason);
15191        }
15192
15193        /** Existing install */
15194        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15195                        boolean isExternal, boolean isForwardLocked) {
15196            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15197                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15198                    instructionSets, null, null, null, 0, null /*certificates*/,
15199                    PackageManager.INSTALL_REASON_UNKNOWN);
15200            // Hackily pretend we're still looking at a full code path
15201            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15202                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15203            }
15204
15205            // Extract cid from fullCodePath
15206            int eidx = fullCodePath.lastIndexOf("/");
15207            String subStr1 = fullCodePath.substring(0, eidx);
15208            int sidx = subStr1.lastIndexOf("/");
15209            cid = subStr1.substring(sidx+1, eidx);
15210            setMountPath(subStr1);
15211        }
15212
15213        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15214            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15215                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15216                    instructionSets, null, null, null, 0, null /*certificates*/,
15217                    PackageManager.INSTALL_REASON_UNKNOWN);
15218            this.cid = cid;
15219            setMountPath(PackageHelper.getSdDir(cid));
15220        }
15221
15222        void createCopyFile() {
15223            cid = mInstallerService.allocateExternalStageCidLegacy();
15224        }
15225
15226        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15227            if (origin.staged && origin.cid != null) {
15228                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15229                cid = origin.cid;
15230                setMountPath(PackageHelper.getSdDir(cid));
15231                return PackageManager.INSTALL_SUCCEEDED;
15232            }
15233
15234            if (temp) {
15235                createCopyFile();
15236            } else {
15237                /*
15238                 * Pre-emptively destroy the container since it's destroyed if
15239                 * copying fails due to it existing anyway.
15240                 */
15241                PackageHelper.destroySdDir(cid);
15242            }
15243
15244            final String newMountPath = imcs.copyPackageToContainer(
15245                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15246                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15247
15248            if (newMountPath != null) {
15249                setMountPath(newMountPath);
15250                return PackageManager.INSTALL_SUCCEEDED;
15251            } else {
15252                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15253            }
15254        }
15255
15256        @Override
15257        String getCodePath() {
15258            return packagePath;
15259        }
15260
15261        @Override
15262        String getResourcePath() {
15263            return resourcePath;
15264        }
15265
15266        int doPreInstall(int status) {
15267            if (status != PackageManager.INSTALL_SUCCEEDED) {
15268                // Destroy container
15269                PackageHelper.destroySdDir(cid);
15270            } else {
15271                boolean mounted = PackageHelper.isContainerMounted(cid);
15272                if (!mounted) {
15273                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15274                            Process.SYSTEM_UID);
15275                    if (newMountPath != null) {
15276                        setMountPath(newMountPath);
15277                    } else {
15278                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15279                    }
15280                }
15281            }
15282            return status;
15283        }
15284
15285        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15286            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15287            String newMountPath = null;
15288            if (PackageHelper.isContainerMounted(cid)) {
15289                // Unmount the container
15290                if (!PackageHelper.unMountSdDir(cid)) {
15291                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15292                    return false;
15293                }
15294            }
15295            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15296                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15297                        " which might be stale. Will try to clean up.");
15298                // Clean up the stale container and proceed to recreate.
15299                if (!PackageHelper.destroySdDir(newCacheId)) {
15300                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15301                    return false;
15302                }
15303                // Successfully cleaned up stale container. Try to rename again.
15304                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15305                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15306                            + " inspite of cleaning it up.");
15307                    return false;
15308                }
15309            }
15310            if (!PackageHelper.isContainerMounted(newCacheId)) {
15311                Slog.w(TAG, "Mounting container " + newCacheId);
15312                newMountPath = PackageHelper.mountSdDir(newCacheId,
15313                        getEncryptKey(), Process.SYSTEM_UID);
15314            } else {
15315                newMountPath = PackageHelper.getSdDir(newCacheId);
15316            }
15317            if (newMountPath == null) {
15318                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15319                return false;
15320            }
15321            Log.i(TAG, "Succesfully renamed " + cid +
15322                    " to " + newCacheId +
15323                    " at new path: " + newMountPath);
15324            cid = newCacheId;
15325
15326            final File beforeCodeFile = new File(packagePath);
15327            setMountPath(newMountPath);
15328            final File afterCodeFile = new File(packagePath);
15329
15330            // Reflect the rename in scanned details
15331            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15332            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15333                    afterCodeFile, pkg.baseCodePath));
15334            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15335                    afterCodeFile, pkg.splitCodePaths));
15336
15337            // Reflect the rename in app info
15338            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15339            pkg.setApplicationInfoCodePath(pkg.codePath);
15340            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15341            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15342            pkg.setApplicationInfoResourcePath(pkg.codePath);
15343            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15344            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15345
15346            return true;
15347        }
15348
15349        private void setMountPath(String mountPath) {
15350            final File mountFile = new File(mountPath);
15351
15352            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15353            if (monolithicFile.exists()) {
15354                packagePath = monolithicFile.getAbsolutePath();
15355                if (isFwdLocked()) {
15356                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15357                } else {
15358                    resourcePath = packagePath;
15359                }
15360            } else {
15361                packagePath = mountFile.getAbsolutePath();
15362                resourcePath = packagePath;
15363            }
15364        }
15365
15366        int doPostInstall(int status, int uid) {
15367            if (status != PackageManager.INSTALL_SUCCEEDED) {
15368                cleanUp();
15369            } else {
15370                final int groupOwner;
15371                final String protectedFile;
15372                if (isFwdLocked()) {
15373                    groupOwner = UserHandle.getSharedAppGid(uid);
15374                    protectedFile = RES_FILE_NAME;
15375                } else {
15376                    groupOwner = -1;
15377                    protectedFile = null;
15378                }
15379
15380                if (uid < Process.FIRST_APPLICATION_UID
15381                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15382                    Slog.e(TAG, "Failed to finalize " + cid);
15383                    PackageHelper.destroySdDir(cid);
15384                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15385                }
15386
15387                boolean mounted = PackageHelper.isContainerMounted(cid);
15388                if (!mounted) {
15389                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15390                }
15391            }
15392            return status;
15393        }
15394
15395        private void cleanUp() {
15396            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15397
15398            // Destroy secure container
15399            PackageHelper.destroySdDir(cid);
15400        }
15401
15402        private List<String> getAllCodePaths() {
15403            final File codeFile = new File(getCodePath());
15404            if (codeFile != null && codeFile.exists()) {
15405                try {
15406                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15407                    return pkg.getAllCodePaths();
15408                } catch (PackageParserException e) {
15409                    // Ignored; we tried our best
15410                }
15411            }
15412            return Collections.EMPTY_LIST;
15413        }
15414
15415        void cleanUpResourcesLI() {
15416            // Enumerate all code paths before deleting
15417            cleanUpResourcesLI(getAllCodePaths());
15418        }
15419
15420        private void cleanUpResourcesLI(List<String> allCodePaths) {
15421            cleanUp();
15422            removeDexFiles(allCodePaths, instructionSets);
15423        }
15424
15425        String getPackageName() {
15426            return getAsecPackageName(cid);
15427        }
15428
15429        boolean doPostDeleteLI(boolean delete) {
15430            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15431            final List<String> allCodePaths = getAllCodePaths();
15432            boolean mounted = PackageHelper.isContainerMounted(cid);
15433            if (mounted) {
15434                // Unmount first
15435                if (PackageHelper.unMountSdDir(cid)) {
15436                    mounted = false;
15437                }
15438            }
15439            if (!mounted && delete) {
15440                cleanUpResourcesLI(allCodePaths);
15441            }
15442            return !mounted;
15443        }
15444
15445        @Override
15446        int doPreCopy() {
15447            if (isFwdLocked()) {
15448                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15449                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15450                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15451                }
15452            }
15453
15454            return PackageManager.INSTALL_SUCCEEDED;
15455        }
15456
15457        @Override
15458        int doPostCopy(int uid) {
15459            if (isFwdLocked()) {
15460                if (uid < Process.FIRST_APPLICATION_UID
15461                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15462                                RES_FILE_NAME)) {
15463                    Slog.e(TAG, "Failed to finalize " + cid);
15464                    PackageHelper.destroySdDir(cid);
15465                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15466                }
15467            }
15468
15469            return PackageManager.INSTALL_SUCCEEDED;
15470        }
15471    }
15472
15473    /**
15474     * Logic to handle movement of existing installed applications.
15475     */
15476    class MoveInstallArgs extends InstallArgs {
15477        private File codeFile;
15478        private File resourceFile;
15479
15480        /** New install */
15481        MoveInstallArgs(InstallParams params) {
15482            super(params.origin, params.move, params.observer, params.installFlags,
15483                    params.installerPackageName, params.volumeUuid,
15484                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15485                    params.grantedRuntimePermissions,
15486                    params.traceMethod, params.traceCookie, params.certificates,
15487                    params.installReason);
15488        }
15489
15490        int copyApk(IMediaContainerService imcs, boolean temp) {
15491            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15492                    + move.fromUuid + " to " + move.toUuid);
15493            synchronized (mInstaller) {
15494                try {
15495                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15496                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15497                } catch (InstallerException e) {
15498                    Slog.w(TAG, "Failed to move app", e);
15499                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15500                }
15501            }
15502
15503            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15504            resourceFile = codeFile;
15505            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15506
15507            return PackageManager.INSTALL_SUCCEEDED;
15508        }
15509
15510        int doPreInstall(int status) {
15511            if (status != PackageManager.INSTALL_SUCCEEDED) {
15512                cleanUp(move.toUuid);
15513            }
15514            return status;
15515        }
15516
15517        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15518            if (status != PackageManager.INSTALL_SUCCEEDED) {
15519                cleanUp(move.toUuid);
15520                return false;
15521            }
15522
15523            // Reflect the move in app info
15524            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15525            pkg.setApplicationInfoCodePath(pkg.codePath);
15526            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15527            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15528            pkg.setApplicationInfoResourcePath(pkg.codePath);
15529            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15530            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15531
15532            return true;
15533        }
15534
15535        int doPostInstall(int status, int uid) {
15536            if (status == PackageManager.INSTALL_SUCCEEDED) {
15537                cleanUp(move.fromUuid);
15538            } else {
15539                cleanUp(move.toUuid);
15540            }
15541            return status;
15542        }
15543
15544        @Override
15545        String getCodePath() {
15546            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15547        }
15548
15549        @Override
15550        String getResourcePath() {
15551            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15552        }
15553
15554        private boolean cleanUp(String volumeUuid) {
15555            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15556                    move.dataAppName);
15557            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15558            final int[] userIds = sUserManager.getUserIds();
15559            synchronized (mInstallLock) {
15560                // Clean up both app data and code
15561                // All package moves are frozen until finished
15562                for (int userId : userIds) {
15563                    try {
15564                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15565                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15566                    } catch (InstallerException e) {
15567                        Slog.w(TAG, String.valueOf(e));
15568                    }
15569                }
15570                removeCodePathLI(codeFile);
15571            }
15572            return true;
15573        }
15574
15575        void cleanUpResourcesLI() {
15576            throw new UnsupportedOperationException();
15577        }
15578
15579        boolean doPostDeleteLI(boolean delete) {
15580            throw new UnsupportedOperationException();
15581        }
15582    }
15583
15584    static String getAsecPackageName(String packageCid) {
15585        int idx = packageCid.lastIndexOf("-");
15586        if (idx == -1) {
15587            return packageCid;
15588        }
15589        return packageCid.substring(0, idx);
15590    }
15591
15592    // Utility method used to create code paths based on package name and available index.
15593    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15594        String idxStr = "";
15595        int idx = 1;
15596        // Fall back to default value of idx=1 if prefix is not
15597        // part of oldCodePath
15598        if (oldCodePath != null) {
15599            String subStr = oldCodePath;
15600            // Drop the suffix right away
15601            if (suffix != null && subStr.endsWith(suffix)) {
15602                subStr = subStr.substring(0, subStr.length() - suffix.length());
15603            }
15604            // If oldCodePath already contains prefix find out the
15605            // ending index to either increment or decrement.
15606            int sidx = subStr.lastIndexOf(prefix);
15607            if (sidx != -1) {
15608                subStr = subStr.substring(sidx + prefix.length());
15609                if (subStr != null) {
15610                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15611                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15612                    }
15613                    try {
15614                        idx = Integer.parseInt(subStr);
15615                        if (idx <= 1) {
15616                            idx++;
15617                        } else {
15618                            idx--;
15619                        }
15620                    } catch(NumberFormatException e) {
15621                    }
15622                }
15623            }
15624        }
15625        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15626        return prefix + idxStr;
15627    }
15628
15629    private File getNextCodePath(File targetDir, String packageName) {
15630        File result;
15631        SecureRandom random = new SecureRandom();
15632        byte[] bytes = new byte[16];
15633        do {
15634            random.nextBytes(bytes);
15635            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15636            result = new File(targetDir, packageName + "-" + suffix);
15637        } while (result.exists());
15638        return result;
15639    }
15640
15641    // Utility method that returns the relative package path with respect
15642    // to the installation directory. Like say for /data/data/com.test-1.apk
15643    // string com.test-1 is returned.
15644    static String deriveCodePathName(String codePath) {
15645        if (codePath == null) {
15646            return null;
15647        }
15648        final File codeFile = new File(codePath);
15649        final String name = codeFile.getName();
15650        if (codeFile.isDirectory()) {
15651            return name;
15652        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15653            final int lastDot = name.lastIndexOf('.');
15654            return name.substring(0, lastDot);
15655        } else {
15656            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15657            return null;
15658        }
15659    }
15660
15661    static class PackageInstalledInfo {
15662        String name;
15663        int uid;
15664        // The set of users that originally had this package installed.
15665        int[] origUsers;
15666        // The set of users that now have this package installed.
15667        int[] newUsers;
15668        PackageParser.Package pkg;
15669        int returnCode;
15670        String returnMsg;
15671        PackageRemovedInfo removedInfo;
15672        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15673
15674        public void setError(int code, String msg) {
15675            setReturnCode(code);
15676            setReturnMessage(msg);
15677            Slog.w(TAG, msg);
15678        }
15679
15680        public void setError(String msg, PackageParserException e) {
15681            setReturnCode(e.error);
15682            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15683            Slog.w(TAG, msg, e);
15684        }
15685
15686        public void setError(String msg, PackageManagerException e) {
15687            returnCode = e.error;
15688            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15689            Slog.w(TAG, msg, e);
15690        }
15691
15692        public void setReturnCode(int returnCode) {
15693            this.returnCode = returnCode;
15694            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15695            for (int i = 0; i < childCount; i++) {
15696                addedChildPackages.valueAt(i).returnCode = returnCode;
15697            }
15698        }
15699
15700        private void setReturnMessage(String returnMsg) {
15701            this.returnMsg = returnMsg;
15702            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15703            for (int i = 0; i < childCount; i++) {
15704                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15705            }
15706        }
15707
15708        // In some error cases we want to convey more info back to the observer
15709        String origPackage;
15710        String origPermission;
15711    }
15712
15713    /*
15714     * Install a non-existing package.
15715     */
15716    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15717            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15718            PackageInstalledInfo res, int installReason) {
15719        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15720
15721        // Remember this for later, in case we need to rollback this install
15722        String pkgName = pkg.packageName;
15723
15724        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15725
15726        synchronized(mPackages) {
15727            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15728            if (renamedPackage != null) {
15729                // A package with the same name is already installed, though
15730                // it has been renamed to an older name.  The package we
15731                // are trying to install should be installed as an update to
15732                // the existing one, but that has not been requested, so bail.
15733                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15734                        + " without first uninstalling package running as "
15735                        + renamedPackage);
15736                return;
15737            }
15738            if (mPackages.containsKey(pkgName)) {
15739                // Don't allow installation over an existing package with the same name.
15740                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15741                        + " without first uninstalling.");
15742                return;
15743            }
15744        }
15745
15746        try {
15747            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15748                    System.currentTimeMillis(), user);
15749
15750            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15751
15752            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15753                prepareAppDataAfterInstallLIF(newPackage);
15754
15755            } else {
15756                // Remove package from internal structures, but keep around any
15757                // data that might have already existed
15758                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15759                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15760            }
15761        } catch (PackageManagerException e) {
15762            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15763        }
15764
15765        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15766    }
15767
15768    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15769        // Can't rotate keys during boot or if sharedUser.
15770        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15771                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15772            return false;
15773        }
15774        // app is using upgradeKeySets; make sure all are valid
15775        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15776        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15777        for (int i = 0; i < upgradeKeySets.length; i++) {
15778            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15779                Slog.wtf(TAG, "Package "
15780                         + (oldPs.name != null ? oldPs.name : "<null>")
15781                         + " contains upgrade-key-set reference to unknown key-set: "
15782                         + upgradeKeySets[i]
15783                         + " reverting to signatures check.");
15784                return false;
15785            }
15786        }
15787        return true;
15788    }
15789
15790    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15791        // Upgrade keysets are being used.  Determine if new package has a superset of the
15792        // required keys.
15793        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15794        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15795        for (int i = 0; i < upgradeKeySets.length; i++) {
15796            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15797            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15798                return true;
15799            }
15800        }
15801        return false;
15802    }
15803
15804    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15805        try (DigestInputStream digestStream =
15806                new DigestInputStream(new FileInputStream(file), digest)) {
15807            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15808        }
15809    }
15810
15811    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15812            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15813            int installReason) {
15814        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15815
15816        final PackageParser.Package oldPackage;
15817        final String pkgName = pkg.packageName;
15818        final int[] allUsers;
15819        final int[] installedUsers;
15820
15821        synchronized(mPackages) {
15822            oldPackage = mPackages.get(pkgName);
15823            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15824
15825            // don't allow upgrade to target a release SDK from a pre-release SDK
15826            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15827                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15828            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15829                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15830            if (oldTargetsPreRelease
15831                    && !newTargetsPreRelease
15832                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15833                Slog.w(TAG, "Can't install package targeting released sdk");
15834                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15835                return;
15836            }
15837
15838            // don't allow an upgrade from full to ephemeral
15839            final boolean oldIsEphemeral = oldPackage.applicationInfo.isInstantApp();
15840            if (isEphemeral && !oldIsEphemeral) {
15841                // can't downgrade from full to ephemeral
15842                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15843                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15844                return;
15845            }
15846
15847            // verify signatures are valid
15848            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15849            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15850                if (!checkUpgradeKeySetLP(ps, pkg)) {
15851                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15852                            "New package not signed by keys specified by upgrade-keysets: "
15853                                    + pkgName);
15854                    return;
15855                }
15856            } else {
15857                // default to original signature matching
15858                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15859                        != PackageManager.SIGNATURE_MATCH) {
15860                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15861                            "New package has a different signature: " + pkgName);
15862                    return;
15863                }
15864            }
15865
15866            // don't allow a system upgrade unless the upgrade hash matches
15867            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15868                byte[] digestBytes = null;
15869                try {
15870                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15871                    updateDigest(digest, new File(pkg.baseCodePath));
15872                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15873                        for (String path : pkg.splitCodePaths) {
15874                            updateDigest(digest, new File(path));
15875                        }
15876                    }
15877                    digestBytes = digest.digest();
15878                } catch (NoSuchAlgorithmException | IOException e) {
15879                    res.setError(INSTALL_FAILED_INVALID_APK,
15880                            "Could not compute hash: " + pkgName);
15881                    return;
15882                }
15883                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15884                    res.setError(INSTALL_FAILED_INVALID_APK,
15885                            "New package fails restrict-update check: " + pkgName);
15886                    return;
15887                }
15888                // retain upgrade restriction
15889                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15890            }
15891
15892            // Check for shared user id changes
15893            String invalidPackageName =
15894                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15895            if (invalidPackageName != null) {
15896                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15897                        "Package " + invalidPackageName + " tried to change user "
15898                                + oldPackage.mSharedUserId);
15899                return;
15900            }
15901
15902            // In case of rollback, remember per-user/profile install state
15903            allUsers = sUserManager.getUserIds();
15904            installedUsers = ps.queryInstalledUsers(allUsers, true);
15905        }
15906
15907        // Update what is removed
15908        res.removedInfo = new PackageRemovedInfo();
15909        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15910        res.removedInfo.removedPackage = oldPackage.packageName;
15911        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15912        res.removedInfo.isUpdate = true;
15913        res.removedInfo.origUsers = installedUsers;
15914        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15915        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15916        for (int i = 0; i < installedUsers.length; i++) {
15917            final int userId = installedUsers[i];
15918            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15919        }
15920
15921        final int childCount = (oldPackage.childPackages != null)
15922                ? oldPackage.childPackages.size() : 0;
15923        for (int i = 0; i < childCount; i++) {
15924            boolean childPackageUpdated = false;
15925            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15926            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15927            if (res.addedChildPackages != null) {
15928                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15929                if (childRes != null) {
15930                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15931                    childRes.removedInfo.removedPackage = childPkg.packageName;
15932                    childRes.removedInfo.isUpdate = true;
15933                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15934                    childPackageUpdated = true;
15935                }
15936            }
15937            if (!childPackageUpdated) {
15938                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15939                childRemovedRes.removedPackage = childPkg.packageName;
15940                childRemovedRes.isUpdate = false;
15941                childRemovedRes.dataRemoved = true;
15942                synchronized (mPackages) {
15943                    if (childPs != null) {
15944                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15945                    }
15946                }
15947                if (res.removedInfo.removedChildPackages == null) {
15948                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15949                }
15950                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15951            }
15952        }
15953
15954        boolean sysPkg = (isSystemApp(oldPackage));
15955        if (sysPkg) {
15956            // Set the system/privileged flags as needed
15957            final boolean privileged =
15958                    (oldPackage.applicationInfo.privateFlags
15959                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15960            final int systemPolicyFlags = policyFlags
15961                    | PackageParser.PARSE_IS_SYSTEM
15962                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15963
15964            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15965                    user, allUsers, installerPackageName, res, installReason);
15966        } else {
15967            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15968                    user, allUsers, installerPackageName, res, installReason);
15969        }
15970    }
15971
15972    public List<String> getPreviousCodePaths(String packageName) {
15973        final PackageSetting ps = mSettings.mPackages.get(packageName);
15974        final List<String> result = new ArrayList<String>();
15975        if (ps != null && ps.oldCodePaths != null) {
15976            result.addAll(ps.oldCodePaths);
15977        }
15978        return result;
15979    }
15980
15981    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15982            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15983            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15984            int installReason) {
15985        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15986                + deletedPackage);
15987
15988        String pkgName = deletedPackage.packageName;
15989        boolean deletedPkg = true;
15990        boolean addedPkg = false;
15991        boolean updatedSettings = false;
15992        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15993        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15994                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15995
15996        final long origUpdateTime = (pkg.mExtras != null)
15997                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15998
15999        // First delete the existing package while retaining the data directory
16000        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16001                res.removedInfo, true, pkg)) {
16002            // If the existing package wasn't successfully deleted
16003            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16004            deletedPkg = false;
16005        } else {
16006            // Successfully deleted the old package; proceed with replace.
16007
16008            // If deleted package lived in a container, give users a chance to
16009            // relinquish resources before killing.
16010            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16011                if (DEBUG_INSTALL) {
16012                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16013                }
16014                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16015                final ArrayList<String> pkgList = new ArrayList<String>(1);
16016                pkgList.add(deletedPackage.applicationInfo.packageName);
16017                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16018            }
16019
16020            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16021                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16022            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16023
16024            try {
16025                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16026                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16027                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16028                        installReason);
16029
16030                // Update the in-memory copy of the previous code paths.
16031                PackageSetting ps = mSettings.mPackages.get(pkgName);
16032                if (!killApp) {
16033                    if (ps.oldCodePaths == null) {
16034                        ps.oldCodePaths = new ArraySet<>();
16035                    }
16036                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16037                    if (deletedPackage.splitCodePaths != null) {
16038                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16039                    }
16040                } else {
16041                    ps.oldCodePaths = null;
16042                }
16043                if (ps.childPackageNames != null) {
16044                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16045                        final String childPkgName = ps.childPackageNames.get(i);
16046                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16047                        childPs.oldCodePaths = ps.oldCodePaths;
16048                    }
16049                }
16050                prepareAppDataAfterInstallLIF(newPackage);
16051                addedPkg = true;
16052            } catch (PackageManagerException e) {
16053                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16054            }
16055        }
16056
16057        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16058            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16059
16060            // Revert all internal state mutations and added folders for the failed install
16061            if (addedPkg) {
16062                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16063                        res.removedInfo, true, null);
16064            }
16065
16066            // Restore the old package
16067            if (deletedPkg) {
16068                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16069                File restoreFile = new File(deletedPackage.codePath);
16070                // Parse old package
16071                boolean oldExternal = isExternal(deletedPackage);
16072                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16073                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16074                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16075                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16076                try {
16077                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16078                            null);
16079                } catch (PackageManagerException e) {
16080                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16081                            + e.getMessage());
16082                    return;
16083                }
16084
16085                synchronized (mPackages) {
16086                    // Ensure the installer package name up to date
16087                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16088
16089                    // Update permissions for restored package
16090                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16091
16092                    mSettings.writeLPr();
16093                }
16094
16095                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16096            }
16097        } else {
16098            synchronized (mPackages) {
16099                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16100                if (ps != null) {
16101                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16102                    if (res.removedInfo.removedChildPackages != null) {
16103                        final int childCount = res.removedInfo.removedChildPackages.size();
16104                        // Iterate in reverse as we may modify the collection
16105                        for (int i = childCount - 1; i >= 0; i--) {
16106                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16107                            if (res.addedChildPackages.containsKey(childPackageName)) {
16108                                res.removedInfo.removedChildPackages.removeAt(i);
16109                            } else {
16110                                PackageRemovedInfo childInfo = res.removedInfo
16111                                        .removedChildPackages.valueAt(i);
16112                                childInfo.removedForAllUsers = mPackages.get(
16113                                        childInfo.removedPackage) == null;
16114                            }
16115                        }
16116                    }
16117                }
16118            }
16119        }
16120    }
16121
16122    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16123            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16124            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16125            int installReason) {
16126        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16127                + ", old=" + deletedPackage);
16128
16129        final boolean disabledSystem;
16130
16131        // Remove existing system package
16132        removePackageLI(deletedPackage, true);
16133
16134        synchronized (mPackages) {
16135            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16136        }
16137        if (!disabledSystem) {
16138            // We didn't need to disable the .apk as a current system package,
16139            // which means we are replacing another update that is already
16140            // installed.  We need to make sure to delete the older one's .apk.
16141            res.removedInfo.args = createInstallArgsForExisting(0,
16142                    deletedPackage.applicationInfo.getCodePath(),
16143                    deletedPackage.applicationInfo.getResourcePath(),
16144                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16145        } else {
16146            res.removedInfo.args = null;
16147        }
16148
16149        // Successfully disabled the old package. Now proceed with re-installation
16150        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16151                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16152        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16153
16154        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16155        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16156                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16157
16158        PackageParser.Package newPackage = null;
16159        try {
16160            // Add the package to the internal data structures
16161            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16162
16163            // Set the update and install times
16164            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16165            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16166                    System.currentTimeMillis());
16167
16168            // Update the package dynamic state if succeeded
16169            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16170                // Now that the install succeeded make sure we remove data
16171                // directories for any child package the update removed.
16172                final int deletedChildCount = (deletedPackage.childPackages != null)
16173                        ? deletedPackage.childPackages.size() : 0;
16174                final int newChildCount = (newPackage.childPackages != null)
16175                        ? newPackage.childPackages.size() : 0;
16176                for (int i = 0; i < deletedChildCount; i++) {
16177                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16178                    boolean childPackageDeleted = true;
16179                    for (int j = 0; j < newChildCount; j++) {
16180                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16181                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16182                            childPackageDeleted = false;
16183                            break;
16184                        }
16185                    }
16186                    if (childPackageDeleted) {
16187                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16188                                deletedChildPkg.packageName);
16189                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16190                            PackageRemovedInfo removedChildRes = res.removedInfo
16191                                    .removedChildPackages.get(deletedChildPkg.packageName);
16192                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16193                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16194                        }
16195                    }
16196                }
16197
16198                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16199                        installReason);
16200                prepareAppDataAfterInstallLIF(newPackage);
16201            }
16202        } catch (PackageManagerException e) {
16203            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16204            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16205        }
16206
16207        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16208            // Re installation failed. Restore old information
16209            // Remove new pkg information
16210            if (newPackage != null) {
16211                removeInstalledPackageLI(newPackage, true);
16212            }
16213            // Add back the old system package
16214            try {
16215                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16216            } catch (PackageManagerException e) {
16217                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16218            }
16219
16220            synchronized (mPackages) {
16221                if (disabledSystem) {
16222                    enableSystemPackageLPw(deletedPackage);
16223                }
16224
16225                // Ensure the installer package name up to date
16226                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16227
16228                // Update permissions for restored package
16229                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16230
16231                mSettings.writeLPr();
16232            }
16233
16234            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16235                    + " after failed upgrade");
16236        }
16237    }
16238
16239    /**
16240     * Checks whether the parent or any of the child packages have a change shared
16241     * user. For a package to be a valid update the shred users of the parent and
16242     * the children should match. We may later support changing child shared users.
16243     * @param oldPkg The updated package.
16244     * @param newPkg The update package.
16245     * @return The shared user that change between the versions.
16246     */
16247    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16248            PackageParser.Package newPkg) {
16249        // Check parent shared user
16250        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16251            return newPkg.packageName;
16252        }
16253        // Check child shared users
16254        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16255        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16256        for (int i = 0; i < newChildCount; i++) {
16257            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16258            // If this child was present, did it have the same shared user?
16259            for (int j = 0; j < oldChildCount; j++) {
16260                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16261                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16262                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16263                    return newChildPkg.packageName;
16264                }
16265            }
16266        }
16267        return null;
16268    }
16269
16270    private void removeNativeBinariesLI(PackageSetting ps) {
16271        // Remove the lib path for the parent package
16272        if (ps != null) {
16273            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16274            // Remove the lib path for the child packages
16275            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16276            for (int i = 0; i < childCount; i++) {
16277                PackageSetting childPs = null;
16278                synchronized (mPackages) {
16279                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16280                }
16281                if (childPs != null) {
16282                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16283                            .legacyNativeLibraryPathString);
16284                }
16285            }
16286        }
16287    }
16288
16289    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16290        // Enable the parent package
16291        mSettings.enableSystemPackageLPw(pkg.packageName);
16292        // Enable the child packages
16293        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16294        for (int i = 0; i < childCount; i++) {
16295            PackageParser.Package childPkg = pkg.childPackages.get(i);
16296            mSettings.enableSystemPackageLPw(childPkg.packageName);
16297        }
16298    }
16299
16300    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16301            PackageParser.Package newPkg) {
16302        // Disable the parent package (parent always replaced)
16303        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16304        // Disable the child packages
16305        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16306        for (int i = 0; i < childCount; i++) {
16307            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16308            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16309            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16310        }
16311        return disabled;
16312    }
16313
16314    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16315            String installerPackageName) {
16316        // Enable the parent package
16317        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16318        // Enable the child packages
16319        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16320        for (int i = 0; i < childCount; i++) {
16321            PackageParser.Package childPkg = pkg.childPackages.get(i);
16322            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16323        }
16324    }
16325
16326    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16327        // Collect all used permissions in the UID
16328        ArraySet<String> usedPermissions = new ArraySet<>();
16329        final int packageCount = su.packages.size();
16330        for (int i = 0; i < packageCount; i++) {
16331            PackageSetting ps = su.packages.valueAt(i);
16332            if (ps.pkg == null) {
16333                continue;
16334            }
16335            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16336            for (int j = 0; j < requestedPermCount; j++) {
16337                String permission = ps.pkg.requestedPermissions.get(j);
16338                BasePermission bp = mSettings.mPermissions.get(permission);
16339                if (bp != null) {
16340                    usedPermissions.add(permission);
16341                }
16342            }
16343        }
16344
16345        PermissionsState permissionsState = su.getPermissionsState();
16346        // Prune install permissions
16347        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16348        final int installPermCount = installPermStates.size();
16349        for (int i = installPermCount - 1; i >= 0;  i--) {
16350            PermissionState permissionState = installPermStates.get(i);
16351            if (!usedPermissions.contains(permissionState.getName())) {
16352                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16353                if (bp != null) {
16354                    permissionsState.revokeInstallPermission(bp);
16355                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16356                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16357                }
16358            }
16359        }
16360
16361        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16362
16363        // Prune runtime permissions
16364        for (int userId : allUserIds) {
16365            List<PermissionState> runtimePermStates = permissionsState
16366                    .getRuntimePermissionStates(userId);
16367            final int runtimePermCount = runtimePermStates.size();
16368            for (int i = runtimePermCount - 1; i >= 0; i--) {
16369                PermissionState permissionState = runtimePermStates.get(i);
16370                if (!usedPermissions.contains(permissionState.getName())) {
16371                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16372                    if (bp != null) {
16373                        permissionsState.revokeRuntimePermission(bp, userId);
16374                        permissionsState.updatePermissionFlags(bp, userId,
16375                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16376                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16377                                runtimePermissionChangedUserIds, userId);
16378                    }
16379                }
16380            }
16381        }
16382
16383        return runtimePermissionChangedUserIds;
16384    }
16385
16386    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16387            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16388        // Update the parent package setting
16389        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16390                res, user, installReason);
16391        // Update the child packages setting
16392        final int childCount = (newPackage.childPackages != null)
16393                ? newPackage.childPackages.size() : 0;
16394        for (int i = 0; i < childCount; i++) {
16395            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16396            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16397            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16398                    childRes.origUsers, childRes, user, installReason);
16399        }
16400    }
16401
16402    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16403            String installerPackageName, int[] allUsers, int[] installedForUsers,
16404            PackageInstalledInfo res, UserHandle user, int installReason) {
16405        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16406
16407        String pkgName = newPackage.packageName;
16408        synchronized (mPackages) {
16409            //write settings. the installStatus will be incomplete at this stage.
16410            //note that the new package setting would have already been
16411            //added to mPackages. It hasn't been persisted yet.
16412            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16413            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16414            mSettings.writeLPr();
16415            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16416        }
16417
16418        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16419        synchronized (mPackages) {
16420            updatePermissionsLPw(newPackage.packageName, newPackage,
16421                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16422                            ? UPDATE_PERMISSIONS_ALL : 0));
16423            // For system-bundled packages, we assume that installing an upgraded version
16424            // of the package implies that the user actually wants to run that new code,
16425            // so we enable the package.
16426            PackageSetting ps = mSettings.mPackages.get(pkgName);
16427            final int userId = user.getIdentifier();
16428            if (ps != null) {
16429                if (isSystemApp(newPackage)) {
16430                    if (DEBUG_INSTALL) {
16431                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16432                    }
16433                    // Enable system package for requested users
16434                    if (res.origUsers != null) {
16435                        for (int origUserId : res.origUsers) {
16436                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16437                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16438                                        origUserId, installerPackageName);
16439                            }
16440                        }
16441                    }
16442                    // Also convey the prior install/uninstall state
16443                    if (allUsers != null && installedForUsers != null) {
16444                        for (int currentUserId : allUsers) {
16445                            final boolean installed = ArrayUtils.contains(
16446                                    installedForUsers, currentUserId);
16447                            if (DEBUG_INSTALL) {
16448                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16449                            }
16450                            ps.setInstalled(installed, currentUserId);
16451                        }
16452                        // these install state changes will be persisted in the
16453                        // upcoming call to mSettings.writeLPr().
16454                    }
16455                }
16456                // It's implied that when a user requests installation, they want the app to be
16457                // installed and enabled.
16458                if (userId != UserHandle.USER_ALL) {
16459                    ps.setInstalled(true, userId);
16460                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16461                }
16462
16463                // When replacing an existing package, preserve the original install reason for all
16464                // users that had the package installed before.
16465                final Set<Integer> previousUserIds = new ArraySet<>();
16466                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16467                    final int installReasonCount = res.removedInfo.installReasons.size();
16468                    for (int i = 0; i < installReasonCount; i++) {
16469                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16470                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16471                        ps.setInstallReason(previousInstallReason, previousUserId);
16472                        previousUserIds.add(previousUserId);
16473                    }
16474                }
16475
16476                // Set install reason for users that are having the package newly installed.
16477                if (userId == UserHandle.USER_ALL) {
16478                    for (int currentUserId : sUserManager.getUserIds()) {
16479                        if (!previousUserIds.contains(currentUserId)) {
16480                            ps.setInstallReason(installReason, currentUserId);
16481                        }
16482                    }
16483                } else if (!previousUserIds.contains(userId)) {
16484                    ps.setInstallReason(installReason, userId);
16485                }
16486            }
16487            res.name = pkgName;
16488            res.uid = newPackage.applicationInfo.uid;
16489            res.pkg = newPackage;
16490            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16491            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16492            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16493            //to update install status
16494            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16495            mSettings.writeLPr();
16496            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16497        }
16498
16499        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16500    }
16501
16502    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16503        try {
16504            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16505            installPackageLI(args, res);
16506        } finally {
16507            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16508        }
16509    }
16510
16511    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16512        final int installFlags = args.installFlags;
16513        final String installerPackageName = args.installerPackageName;
16514        final String volumeUuid = args.volumeUuid;
16515        final File tmpPackageFile = new File(args.getCodePath());
16516        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16517        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16518                || (args.volumeUuid != null));
16519        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16520        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16521        boolean replace = false;
16522        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16523        if (args.move != null) {
16524            // moving a complete application; perform an initial scan on the new install location
16525            scanFlags |= SCAN_INITIAL;
16526        }
16527        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16528            scanFlags |= SCAN_DONT_KILL_APP;
16529        }
16530
16531        // Result object to be returned
16532        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16533
16534        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16535
16536        // Sanity check
16537        if (ephemeral && (forwardLocked || onExternal)) {
16538            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16539                    + " external=" + onExternal);
16540            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16541            return;
16542        }
16543
16544        // Retrieve PackageSettings and parse package
16545        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16546                | PackageParser.PARSE_ENFORCE_CODE
16547                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16548                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16549                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16550                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16551        PackageParser pp = new PackageParser();
16552        pp.setSeparateProcesses(mSeparateProcesses);
16553        pp.setDisplayMetrics(mMetrics);
16554
16555        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16556        final PackageParser.Package pkg;
16557        try {
16558            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16559        } catch (PackageParserException e) {
16560            res.setError("Failed parse during installPackageLI", e);
16561            return;
16562        } finally {
16563            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16564        }
16565
16566//        // Ephemeral apps must have target SDK >= O.
16567//        // TODO: Update conditional and error message when O gets locked down
16568//        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16569//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16570//                    "Ephemeral apps must have target SDK version of at least O");
16571//            return;
16572//        }
16573
16574        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16575            // Static shared libraries have synthetic package names
16576            renameStaticSharedLibraryPackage(pkg);
16577
16578            // No static shared libs on external storage
16579            if (onExternal) {
16580                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16581                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16582                        "Packages declaring static-shared libs cannot be updated");
16583                return;
16584            }
16585        }
16586
16587        // If we are installing a clustered package add results for the children
16588        if (pkg.childPackages != null) {
16589            synchronized (mPackages) {
16590                final int childCount = pkg.childPackages.size();
16591                for (int i = 0; i < childCount; i++) {
16592                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16593                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16594                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16595                    childRes.pkg = childPkg;
16596                    childRes.name = childPkg.packageName;
16597                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16598                    if (childPs != null) {
16599                        childRes.origUsers = childPs.queryInstalledUsers(
16600                                sUserManager.getUserIds(), true);
16601                    }
16602                    if ((mPackages.containsKey(childPkg.packageName))) {
16603                        childRes.removedInfo = new PackageRemovedInfo();
16604                        childRes.removedInfo.removedPackage = childPkg.packageName;
16605                    }
16606                    if (res.addedChildPackages == null) {
16607                        res.addedChildPackages = new ArrayMap<>();
16608                    }
16609                    res.addedChildPackages.put(childPkg.packageName, childRes);
16610                }
16611            }
16612        }
16613
16614        // If package doesn't declare API override, mark that we have an install
16615        // time CPU ABI override.
16616        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16617            pkg.cpuAbiOverride = args.abiOverride;
16618        }
16619
16620        String pkgName = res.name = pkg.packageName;
16621        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16622            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16623                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16624                return;
16625            }
16626        }
16627
16628        try {
16629            // either use what we've been given or parse directly from the APK
16630            if (args.certificates != null) {
16631                try {
16632                    PackageParser.populateCertificates(pkg, args.certificates);
16633                } catch (PackageParserException e) {
16634                    // there was something wrong with the certificates we were given;
16635                    // try to pull them from the APK
16636                    PackageParser.collectCertificates(pkg, parseFlags);
16637                }
16638            } else {
16639                PackageParser.collectCertificates(pkg, parseFlags);
16640            }
16641        } catch (PackageParserException e) {
16642            res.setError("Failed collect during installPackageLI", e);
16643            return;
16644        }
16645
16646        // Get rid of all references to package scan path via parser.
16647        pp = null;
16648        String oldCodePath = null;
16649        boolean systemApp = false;
16650        synchronized (mPackages) {
16651            // Check if installing already existing package
16652            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16653                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16654                if (pkg.mOriginalPackages != null
16655                        && pkg.mOriginalPackages.contains(oldName)
16656                        && mPackages.containsKey(oldName)) {
16657                    // This package is derived from an original package,
16658                    // and this device has been updating from that original
16659                    // name.  We must continue using the original name, so
16660                    // rename the new package here.
16661                    pkg.setPackageName(oldName);
16662                    pkgName = pkg.packageName;
16663                    replace = true;
16664                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16665                            + oldName + " pkgName=" + pkgName);
16666                } else if (mPackages.containsKey(pkgName)) {
16667                    // This package, under its official name, already exists
16668                    // on the device; we should replace it.
16669                    replace = true;
16670                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16671                }
16672
16673                // Child packages are installed through the parent package
16674                if (pkg.parentPackage != null) {
16675                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16676                            "Package " + pkg.packageName + " is child of package "
16677                                    + pkg.parentPackage.parentPackage + ". Child packages "
16678                                    + "can be updated only through the parent package.");
16679                    return;
16680                }
16681
16682                if (replace) {
16683                    // Prevent apps opting out from runtime permissions
16684                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16685                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16686                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16687                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16688                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16689                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16690                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16691                                        + " doesn't support runtime permissions but the old"
16692                                        + " target SDK " + oldTargetSdk + " does.");
16693                        return;
16694                    }
16695
16696                    // Prevent installing of child packages
16697                    if (oldPackage.parentPackage != null) {
16698                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16699                                "Package " + pkg.packageName + " is child of package "
16700                                        + oldPackage.parentPackage + ". Child packages "
16701                                        + "can be updated only through the parent package.");
16702                        return;
16703                    }
16704                }
16705            }
16706
16707            PackageSetting ps = mSettings.mPackages.get(pkgName);
16708            if (ps != null) {
16709                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16710
16711                // Static shared libs have same package with different versions where
16712                // we internally use a synthetic package name to allow multiple versions
16713                // of the same package, therefore we need to compare signatures against
16714                // the package setting for the latest library version.
16715                PackageSetting signatureCheckPs = ps;
16716                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16717                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16718                    if (libraryEntry != null) {
16719                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16720                    }
16721                }
16722
16723                // Quick sanity check that we're signed correctly if updating;
16724                // we'll check this again later when scanning, but we want to
16725                // bail early here before tripping over redefined permissions.
16726                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16727                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16728                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16729                                + pkg.packageName + " upgrade keys do not match the "
16730                                + "previously installed version");
16731                        return;
16732                    }
16733                } else {
16734                    try {
16735                        verifySignaturesLP(signatureCheckPs, pkg);
16736                    } catch (PackageManagerException e) {
16737                        res.setError(e.error, e.getMessage());
16738                        return;
16739                    }
16740                }
16741
16742                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16743                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16744                    systemApp = (ps.pkg.applicationInfo.flags &
16745                            ApplicationInfo.FLAG_SYSTEM) != 0;
16746                }
16747                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16748            }
16749
16750            // Check whether the newly-scanned package wants to define an already-defined perm
16751            int N = pkg.permissions.size();
16752            for (int i = N-1; i >= 0; i--) {
16753                PackageParser.Permission perm = pkg.permissions.get(i);
16754                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16755                if (bp != null) {
16756                    // If the defining package is signed with our cert, it's okay.  This
16757                    // also includes the "updating the same package" case, of course.
16758                    // "updating same package" could also involve key-rotation.
16759                    final boolean sigsOk;
16760                    if (bp.sourcePackage.equals(pkg.packageName)
16761                            && (bp.packageSetting instanceof PackageSetting)
16762                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16763                                    scanFlags))) {
16764                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16765                    } else {
16766                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16767                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16768                    }
16769                    if (!sigsOk) {
16770                        // If the owning package is the system itself, we log but allow
16771                        // install to proceed; we fail the install on all other permission
16772                        // redefinitions.
16773                        if (!bp.sourcePackage.equals("android")) {
16774                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16775                                    + pkg.packageName + " attempting to redeclare permission "
16776                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16777                            res.origPermission = perm.info.name;
16778                            res.origPackage = bp.sourcePackage;
16779                            return;
16780                        } else {
16781                            Slog.w(TAG, "Package " + pkg.packageName
16782                                    + " attempting to redeclare system permission "
16783                                    + perm.info.name + "; ignoring new declaration");
16784                            pkg.permissions.remove(i);
16785                        }
16786                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16787                        // Prevent apps to change protection level to dangerous from any other
16788                        // type as this would allow a privilege escalation where an app adds a
16789                        // normal/signature permission in other app's group and later redefines
16790                        // it as dangerous leading to the group auto-grant.
16791                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16792                                == PermissionInfo.PROTECTION_DANGEROUS) {
16793                            if (bp != null && !bp.isRuntime()) {
16794                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16795                                        + "non-runtime permission " + perm.info.name
16796                                        + " to runtime; keeping old protection level");
16797                                perm.info.protectionLevel = bp.protectionLevel;
16798                            }
16799                        }
16800                    }
16801                }
16802            }
16803        }
16804
16805        if (systemApp) {
16806            if (onExternal) {
16807                // Abort update; system app can't be replaced with app on sdcard
16808                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16809                        "Cannot install updates to system apps on sdcard");
16810                return;
16811            } else if (ephemeral) {
16812                // Abort update; system app can't be replaced with an ephemeral app
16813                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16814                        "Cannot update a system app with an ephemeral app");
16815                return;
16816            }
16817        }
16818
16819        if (args.move != null) {
16820            // We did an in-place move, so dex is ready to roll
16821            scanFlags |= SCAN_NO_DEX;
16822            scanFlags |= SCAN_MOVE;
16823
16824            synchronized (mPackages) {
16825                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16826                if (ps == null) {
16827                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16828                            "Missing settings for moved package " + pkgName);
16829                }
16830
16831                // We moved the entire application as-is, so bring over the
16832                // previously derived ABI information.
16833                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16834                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16835            }
16836
16837        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16838            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16839            scanFlags |= SCAN_NO_DEX;
16840
16841            try {
16842                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16843                    args.abiOverride : pkg.cpuAbiOverride);
16844                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16845                        true /*extractLibs*/, mAppLib32InstallDir);
16846            } catch (PackageManagerException pme) {
16847                Slog.e(TAG, "Error deriving application ABI", pme);
16848                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16849                return;
16850            }
16851
16852            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16853            // Do not run PackageDexOptimizer through the local performDexOpt
16854            // method because `pkg` may not be in `mPackages` yet.
16855            //
16856            // Also, don't fail application installs if the dexopt step fails.
16857            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16858                    null /* instructionSets */, false /* checkProfiles */,
16859                    getCompilerFilterForReason(REASON_INSTALL),
16860                    getOrCreateCompilerPackageStats(pkg));
16861            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16862
16863            // Notify BackgroundDexOptJobService that the package has been changed.
16864            // If this is an update of a package which used to fail to compile,
16865            // BDOS will remove it from its blacklist.
16866            // TODO: Layering violation
16867            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16868        }
16869
16870        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16871            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16872            return;
16873        }
16874
16875        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16876
16877        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16878                "installPackageLI")) {
16879            if (replace) {
16880                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16881                    // Static libs have a synthetic package name containing the version
16882                    // and cannot be updated as an update would get a new package name,
16883                    // unless this is the exact same version code which is useful for
16884                    // development.
16885                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16886                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16887                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16888                                + "static-shared libs cannot be updated");
16889                        return;
16890                    }
16891                }
16892                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16893                        installerPackageName, res, args.installReason);
16894            } else {
16895                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16896                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16897            }
16898        }
16899        synchronized (mPackages) {
16900            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16901            if (ps != null) {
16902                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16903            }
16904
16905            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16906            for (int i = 0; i < childCount; i++) {
16907                PackageParser.Package childPkg = pkg.childPackages.get(i);
16908                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16909                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16910                if (childPs != null) {
16911                    childRes.newUsers = childPs.queryInstalledUsers(
16912                            sUserManager.getUserIds(), true);
16913                }
16914            }
16915
16916            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16917                updateSequenceNumberLP(pkgName, res.newUsers);
16918            }
16919        }
16920    }
16921
16922    private void startIntentFilterVerifications(int userId, boolean replacing,
16923            PackageParser.Package pkg) {
16924        if (mIntentFilterVerifierComponent == null) {
16925            Slog.w(TAG, "No IntentFilter verification will not be done as "
16926                    + "there is no IntentFilterVerifier available!");
16927            return;
16928        }
16929
16930        final int verifierUid = getPackageUid(
16931                mIntentFilterVerifierComponent.getPackageName(),
16932                MATCH_DEBUG_TRIAGED_MISSING,
16933                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16934
16935        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16936        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16937        mHandler.sendMessage(msg);
16938
16939        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16940        for (int i = 0; i < childCount; i++) {
16941            PackageParser.Package childPkg = pkg.childPackages.get(i);
16942            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16943            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16944            mHandler.sendMessage(msg);
16945        }
16946    }
16947
16948    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16949            PackageParser.Package pkg) {
16950        int size = pkg.activities.size();
16951        if (size == 0) {
16952            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16953                    "No activity, so no need to verify any IntentFilter!");
16954            return;
16955        }
16956
16957        final boolean hasDomainURLs = hasDomainURLs(pkg);
16958        if (!hasDomainURLs) {
16959            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16960                    "No domain URLs, so no need to verify any IntentFilter!");
16961            return;
16962        }
16963
16964        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16965                + " if any IntentFilter from the " + size
16966                + " Activities needs verification ...");
16967
16968        int count = 0;
16969        final String packageName = pkg.packageName;
16970
16971        synchronized (mPackages) {
16972            // If this is a new install and we see that we've already run verification for this
16973            // package, we have nothing to do: it means the state was restored from backup.
16974            if (!replacing) {
16975                IntentFilterVerificationInfo ivi =
16976                        mSettings.getIntentFilterVerificationLPr(packageName);
16977                if (ivi != null) {
16978                    if (DEBUG_DOMAIN_VERIFICATION) {
16979                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16980                                + ivi.getStatusString());
16981                    }
16982                    return;
16983                }
16984            }
16985
16986            // If any filters need to be verified, then all need to be.
16987            boolean needToVerify = false;
16988            for (PackageParser.Activity a : pkg.activities) {
16989                for (ActivityIntentInfo filter : a.intents) {
16990                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16991                        if (DEBUG_DOMAIN_VERIFICATION) {
16992                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16993                        }
16994                        needToVerify = true;
16995                        break;
16996                    }
16997                }
16998            }
16999
17000            if (needToVerify) {
17001                final int verificationId = mIntentFilterVerificationToken++;
17002                for (PackageParser.Activity a : pkg.activities) {
17003                    for (ActivityIntentInfo filter : a.intents) {
17004                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17005                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17006                                    "Verification needed for IntentFilter:" + filter.toString());
17007                            mIntentFilterVerifier.addOneIntentFilterVerification(
17008                                    verifierUid, userId, verificationId, filter, packageName);
17009                            count++;
17010                        }
17011                    }
17012                }
17013            }
17014        }
17015
17016        if (count > 0) {
17017            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17018                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17019                    +  " for userId:" + userId);
17020            mIntentFilterVerifier.startVerifications(userId);
17021        } else {
17022            if (DEBUG_DOMAIN_VERIFICATION) {
17023                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17024            }
17025        }
17026    }
17027
17028    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17029        final ComponentName cn  = filter.activity.getComponentName();
17030        final String packageName = cn.getPackageName();
17031
17032        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17033                packageName);
17034        if (ivi == null) {
17035            return true;
17036        }
17037        int status = ivi.getStatus();
17038        switch (status) {
17039            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17040            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17041                return true;
17042
17043            default:
17044                // Nothing to do
17045                return false;
17046        }
17047    }
17048
17049    private static boolean isMultiArch(ApplicationInfo info) {
17050        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17051    }
17052
17053    private static boolean isExternal(PackageParser.Package pkg) {
17054        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17055    }
17056
17057    private static boolean isExternal(PackageSetting ps) {
17058        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17059    }
17060
17061    private static boolean isEphemeral(PackageParser.Package pkg) {
17062        return pkg.applicationInfo.isInstantApp();
17063    }
17064
17065    private static boolean isEphemeral(PackageSetting ps) {
17066        return ps.pkg != null && isEphemeral(ps.pkg);
17067    }
17068
17069    private static boolean isSystemApp(PackageParser.Package pkg) {
17070        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17071    }
17072
17073    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17074        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17075    }
17076
17077    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17078        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17079    }
17080
17081    private static boolean isSystemApp(PackageSetting ps) {
17082        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17083    }
17084
17085    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17086        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17087    }
17088
17089    private int packageFlagsToInstallFlags(PackageSetting ps) {
17090        int installFlags = 0;
17091        if (isEphemeral(ps)) {
17092            installFlags |= PackageManager.INSTALL_EPHEMERAL;
17093        }
17094        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17095            // This existing package was an external ASEC install when we have
17096            // the external flag without a UUID
17097            installFlags |= PackageManager.INSTALL_EXTERNAL;
17098        }
17099        if (ps.isForwardLocked()) {
17100            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17101        }
17102        return installFlags;
17103    }
17104
17105    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17106        if (isExternal(pkg)) {
17107            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17108                return StorageManager.UUID_PRIMARY_PHYSICAL;
17109            } else {
17110                return pkg.volumeUuid;
17111            }
17112        } else {
17113            return StorageManager.UUID_PRIVATE_INTERNAL;
17114        }
17115    }
17116
17117    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17118        if (isExternal(pkg)) {
17119            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17120                return mSettings.getExternalVersion();
17121            } else {
17122                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17123            }
17124        } else {
17125            return mSettings.getInternalVersion();
17126        }
17127    }
17128
17129    private void deleteTempPackageFiles() {
17130        final FilenameFilter filter = new FilenameFilter() {
17131            public boolean accept(File dir, String name) {
17132                return name.startsWith("vmdl") && name.endsWith(".tmp");
17133            }
17134        };
17135        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17136            file.delete();
17137        }
17138    }
17139
17140    @Override
17141    public void deletePackageAsUser(String packageName, int versionCode,
17142            IPackageDeleteObserver observer, int userId, int flags) {
17143        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17144                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17145    }
17146
17147    @Override
17148    public void deletePackageVersioned(VersionedPackage versionedPackage,
17149            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17150        mContext.enforceCallingOrSelfPermission(
17151                android.Manifest.permission.DELETE_PACKAGES, null);
17152        Preconditions.checkNotNull(versionedPackage);
17153        Preconditions.checkNotNull(observer);
17154        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17155                PackageManager.VERSION_CODE_HIGHEST,
17156                Integer.MAX_VALUE, "versionCode must be >= -1");
17157
17158        final String packageName = versionedPackage.getPackageName();
17159        // TODO: We will change version code to long, so in the new API it is long
17160        final int versionCode = (int) versionedPackage.getVersionCode();
17161        final String internalPackageName;
17162        synchronized (mPackages) {
17163            // Normalize package name to handle renamed packages and static libs
17164            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17165                    // TODO: We will change version code to long, so in the new API it is long
17166                    (int) versionedPackage.getVersionCode());
17167        }
17168
17169        final int uid = Binder.getCallingUid();
17170        if (!isOrphaned(internalPackageName)
17171                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17172            try {
17173                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17174                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17175                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17176                observer.onUserActionRequired(intent);
17177            } catch (RemoteException re) {
17178            }
17179            return;
17180        }
17181        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17182        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17183        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17184            mContext.enforceCallingOrSelfPermission(
17185                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17186                    "deletePackage for user " + userId);
17187        }
17188
17189        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17190            try {
17191                observer.onPackageDeleted(packageName,
17192                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17193            } catch (RemoteException re) {
17194            }
17195            return;
17196        }
17197
17198        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17199            try {
17200                observer.onPackageDeleted(packageName,
17201                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17202            } catch (RemoteException re) {
17203            }
17204            return;
17205        }
17206
17207        if (DEBUG_REMOVE) {
17208            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17209                    + " deleteAllUsers: " + deleteAllUsers + " version="
17210                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17211                    ? "VERSION_CODE_HIGHEST" : versionCode));
17212        }
17213        // Queue up an async operation since the package deletion may take a little while.
17214        mHandler.post(new Runnable() {
17215            public void run() {
17216                mHandler.removeCallbacks(this);
17217                int returnCode;
17218                if (!deleteAllUsers) {
17219                    returnCode = deletePackageX(internalPackageName, versionCode,
17220                            userId, deleteFlags);
17221                } else {
17222                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17223                            internalPackageName, users);
17224                    // If nobody is blocking uninstall, proceed with delete for all users
17225                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17226                        returnCode = deletePackageX(internalPackageName, versionCode,
17227                                userId, deleteFlags);
17228                    } else {
17229                        // Otherwise uninstall individually for users with blockUninstalls=false
17230                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17231                        for (int userId : users) {
17232                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17233                                returnCode = deletePackageX(internalPackageName, versionCode,
17234                                        userId, userFlags);
17235                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17236                                    Slog.w(TAG, "Package delete failed for user " + userId
17237                                            + ", returnCode " + returnCode);
17238                                }
17239                            }
17240                        }
17241                        // The app has only been marked uninstalled for certain users.
17242                        // We still need to report that delete was blocked
17243                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17244                    }
17245                }
17246                try {
17247                    observer.onPackageDeleted(packageName, returnCode, null);
17248                } catch (RemoteException e) {
17249                    Log.i(TAG, "Observer no longer exists.");
17250                } //end catch
17251            } //end run
17252        });
17253    }
17254
17255    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17256        if (pkg.staticSharedLibName != null) {
17257            return pkg.manifestPackageName;
17258        }
17259        return pkg.packageName;
17260    }
17261
17262    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17263        // Handle renamed packages
17264        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17265        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17266
17267        // Is this a static library?
17268        SparseArray<SharedLibraryEntry> versionedLib =
17269                mStaticLibsByDeclaringPackage.get(packageName);
17270        if (versionedLib == null || versionedLib.size() <= 0) {
17271            return packageName;
17272        }
17273
17274        // Figure out which lib versions the caller can see
17275        SparseIntArray versionsCallerCanSee = null;
17276        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17277        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17278                && callingAppId != Process.ROOT_UID) {
17279            versionsCallerCanSee = new SparseIntArray();
17280            String libName = versionedLib.valueAt(0).info.getName();
17281            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17282            if (uidPackages != null) {
17283                for (String uidPackage : uidPackages) {
17284                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17285                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17286                    if (libIdx >= 0) {
17287                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17288                        versionsCallerCanSee.append(libVersion, libVersion);
17289                    }
17290                }
17291            }
17292        }
17293
17294        // Caller can see nothing - done
17295        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17296            return packageName;
17297        }
17298
17299        // Find the version the caller can see and the app version code
17300        SharedLibraryEntry highestVersion = null;
17301        final int versionCount = versionedLib.size();
17302        for (int i = 0; i < versionCount; i++) {
17303            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17304            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17305                    libEntry.info.getVersion()) < 0) {
17306                continue;
17307            }
17308            // TODO: We will change version code to long, so in the new API it is long
17309            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17310            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17311                if (libVersionCode == versionCode) {
17312                    return libEntry.apk;
17313                }
17314            } else if (highestVersion == null) {
17315                highestVersion = libEntry;
17316            } else if (libVersionCode  > highestVersion.info
17317                    .getDeclaringPackage().getVersionCode()) {
17318                highestVersion = libEntry;
17319            }
17320        }
17321
17322        if (highestVersion != null) {
17323            return highestVersion.apk;
17324        }
17325
17326        return packageName;
17327    }
17328
17329    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17330        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17331              || callingUid == Process.SYSTEM_UID) {
17332            return true;
17333        }
17334        final int callingUserId = UserHandle.getUserId(callingUid);
17335        // If the caller installed the pkgName, then allow it to silently uninstall.
17336        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17337            return true;
17338        }
17339
17340        // Allow package verifier to silently uninstall.
17341        if (mRequiredVerifierPackage != null &&
17342                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17343            return true;
17344        }
17345
17346        // Allow package uninstaller to silently uninstall.
17347        if (mRequiredUninstallerPackage != null &&
17348                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17349            return true;
17350        }
17351
17352        // Allow storage manager to silently uninstall.
17353        if (mStorageManagerPackage != null &&
17354                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17355            return true;
17356        }
17357        return false;
17358    }
17359
17360    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17361        int[] result = EMPTY_INT_ARRAY;
17362        for (int userId : userIds) {
17363            if (getBlockUninstallForUser(packageName, userId)) {
17364                result = ArrayUtils.appendInt(result, userId);
17365            }
17366        }
17367        return result;
17368    }
17369
17370    @Override
17371    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17372        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17373    }
17374
17375    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17376        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17377                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17378        try {
17379            if (dpm != null) {
17380                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17381                        /* callingUserOnly =*/ false);
17382                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17383                        : deviceOwnerComponentName.getPackageName();
17384                // Does the package contains the device owner?
17385                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17386                // this check is probably not needed, since DO should be registered as a device
17387                // admin on some user too. (Original bug for this: b/17657954)
17388                if (packageName.equals(deviceOwnerPackageName)) {
17389                    return true;
17390                }
17391                // Does it contain a device admin for any user?
17392                int[] users;
17393                if (userId == UserHandle.USER_ALL) {
17394                    users = sUserManager.getUserIds();
17395                } else {
17396                    users = new int[]{userId};
17397                }
17398                for (int i = 0; i < users.length; ++i) {
17399                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17400                        return true;
17401                    }
17402                }
17403            }
17404        } catch (RemoteException e) {
17405        }
17406        return false;
17407    }
17408
17409    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17410        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17411    }
17412
17413    /**
17414     *  This method is an internal method that could be get invoked either
17415     *  to delete an installed package or to clean up a failed installation.
17416     *  After deleting an installed package, a broadcast is sent to notify any
17417     *  listeners that the package has been removed. For cleaning up a failed
17418     *  installation, the broadcast is not necessary since the package's
17419     *  installation wouldn't have sent the initial broadcast either
17420     *  The key steps in deleting a package are
17421     *  deleting the package information in internal structures like mPackages,
17422     *  deleting the packages base directories through installd
17423     *  updating mSettings to reflect current status
17424     *  persisting settings for later use
17425     *  sending a broadcast if necessary
17426     */
17427    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17428        final PackageRemovedInfo info = new PackageRemovedInfo();
17429        final boolean res;
17430
17431        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17432                ? UserHandle.USER_ALL : userId;
17433
17434        if (isPackageDeviceAdmin(packageName, removeUser)) {
17435            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17436            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17437        }
17438
17439        PackageSetting uninstalledPs = null;
17440
17441        // for the uninstall-updates case and restricted profiles, remember the per-
17442        // user handle installed state
17443        int[] allUsers;
17444        synchronized (mPackages) {
17445            uninstalledPs = mSettings.mPackages.get(packageName);
17446            if (uninstalledPs == null) {
17447                Slog.w(TAG, "Not removing non-existent package " + packageName);
17448                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17449            }
17450
17451            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17452                    && uninstalledPs.versionCode != versionCode) {
17453                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17454                        + uninstalledPs.versionCode + " != " + versionCode);
17455                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17456            }
17457
17458            // Static shared libs can be declared by any package, so let us not
17459            // allow removing a package if it provides a lib others depend on.
17460            PackageParser.Package pkg = mPackages.get(packageName);
17461            if (pkg != null && pkg.staticSharedLibName != null) {
17462                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17463                        pkg.staticSharedLibVersion);
17464                if (libEntry != null) {
17465                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17466                            libEntry.info, 0, userId);
17467                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17468                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17469                                + " hosting lib " + libEntry.info.getName() + " version "
17470                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17471                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17472                    }
17473                }
17474            }
17475
17476            allUsers = sUserManager.getUserIds();
17477            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17478        }
17479
17480        final int freezeUser;
17481        if (isUpdatedSystemApp(uninstalledPs)
17482                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17483            // We're downgrading a system app, which will apply to all users, so
17484            // freeze them all during the downgrade
17485            freezeUser = UserHandle.USER_ALL;
17486        } else {
17487            freezeUser = removeUser;
17488        }
17489
17490        synchronized (mInstallLock) {
17491            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17492            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17493                    deleteFlags, "deletePackageX")) {
17494                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17495                        deleteFlags | REMOVE_CHATTY, info, true, null);
17496            }
17497            synchronized (mPackages) {
17498                if (res) {
17499                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17500                            info.removedUsers);
17501                    updateSequenceNumberLP(packageName, info.removedUsers);
17502                }
17503            }
17504        }
17505
17506        if (res) {
17507            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17508            info.sendPackageRemovedBroadcasts(killApp);
17509            info.sendSystemPackageUpdatedBroadcasts();
17510            info.sendSystemPackageAppearedBroadcasts();
17511        }
17512        // Force a gc here.
17513        Runtime.getRuntime().gc();
17514        // Delete the resources here after sending the broadcast to let
17515        // other processes clean up before deleting resources.
17516        if (info.args != null) {
17517            synchronized (mInstallLock) {
17518                info.args.doPostDeleteLI(true);
17519            }
17520        }
17521
17522        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17523    }
17524
17525    class PackageRemovedInfo {
17526        String removedPackage;
17527        int uid = -1;
17528        int removedAppId = -1;
17529        int[] origUsers;
17530        int[] removedUsers = null;
17531        SparseArray<Integer> installReasons;
17532        boolean isRemovedPackageSystemUpdate = false;
17533        boolean isUpdate;
17534        boolean dataRemoved;
17535        boolean removedForAllUsers;
17536        boolean isStaticSharedLib;
17537        // Clean up resources deleted packages.
17538        InstallArgs args = null;
17539        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17540        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17541
17542        void sendPackageRemovedBroadcasts(boolean killApp) {
17543            sendPackageRemovedBroadcastInternal(killApp);
17544            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17545            for (int i = 0; i < childCount; i++) {
17546                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17547                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17548            }
17549        }
17550
17551        void sendSystemPackageUpdatedBroadcasts() {
17552            if (isRemovedPackageSystemUpdate) {
17553                sendSystemPackageUpdatedBroadcastsInternal();
17554                final int childCount = (removedChildPackages != null)
17555                        ? removedChildPackages.size() : 0;
17556                for (int i = 0; i < childCount; i++) {
17557                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17558                    if (childInfo.isRemovedPackageSystemUpdate) {
17559                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17560                    }
17561                }
17562            }
17563        }
17564
17565        void sendSystemPackageAppearedBroadcasts() {
17566            final int packageCount = (appearedChildPackages != null)
17567                    ? appearedChildPackages.size() : 0;
17568            for (int i = 0; i < packageCount; i++) {
17569                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17570                sendPackageAddedForNewUsers(installedInfo.name, true,
17571                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17572            }
17573        }
17574
17575        private void sendSystemPackageUpdatedBroadcastsInternal() {
17576            Bundle extras = new Bundle(2);
17577            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17578            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17579            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17580                    extras, 0, null, null, null);
17581            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17582                    extras, 0, null, null, null);
17583            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17584                    null, 0, removedPackage, null, null);
17585        }
17586
17587        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17588            // Don't send static shared library removal broadcasts as these
17589            // libs are visible only the the apps that depend on them an one
17590            // cannot remove the library if it has a dependency.
17591            if (isStaticSharedLib) {
17592                return;
17593            }
17594            Bundle extras = new Bundle(2);
17595            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17596            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17597            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17598            if (isUpdate || isRemovedPackageSystemUpdate) {
17599                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17600            }
17601            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17602            if (removedPackage != null) {
17603                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17604                        extras, 0, null, null, removedUsers);
17605                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17606                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17607                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17608                            null, null, removedUsers);
17609                }
17610            }
17611            if (removedAppId >= 0) {
17612                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17613                        removedUsers);
17614            }
17615        }
17616    }
17617
17618    /*
17619     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17620     * flag is not set, the data directory is removed as well.
17621     * make sure this flag is set for partially installed apps. If not its meaningless to
17622     * delete a partially installed application.
17623     */
17624    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17625            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17626        String packageName = ps.name;
17627        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17628        // Retrieve object to delete permissions for shared user later on
17629        final PackageParser.Package deletedPkg;
17630        final PackageSetting deletedPs;
17631        // reader
17632        synchronized (mPackages) {
17633            deletedPkg = mPackages.get(packageName);
17634            deletedPs = mSettings.mPackages.get(packageName);
17635            if (outInfo != null) {
17636                outInfo.removedPackage = packageName;
17637                outInfo.isStaticSharedLib = deletedPkg != null
17638                        && deletedPkg.staticSharedLibName != null;
17639                outInfo.removedUsers = deletedPs != null
17640                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17641                        : null;
17642            }
17643        }
17644
17645        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17646
17647        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17648            final PackageParser.Package resolvedPkg;
17649            if (deletedPkg != null) {
17650                resolvedPkg = deletedPkg;
17651            } else {
17652                // We don't have a parsed package when it lives on an ejected
17653                // adopted storage device, so fake something together
17654                resolvedPkg = new PackageParser.Package(ps.name);
17655                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17656            }
17657            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17658                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17659            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17660            if (outInfo != null) {
17661                outInfo.dataRemoved = true;
17662            }
17663            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17664        }
17665
17666        int removedAppId = -1;
17667
17668        // writer
17669        synchronized (mPackages) {
17670            if (deletedPs != null) {
17671                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17672                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17673                    clearDefaultBrowserIfNeeded(packageName);
17674                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17675                    removedAppId = mSettings.removePackageLPw(packageName);
17676                    if (outInfo != null) {
17677                        outInfo.removedAppId = removedAppId;
17678                    }
17679                    updatePermissionsLPw(deletedPs.name, null, 0);
17680                    if (deletedPs.sharedUser != null) {
17681                        // Remove permissions associated with package. Since runtime
17682                        // permissions are per user we have to kill the removed package
17683                        // or packages running under the shared user of the removed
17684                        // package if revoking the permissions requested only by the removed
17685                        // package is successful and this causes a change in gids.
17686                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17687                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17688                                    userId);
17689                            if (userIdToKill == UserHandle.USER_ALL
17690                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17691                                // If gids changed for this user, kill all affected packages.
17692                                mHandler.post(new Runnable() {
17693                                    @Override
17694                                    public void run() {
17695                                        // This has to happen with no lock held.
17696                                        killApplication(deletedPs.name, deletedPs.appId,
17697                                                KILL_APP_REASON_GIDS_CHANGED);
17698                                    }
17699                                });
17700                                break;
17701                            }
17702                        }
17703                    }
17704                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17705                }
17706                // make sure to preserve per-user disabled state if this removal was just
17707                // a downgrade of a system app to the factory package
17708                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17709                    if (DEBUG_REMOVE) {
17710                        Slog.d(TAG, "Propagating install state across downgrade");
17711                    }
17712                    for (int userId : allUserHandles) {
17713                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17714                        if (DEBUG_REMOVE) {
17715                            Slog.d(TAG, "    user " + userId + " => " + installed);
17716                        }
17717                        ps.setInstalled(installed, userId);
17718                    }
17719                }
17720            }
17721            // can downgrade to reader
17722            if (writeSettings) {
17723                // Save settings now
17724                mSettings.writeLPr();
17725            }
17726        }
17727        if (removedAppId != -1) {
17728            // A user ID was deleted here. Go through all users and remove it
17729            // from KeyStore.
17730            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17731        }
17732    }
17733
17734    static boolean locationIsPrivileged(File path) {
17735        try {
17736            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17737                    .getCanonicalPath();
17738            return path.getCanonicalPath().startsWith(privilegedAppDir);
17739        } catch (IOException e) {
17740            Slog.e(TAG, "Unable to access code path " + path);
17741        }
17742        return false;
17743    }
17744
17745    /*
17746     * Tries to delete system package.
17747     */
17748    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17749            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17750            boolean writeSettings) {
17751        if (deletedPs.parentPackageName != null) {
17752            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17753            return false;
17754        }
17755
17756        final boolean applyUserRestrictions
17757                = (allUserHandles != null) && (outInfo.origUsers != null);
17758        final PackageSetting disabledPs;
17759        // Confirm if the system package has been updated
17760        // An updated system app can be deleted. This will also have to restore
17761        // the system pkg from system partition
17762        // reader
17763        synchronized (mPackages) {
17764            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17765        }
17766
17767        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17768                + " disabledPs=" + disabledPs);
17769
17770        if (disabledPs == null) {
17771            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17772            return false;
17773        } else if (DEBUG_REMOVE) {
17774            Slog.d(TAG, "Deleting system pkg from data partition");
17775        }
17776
17777        if (DEBUG_REMOVE) {
17778            if (applyUserRestrictions) {
17779                Slog.d(TAG, "Remembering install states:");
17780                for (int userId : allUserHandles) {
17781                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17782                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17783                }
17784            }
17785        }
17786
17787        // Delete the updated package
17788        outInfo.isRemovedPackageSystemUpdate = true;
17789        if (outInfo.removedChildPackages != null) {
17790            final int childCount = (deletedPs.childPackageNames != null)
17791                    ? deletedPs.childPackageNames.size() : 0;
17792            for (int i = 0; i < childCount; i++) {
17793                String childPackageName = deletedPs.childPackageNames.get(i);
17794                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17795                        .contains(childPackageName)) {
17796                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17797                            childPackageName);
17798                    if (childInfo != null) {
17799                        childInfo.isRemovedPackageSystemUpdate = true;
17800                    }
17801                }
17802            }
17803        }
17804
17805        if (disabledPs.versionCode < deletedPs.versionCode) {
17806            // Delete data for downgrades
17807            flags &= ~PackageManager.DELETE_KEEP_DATA;
17808        } else {
17809            // Preserve data by setting flag
17810            flags |= PackageManager.DELETE_KEEP_DATA;
17811        }
17812
17813        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17814                outInfo, writeSettings, disabledPs.pkg);
17815        if (!ret) {
17816            return false;
17817        }
17818
17819        // writer
17820        synchronized (mPackages) {
17821            // Reinstate the old system package
17822            enableSystemPackageLPw(disabledPs.pkg);
17823            // Remove any native libraries from the upgraded package.
17824            removeNativeBinariesLI(deletedPs);
17825        }
17826
17827        // Install the system package
17828        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17829        int parseFlags = mDefParseFlags
17830                | PackageParser.PARSE_MUST_BE_APK
17831                | PackageParser.PARSE_IS_SYSTEM
17832                | PackageParser.PARSE_IS_SYSTEM_DIR;
17833        if (locationIsPrivileged(disabledPs.codePath)) {
17834            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17835        }
17836
17837        final PackageParser.Package newPkg;
17838        try {
17839            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17840                0 /* currentTime */, null);
17841        } catch (PackageManagerException e) {
17842            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17843                    + e.getMessage());
17844            return false;
17845        }
17846
17847        try {
17848            // update shared libraries for the newly re-installed system package
17849            updateSharedLibrariesLPr(newPkg, null);
17850        } catch (PackageManagerException e) {
17851            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17852        }
17853
17854        prepareAppDataAfterInstallLIF(newPkg);
17855
17856        // writer
17857        synchronized (mPackages) {
17858            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17859
17860            // Propagate the permissions state as we do not want to drop on the floor
17861            // runtime permissions. The update permissions method below will take
17862            // care of removing obsolete permissions and grant install permissions.
17863            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17864            updatePermissionsLPw(newPkg.packageName, newPkg,
17865                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17866
17867            if (applyUserRestrictions) {
17868                if (DEBUG_REMOVE) {
17869                    Slog.d(TAG, "Propagating install state across reinstall");
17870                }
17871                for (int userId : allUserHandles) {
17872                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17873                    if (DEBUG_REMOVE) {
17874                        Slog.d(TAG, "    user " + userId + " => " + installed);
17875                    }
17876                    ps.setInstalled(installed, userId);
17877
17878                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17879                }
17880                // Regardless of writeSettings we need to ensure that this restriction
17881                // state propagation is persisted
17882                mSettings.writeAllUsersPackageRestrictionsLPr();
17883            }
17884            // can downgrade to reader here
17885            if (writeSettings) {
17886                mSettings.writeLPr();
17887            }
17888        }
17889        return true;
17890    }
17891
17892    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17893            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17894            PackageRemovedInfo outInfo, boolean writeSettings,
17895            PackageParser.Package replacingPackage) {
17896        synchronized (mPackages) {
17897            if (outInfo != null) {
17898                outInfo.uid = ps.appId;
17899            }
17900
17901            if (outInfo != null && outInfo.removedChildPackages != null) {
17902                final int childCount = (ps.childPackageNames != null)
17903                        ? ps.childPackageNames.size() : 0;
17904                for (int i = 0; i < childCount; i++) {
17905                    String childPackageName = ps.childPackageNames.get(i);
17906                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17907                    if (childPs == null) {
17908                        return false;
17909                    }
17910                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17911                            childPackageName);
17912                    if (childInfo != null) {
17913                        childInfo.uid = childPs.appId;
17914                    }
17915                }
17916            }
17917        }
17918
17919        // Delete package data from internal structures and also remove data if flag is set
17920        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17921
17922        // Delete the child packages data
17923        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17924        for (int i = 0; i < childCount; i++) {
17925            PackageSetting childPs;
17926            synchronized (mPackages) {
17927                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17928            }
17929            if (childPs != null) {
17930                PackageRemovedInfo childOutInfo = (outInfo != null
17931                        && outInfo.removedChildPackages != null)
17932                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17933                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17934                        && (replacingPackage != null
17935                        && !replacingPackage.hasChildPackage(childPs.name))
17936                        ? flags & ~DELETE_KEEP_DATA : flags;
17937                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17938                        deleteFlags, writeSettings);
17939            }
17940        }
17941
17942        // Delete application code and resources only for parent packages
17943        if (ps.parentPackageName == null) {
17944            if (deleteCodeAndResources && (outInfo != null)) {
17945                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17946                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17947                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17948            }
17949        }
17950
17951        return true;
17952    }
17953
17954    @Override
17955    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17956            int userId) {
17957        mContext.enforceCallingOrSelfPermission(
17958                android.Manifest.permission.DELETE_PACKAGES, null);
17959        synchronized (mPackages) {
17960            PackageSetting ps = mSettings.mPackages.get(packageName);
17961            if (ps == null) {
17962                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17963                return false;
17964            }
17965            // Cannot block uninstall of static shared libs as they are
17966            // considered a part of the using app (emulating static linking).
17967            // Also static libs are installed always on internal storage.
17968            PackageParser.Package pkg = mPackages.get(packageName);
17969            if (pkg != null && pkg.staticSharedLibName != null) {
17970                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17971                        + " providing static shared library: " + pkg.staticSharedLibName);
17972                return false;
17973            }
17974            if (!ps.getInstalled(userId)) {
17975                // Can't block uninstall for an app that is not installed or enabled.
17976                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17977                return false;
17978            }
17979            ps.setBlockUninstall(blockUninstall, userId);
17980            mSettings.writePackageRestrictionsLPr(userId);
17981        }
17982        return true;
17983    }
17984
17985    @Override
17986    public boolean getBlockUninstallForUser(String packageName, int userId) {
17987        synchronized (mPackages) {
17988            PackageSetting ps = mSettings.mPackages.get(packageName);
17989            if (ps == null) {
17990                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17991                return false;
17992            }
17993            return ps.getBlockUninstall(userId);
17994        }
17995    }
17996
17997    @Override
17998    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17999        int callingUid = Binder.getCallingUid();
18000        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18001            throw new SecurityException(
18002                    "setRequiredForSystemUser can only be run by the system or root");
18003        }
18004        synchronized (mPackages) {
18005            PackageSetting ps = mSettings.mPackages.get(packageName);
18006            if (ps == null) {
18007                Log.w(TAG, "Package doesn't exist: " + packageName);
18008                return false;
18009            }
18010            if (systemUserApp) {
18011                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18012            } else {
18013                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18014            }
18015            mSettings.writeLPr();
18016        }
18017        return true;
18018    }
18019
18020    /*
18021     * This method handles package deletion in general
18022     */
18023    private boolean deletePackageLIF(String packageName, UserHandle user,
18024            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18025            PackageRemovedInfo outInfo, boolean writeSettings,
18026            PackageParser.Package replacingPackage) {
18027        if (packageName == null) {
18028            Slog.w(TAG, "Attempt to delete null packageName.");
18029            return false;
18030        }
18031
18032        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18033
18034        PackageSetting ps;
18035        synchronized (mPackages) {
18036            ps = mSettings.mPackages.get(packageName);
18037            if (ps == null) {
18038                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18039                return false;
18040            }
18041
18042            if (ps.parentPackageName != null && (!isSystemApp(ps)
18043                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18044                if (DEBUG_REMOVE) {
18045                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18046                            + ((user == null) ? UserHandle.USER_ALL : user));
18047                }
18048                final int removedUserId = (user != null) ? user.getIdentifier()
18049                        : UserHandle.USER_ALL;
18050                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18051                    return false;
18052                }
18053                markPackageUninstalledForUserLPw(ps, user);
18054                scheduleWritePackageRestrictionsLocked(user);
18055                return true;
18056            }
18057        }
18058
18059        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18060                && user.getIdentifier() != UserHandle.USER_ALL)) {
18061            // The caller is asking that the package only be deleted for a single
18062            // user.  To do this, we just mark its uninstalled state and delete
18063            // its data. If this is a system app, we only allow this to happen if
18064            // they have set the special DELETE_SYSTEM_APP which requests different
18065            // semantics than normal for uninstalling system apps.
18066            markPackageUninstalledForUserLPw(ps, user);
18067
18068            if (!isSystemApp(ps)) {
18069                // Do not uninstall the APK if an app should be cached
18070                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18071                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18072                    // Other user still have this package installed, so all
18073                    // we need to do is clear this user's data and save that
18074                    // it is uninstalled.
18075                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18076                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18077                        return false;
18078                    }
18079                    scheduleWritePackageRestrictionsLocked(user);
18080                    return true;
18081                } else {
18082                    // We need to set it back to 'installed' so the uninstall
18083                    // broadcasts will be sent correctly.
18084                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18085                    ps.setInstalled(true, user.getIdentifier());
18086                }
18087            } else {
18088                // This is a system app, so we assume that the
18089                // other users still have this package installed, so all
18090                // we need to do is clear this user's data and save that
18091                // it is uninstalled.
18092                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18093                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18094                    return false;
18095                }
18096                scheduleWritePackageRestrictionsLocked(user);
18097                return true;
18098            }
18099        }
18100
18101        // If we are deleting a composite package for all users, keep track
18102        // of result for each child.
18103        if (ps.childPackageNames != null && outInfo != null) {
18104            synchronized (mPackages) {
18105                final int childCount = ps.childPackageNames.size();
18106                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18107                for (int i = 0; i < childCount; i++) {
18108                    String childPackageName = ps.childPackageNames.get(i);
18109                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18110                    childInfo.removedPackage = childPackageName;
18111                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18112                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18113                    if (childPs != null) {
18114                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18115                    }
18116                }
18117            }
18118        }
18119
18120        boolean ret = false;
18121        if (isSystemApp(ps)) {
18122            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18123            // When an updated system application is deleted we delete the existing resources
18124            // as well and fall back to existing code in system partition
18125            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18126        } else {
18127            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18128            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18129                    outInfo, writeSettings, replacingPackage);
18130        }
18131
18132        // Take a note whether we deleted the package for all users
18133        if (outInfo != null) {
18134            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18135            if (outInfo.removedChildPackages != null) {
18136                synchronized (mPackages) {
18137                    final int childCount = outInfo.removedChildPackages.size();
18138                    for (int i = 0; i < childCount; i++) {
18139                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18140                        if (childInfo != null) {
18141                            childInfo.removedForAllUsers = mPackages.get(
18142                                    childInfo.removedPackage) == null;
18143                        }
18144                    }
18145                }
18146            }
18147            // If we uninstalled an update to a system app there may be some
18148            // child packages that appeared as they are declared in the system
18149            // app but were not declared in the update.
18150            if (isSystemApp(ps)) {
18151                synchronized (mPackages) {
18152                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18153                    final int childCount = (updatedPs.childPackageNames != null)
18154                            ? updatedPs.childPackageNames.size() : 0;
18155                    for (int i = 0; i < childCount; i++) {
18156                        String childPackageName = updatedPs.childPackageNames.get(i);
18157                        if (outInfo.removedChildPackages == null
18158                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18159                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18160                            if (childPs == null) {
18161                                continue;
18162                            }
18163                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18164                            installRes.name = childPackageName;
18165                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18166                            installRes.pkg = mPackages.get(childPackageName);
18167                            installRes.uid = childPs.pkg.applicationInfo.uid;
18168                            if (outInfo.appearedChildPackages == null) {
18169                                outInfo.appearedChildPackages = new ArrayMap<>();
18170                            }
18171                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18172                        }
18173                    }
18174                }
18175            }
18176        }
18177
18178        return ret;
18179    }
18180
18181    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18182        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18183                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18184        for (int nextUserId : userIds) {
18185            if (DEBUG_REMOVE) {
18186                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18187            }
18188            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18189                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18190                    false /*hidden*/, false /*suspended*/, null, null, null,
18191                    false /*blockUninstall*/,
18192                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18193                    PackageManager.INSTALL_REASON_UNKNOWN);
18194        }
18195    }
18196
18197    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18198            PackageRemovedInfo outInfo) {
18199        final PackageParser.Package pkg;
18200        synchronized (mPackages) {
18201            pkg = mPackages.get(ps.name);
18202        }
18203
18204        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18205                : new int[] {userId};
18206        for (int nextUserId : userIds) {
18207            if (DEBUG_REMOVE) {
18208                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18209                        + nextUserId);
18210            }
18211
18212            destroyAppDataLIF(pkg, userId,
18213                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18214            destroyAppProfilesLIF(pkg, userId);
18215            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18216            schedulePackageCleaning(ps.name, nextUserId, false);
18217            synchronized (mPackages) {
18218                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18219                    scheduleWritePackageRestrictionsLocked(nextUserId);
18220                }
18221                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18222            }
18223        }
18224
18225        if (outInfo != null) {
18226            outInfo.removedPackage = ps.name;
18227            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18228            outInfo.removedAppId = ps.appId;
18229            outInfo.removedUsers = userIds;
18230        }
18231
18232        return true;
18233    }
18234
18235    private final class ClearStorageConnection implements ServiceConnection {
18236        IMediaContainerService mContainerService;
18237
18238        @Override
18239        public void onServiceConnected(ComponentName name, IBinder service) {
18240            synchronized (this) {
18241                mContainerService = IMediaContainerService.Stub
18242                        .asInterface(Binder.allowBlocking(service));
18243                notifyAll();
18244            }
18245        }
18246
18247        @Override
18248        public void onServiceDisconnected(ComponentName name) {
18249        }
18250    }
18251
18252    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18253        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18254
18255        final boolean mounted;
18256        if (Environment.isExternalStorageEmulated()) {
18257            mounted = true;
18258        } else {
18259            final String status = Environment.getExternalStorageState();
18260
18261            mounted = status.equals(Environment.MEDIA_MOUNTED)
18262                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18263        }
18264
18265        if (!mounted) {
18266            return;
18267        }
18268
18269        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18270        int[] users;
18271        if (userId == UserHandle.USER_ALL) {
18272            users = sUserManager.getUserIds();
18273        } else {
18274            users = new int[] { userId };
18275        }
18276        final ClearStorageConnection conn = new ClearStorageConnection();
18277        if (mContext.bindServiceAsUser(
18278                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18279            try {
18280                for (int curUser : users) {
18281                    long timeout = SystemClock.uptimeMillis() + 5000;
18282                    synchronized (conn) {
18283                        long now;
18284                        while (conn.mContainerService == null &&
18285                                (now = SystemClock.uptimeMillis()) < timeout) {
18286                            try {
18287                                conn.wait(timeout - now);
18288                            } catch (InterruptedException e) {
18289                            }
18290                        }
18291                    }
18292                    if (conn.mContainerService == null) {
18293                        return;
18294                    }
18295
18296                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18297                    clearDirectory(conn.mContainerService,
18298                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18299                    if (allData) {
18300                        clearDirectory(conn.mContainerService,
18301                                userEnv.buildExternalStorageAppDataDirs(packageName));
18302                        clearDirectory(conn.mContainerService,
18303                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18304                    }
18305                }
18306            } finally {
18307                mContext.unbindService(conn);
18308            }
18309        }
18310    }
18311
18312    @Override
18313    public void clearApplicationProfileData(String packageName) {
18314        enforceSystemOrRoot("Only the system can clear all profile data");
18315
18316        final PackageParser.Package pkg;
18317        synchronized (mPackages) {
18318            pkg = mPackages.get(packageName);
18319        }
18320
18321        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18322            synchronized (mInstallLock) {
18323                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18324                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18325                        true /* removeBaseMarker */);
18326            }
18327        }
18328    }
18329
18330    @Override
18331    public void clearApplicationUserData(final String packageName,
18332            final IPackageDataObserver observer, final int userId) {
18333        mContext.enforceCallingOrSelfPermission(
18334                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18335
18336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18337                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18338
18339        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18340            throw new SecurityException("Cannot clear data for a protected package: "
18341                    + packageName);
18342        }
18343        // Queue up an async operation since the package deletion may take a little while.
18344        mHandler.post(new Runnable() {
18345            public void run() {
18346                mHandler.removeCallbacks(this);
18347                final boolean succeeded;
18348                try (PackageFreezer freezer = freezePackage(packageName,
18349                        "clearApplicationUserData")) {
18350                    synchronized (mInstallLock) {
18351                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18352                    }
18353                    clearExternalStorageDataSync(packageName, userId, true);
18354                    synchronized (mPackages) {
18355                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18356                                packageName, userId);
18357                    }
18358                }
18359                if (succeeded) {
18360                    // invoke DeviceStorageMonitor's update method to clear any notifications
18361                    DeviceStorageMonitorInternal dsm = LocalServices
18362                            .getService(DeviceStorageMonitorInternal.class);
18363                    if (dsm != null) {
18364                        dsm.checkMemory();
18365                    }
18366                }
18367                if(observer != null) {
18368                    try {
18369                        observer.onRemoveCompleted(packageName, succeeded);
18370                    } catch (RemoteException e) {
18371                        Log.i(TAG, "Observer no longer exists.");
18372                    }
18373                } //end if observer
18374            } //end run
18375        });
18376    }
18377
18378    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18379        if (packageName == null) {
18380            Slog.w(TAG, "Attempt to delete null packageName.");
18381            return false;
18382        }
18383
18384        // Try finding details about the requested package
18385        PackageParser.Package pkg;
18386        synchronized (mPackages) {
18387            pkg = mPackages.get(packageName);
18388            if (pkg == null) {
18389                final PackageSetting ps = mSettings.mPackages.get(packageName);
18390                if (ps != null) {
18391                    pkg = ps.pkg;
18392                }
18393            }
18394
18395            if (pkg == null) {
18396                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18397                return false;
18398            }
18399
18400            PackageSetting ps = (PackageSetting) pkg.mExtras;
18401            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18402        }
18403
18404        clearAppDataLIF(pkg, userId,
18405                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18406
18407        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18408        removeKeystoreDataIfNeeded(userId, appId);
18409
18410        UserManagerInternal umInternal = getUserManagerInternal();
18411        final int flags;
18412        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18413            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18414        } else if (umInternal.isUserRunning(userId)) {
18415            flags = StorageManager.FLAG_STORAGE_DE;
18416        } else {
18417            flags = 0;
18418        }
18419        prepareAppDataContentsLIF(pkg, userId, flags);
18420
18421        return true;
18422    }
18423
18424    /**
18425     * Reverts user permission state changes (permissions and flags) in
18426     * all packages for a given user.
18427     *
18428     * @param userId The device user for which to do a reset.
18429     */
18430    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18431        final int packageCount = mPackages.size();
18432        for (int i = 0; i < packageCount; i++) {
18433            PackageParser.Package pkg = mPackages.valueAt(i);
18434            PackageSetting ps = (PackageSetting) pkg.mExtras;
18435            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18436        }
18437    }
18438
18439    private void resetNetworkPolicies(int userId) {
18440        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18441    }
18442
18443    /**
18444     * Reverts user permission state changes (permissions and flags).
18445     *
18446     * @param ps The package for which to reset.
18447     * @param userId The device user for which to do a reset.
18448     */
18449    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18450            final PackageSetting ps, final int userId) {
18451        if (ps.pkg == null) {
18452            return;
18453        }
18454
18455        // These are flags that can change base on user actions.
18456        final int userSettableMask = FLAG_PERMISSION_USER_SET
18457                | FLAG_PERMISSION_USER_FIXED
18458                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18459                | FLAG_PERMISSION_REVIEW_REQUIRED;
18460
18461        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18462                | FLAG_PERMISSION_POLICY_FIXED;
18463
18464        boolean writeInstallPermissions = false;
18465        boolean writeRuntimePermissions = false;
18466
18467        final int permissionCount = ps.pkg.requestedPermissions.size();
18468        for (int i = 0; i < permissionCount; i++) {
18469            String permission = ps.pkg.requestedPermissions.get(i);
18470
18471            BasePermission bp = mSettings.mPermissions.get(permission);
18472            if (bp == null) {
18473                continue;
18474            }
18475
18476            // If shared user we just reset the state to which only this app contributed.
18477            if (ps.sharedUser != null) {
18478                boolean used = false;
18479                final int packageCount = ps.sharedUser.packages.size();
18480                for (int j = 0; j < packageCount; j++) {
18481                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18482                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18483                            && pkg.pkg.requestedPermissions.contains(permission)) {
18484                        used = true;
18485                        break;
18486                    }
18487                }
18488                if (used) {
18489                    continue;
18490                }
18491            }
18492
18493            PermissionsState permissionsState = ps.getPermissionsState();
18494
18495            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18496
18497            // Always clear the user settable flags.
18498            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18499                    bp.name) != null;
18500            // If permission review is enabled and this is a legacy app, mark the
18501            // permission as requiring a review as this is the initial state.
18502            int flags = 0;
18503            if (mPermissionReviewRequired
18504                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18505                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18506            }
18507            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18508                if (hasInstallState) {
18509                    writeInstallPermissions = true;
18510                } else {
18511                    writeRuntimePermissions = true;
18512                }
18513            }
18514
18515            // Below is only runtime permission handling.
18516            if (!bp.isRuntime()) {
18517                continue;
18518            }
18519
18520            // Never clobber system or policy.
18521            if ((oldFlags & policyOrSystemFlags) != 0) {
18522                continue;
18523            }
18524
18525            // If this permission was granted by default, make sure it is.
18526            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18527                if (permissionsState.grantRuntimePermission(bp, userId)
18528                        != PERMISSION_OPERATION_FAILURE) {
18529                    writeRuntimePermissions = true;
18530                }
18531            // If permission review is enabled the permissions for a legacy apps
18532            // are represented as constantly granted runtime ones, so don't revoke.
18533            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18534                // Otherwise, reset the permission.
18535                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18536                switch (revokeResult) {
18537                    case PERMISSION_OPERATION_SUCCESS:
18538                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18539                        writeRuntimePermissions = true;
18540                        final int appId = ps.appId;
18541                        mHandler.post(new Runnable() {
18542                            @Override
18543                            public void run() {
18544                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18545                            }
18546                        });
18547                    } break;
18548                }
18549            }
18550        }
18551
18552        // Synchronously write as we are taking permissions away.
18553        if (writeRuntimePermissions) {
18554            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18555        }
18556
18557        // Synchronously write as we are taking permissions away.
18558        if (writeInstallPermissions) {
18559            mSettings.writeLPr();
18560        }
18561    }
18562
18563    /**
18564     * Remove entries from the keystore daemon. Will only remove it if the
18565     * {@code appId} is valid.
18566     */
18567    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18568        if (appId < 0) {
18569            return;
18570        }
18571
18572        final KeyStore keyStore = KeyStore.getInstance();
18573        if (keyStore != null) {
18574            if (userId == UserHandle.USER_ALL) {
18575                for (final int individual : sUserManager.getUserIds()) {
18576                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18577                }
18578            } else {
18579                keyStore.clearUid(UserHandle.getUid(userId, appId));
18580            }
18581        } else {
18582            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18583        }
18584    }
18585
18586    @Override
18587    public void deleteApplicationCacheFiles(final String packageName,
18588            final IPackageDataObserver observer) {
18589        final int userId = UserHandle.getCallingUserId();
18590        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18591    }
18592
18593    @Override
18594    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18595            final IPackageDataObserver observer) {
18596        mContext.enforceCallingOrSelfPermission(
18597                android.Manifest.permission.DELETE_CACHE_FILES, null);
18598        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18599                /* requireFullPermission= */ true, /* checkShell= */ false,
18600                "delete application cache files");
18601
18602        final PackageParser.Package pkg;
18603        synchronized (mPackages) {
18604            pkg = mPackages.get(packageName);
18605        }
18606
18607        // Queue up an async operation since the package deletion may take a little while.
18608        mHandler.post(new Runnable() {
18609            public void run() {
18610                synchronized (mInstallLock) {
18611                    final int flags = StorageManager.FLAG_STORAGE_DE
18612                            | StorageManager.FLAG_STORAGE_CE;
18613                    // We're only clearing cache files, so we don't care if the
18614                    // app is unfrozen and still able to run
18615                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18616                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18617                }
18618                clearExternalStorageDataSync(packageName, userId, false);
18619                if (observer != null) {
18620                    try {
18621                        observer.onRemoveCompleted(packageName, true);
18622                    } catch (RemoteException e) {
18623                        Log.i(TAG, "Observer no longer exists.");
18624                    }
18625                }
18626            }
18627        });
18628    }
18629
18630    @Override
18631    public void getPackageSizeInfo(final String packageName, int userHandle,
18632            final IPackageStatsObserver observer) {
18633        mContext.enforceCallingOrSelfPermission(
18634                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18635        if (packageName == null) {
18636            throw new IllegalArgumentException("Attempt to get size of null packageName");
18637        }
18638
18639        PackageStats stats = new PackageStats(packageName, userHandle);
18640
18641        /*
18642         * Queue up an async operation since the package measurement may take a
18643         * little while.
18644         */
18645        Message msg = mHandler.obtainMessage(INIT_COPY);
18646        msg.obj = new MeasureParams(stats, observer);
18647        mHandler.sendMessage(msg);
18648    }
18649
18650    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18651        final PackageSetting ps;
18652        synchronized (mPackages) {
18653            ps = mSettings.mPackages.get(packageName);
18654            if (ps == null) {
18655                Slog.w(TAG, "Failed to find settings for " + packageName);
18656                return false;
18657            }
18658        }
18659
18660        final String[] packageNames = { packageName };
18661        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18662        final String[] codePaths = { ps.codePathString };
18663
18664        try {
18665            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18666                    ps.appId, ceDataInodes, codePaths, stats);
18667
18668            // For now, ignore code size of packages on system partition
18669            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18670                stats.codeSize = 0;
18671            }
18672
18673            // External clients expect these to be tracked separately
18674            stats.dataSize -= stats.cacheSize;
18675
18676        } catch (InstallerException e) {
18677            Slog.w(TAG, String.valueOf(e));
18678            return false;
18679        }
18680
18681        return true;
18682    }
18683
18684    private int getUidTargetSdkVersionLockedLPr(int uid) {
18685        Object obj = mSettings.getUserIdLPr(uid);
18686        if (obj instanceof SharedUserSetting) {
18687            final SharedUserSetting sus = (SharedUserSetting) obj;
18688            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18689            final Iterator<PackageSetting> it = sus.packages.iterator();
18690            while (it.hasNext()) {
18691                final PackageSetting ps = it.next();
18692                if (ps.pkg != null) {
18693                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18694                    if (v < vers) vers = v;
18695                }
18696            }
18697            return vers;
18698        } else if (obj instanceof PackageSetting) {
18699            final PackageSetting ps = (PackageSetting) obj;
18700            if (ps.pkg != null) {
18701                return ps.pkg.applicationInfo.targetSdkVersion;
18702            }
18703        }
18704        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18705    }
18706
18707    @Override
18708    public void addPreferredActivity(IntentFilter filter, int match,
18709            ComponentName[] set, ComponentName activity, int userId) {
18710        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18711                "Adding preferred");
18712    }
18713
18714    private void addPreferredActivityInternal(IntentFilter filter, int match,
18715            ComponentName[] set, ComponentName activity, boolean always, int userId,
18716            String opname) {
18717        // writer
18718        int callingUid = Binder.getCallingUid();
18719        enforceCrossUserPermission(callingUid, userId,
18720                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18721        if (filter.countActions() == 0) {
18722            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18723            return;
18724        }
18725        synchronized (mPackages) {
18726            if (mContext.checkCallingOrSelfPermission(
18727                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18728                    != PackageManager.PERMISSION_GRANTED) {
18729                if (getUidTargetSdkVersionLockedLPr(callingUid)
18730                        < Build.VERSION_CODES.FROYO) {
18731                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18732                            + callingUid);
18733                    return;
18734                }
18735                mContext.enforceCallingOrSelfPermission(
18736                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18737            }
18738
18739            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18740            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18741                    + userId + ":");
18742            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18743            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18744            scheduleWritePackageRestrictionsLocked(userId);
18745            postPreferredActivityChangedBroadcast(userId);
18746        }
18747    }
18748
18749    private void postPreferredActivityChangedBroadcast(int userId) {
18750        mHandler.post(() -> {
18751            final IActivityManager am = ActivityManager.getService();
18752            if (am == null) {
18753                return;
18754            }
18755
18756            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18757            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18758            try {
18759                am.broadcastIntent(null, intent, null, null,
18760                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18761                        null, false, false, userId);
18762            } catch (RemoteException e) {
18763            }
18764        });
18765    }
18766
18767    @Override
18768    public void replacePreferredActivity(IntentFilter filter, int match,
18769            ComponentName[] set, ComponentName activity, int userId) {
18770        if (filter.countActions() != 1) {
18771            throw new IllegalArgumentException(
18772                    "replacePreferredActivity expects filter to have only 1 action.");
18773        }
18774        if (filter.countDataAuthorities() != 0
18775                || filter.countDataPaths() != 0
18776                || filter.countDataSchemes() > 1
18777                || filter.countDataTypes() != 0) {
18778            throw new IllegalArgumentException(
18779                    "replacePreferredActivity expects filter to have no data authorities, " +
18780                    "paths, or types; and at most one scheme.");
18781        }
18782
18783        final int callingUid = Binder.getCallingUid();
18784        enforceCrossUserPermission(callingUid, userId,
18785                true /* requireFullPermission */, false /* checkShell */,
18786                "replace preferred activity");
18787        synchronized (mPackages) {
18788            if (mContext.checkCallingOrSelfPermission(
18789                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18790                    != PackageManager.PERMISSION_GRANTED) {
18791                if (getUidTargetSdkVersionLockedLPr(callingUid)
18792                        < Build.VERSION_CODES.FROYO) {
18793                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18794                            + Binder.getCallingUid());
18795                    return;
18796                }
18797                mContext.enforceCallingOrSelfPermission(
18798                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18799            }
18800
18801            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18802            if (pir != null) {
18803                // Get all of the existing entries that exactly match this filter.
18804                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18805                if (existing != null && existing.size() == 1) {
18806                    PreferredActivity cur = existing.get(0);
18807                    if (DEBUG_PREFERRED) {
18808                        Slog.i(TAG, "Checking replace of preferred:");
18809                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18810                        if (!cur.mPref.mAlways) {
18811                            Slog.i(TAG, "  -- CUR; not mAlways!");
18812                        } else {
18813                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18814                            Slog.i(TAG, "  -- CUR: mSet="
18815                                    + Arrays.toString(cur.mPref.mSetComponents));
18816                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18817                            Slog.i(TAG, "  -- NEW: mMatch="
18818                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18819                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18820                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18821                        }
18822                    }
18823                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18824                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18825                            && cur.mPref.sameSet(set)) {
18826                        // Setting the preferred activity to what it happens to be already
18827                        if (DEBUG_PREFERRED) {
18828                            Slog.i(TAG, "Replacing with same preferred activity "
18829                                    + cur.mPref.mShortComponent + " for user "
18830                                    + userId + ":");
18831                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18832                        }
18833                        return;
18834                    }
18835                }
18836
18837                if (existing != null) {
18838                    if (DEBUG_PREFERRED) {
18839                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18840                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18841                    }
18842                    for (int i = 0; i < existing.size(); i++) {
18843                        PreferredActivity pa = existing.get(i);
18844                        if (DEBUG_PREFERRED) {
18845                            Slog.i(TAG, "Removing existing preferred activity "
18846                                    + pa.mPref.mComponent + ":");
18847                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18848                        }
18849                        pir.removeFilter(pa);
18850                    }
18851                }
18852            }
18853            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18854                    "Replacing preferred");
18855        }
18856    }
18857
18858    @Override
18859    public void clearPackagePreferredActivities(String packageName) {
18860        final int uid = Binder.getCallingUid();
18861        // writer
18862        synchronized (mPackages) {
18863            PackageParser.Package pkg = mPackages.get(packageName);
18864            if (pkg == null || pkg.applicationInfo.uid != uid) {
18865                if (mContext.checkCallingOrSelfPermission(
18866                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18867                        != PackageManager.PERMISSION_GRANTED) {
18868                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18869                            < Build.VERSION_CODES.FROYO) {
18870                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18871                                + Binder.getCallingUid());
18872                        return;
18873                    }
18874                    mContext.enforceCallingOrSelfPermission(
18875                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18876                }
18877            }
18878
18879            int user = UserHandle.getCallingUserId();
18880            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18881                scheduleWritePackageRestrictionsLocked(user);
18882            }
18883        }
18884    }
18885
18886    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18887    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18888        ArrayList<PreferredActivity> removed = null;
18889        boolean changed = false;
18890        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18891            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18892            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18893            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18894                continue;
18895            }
18896            Iterator<PreferredActivity> it = pir.filterIterator();
18897            while (it.hasNext()) {
18898                PreferredActivity pa = it.next();
18899                // Mark entry for removal only if it matches the package name
18900                // and the entry is of type "always".
18901                if (packageName == null ||
18902                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18903                                && pa.mPref.mAlways)) {
18904                    if (removed == null) {
18905                        removed = new ArrayList<PreferredActivity>();
18906                    }
18907                    removed.add(pa);
18908                }
18909            }
18910            if (removed != null) {
18911                for (int j=0; j<removed.size(); j++) {
18912                    PreferredActivity pa = removed.get(j);
18913                    pir.removeFilter(pa);
18914                }
18915                changed = true;
18916            }
18917        }
18918        if (changed) {
18919            postPreferredActivityChangedBroadcast(userId);
18920        }
18921        return changed;
18922    }
18923
18924    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18925    private void clearIntentFilterVerificationsLPw(int userId) {
18926        final int packageCount = mPackages.size();
18927        for (int i = 0; i < packageCount; i++) {
18928            PackageParser.Package pkg = mPackages.valueAt(i);
18929            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18930        }
18931    }
18932
18933    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18934    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18935        if (userId == UserHandle.USER_ALL) {
18936            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18937                    sUserManager.getUserIds())) {
18938                for (int oneUserId : sUserManager.getUserIds()) {
18939                    scheduleWritePackageRestrictionsLocked(oneUserId);
18940                }
18941            }
18942        } else {
18943            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18944                scheduleWritePackageRestrictionsLocked(userId);
18945            }
18946        }
18947    }
18948
18949    void clearDefaultBrowserIfNeeded(String packageName) {
18950        for (int oneUserId : sUserManager.getUserIds()) {
18951            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18952            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18953            if (packageName.equals(defaultBrowserPackageName)) {
18954                setDefaultBrowserPackageName(null, oneUserId);
18955            }
18956        }
18957    }
18958
18959    @Override
18960    public void resetApplicationPreferences(int userId) {
18961        mContext.enforceCallingOrSelfPermission(
18962                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18963        final long identity = Binder.clearCallingIdentity();
18964        // writer
18965        try {
18966            synchronized (mPackages) {
18967                clearPackagePreferredActivitiesLPw(null, userId);
18968                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18969                // TODO: We have to reset the default SMS and Phone. This requires
18970                // significant refactoring to keep all default apps in the package
18971                // manager (cleaner but more work) or have the services provide
18972                // callbacks to the package manager to request a default app reset.
18973                applyFactoryDefaultBrowserLPw(userId);
18974                clearIntentFilterVerificationsLPw(userId);
18975                primeDomainVerificationsLPw(userId);
18976                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18977                scheduleWritePackageRestrictionsLocked(userId);
18978            }
18979            resetNetworkPolicies(userId);
18980        } finally {
18981            Binder.restoreCallingIdentity(identity);
18982        }
18983    }
18984
18985    @Override
18986    public int getPreferredActivities(List<IntentFilter> outFilters,
18987            List<ComponentName> outActivities, String packageName) {
18988
18989        int num = 0;
18990        final int userId = UserHandle.getCallingUserId();
18991        // reader
18992        synchronized (mPackages) {
18993            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18994            if (pir != null) {
18995                final Iterator<PreferredActivity> it = pir.filterIterator();
18996                while (it.hasNext()) {
18997                    final PreferredActivity pa = it.next();
18998                    if (packageName == null
18999                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19000                                    && pa.mPref.mAlways)) {
19001                        if (outFilters != null) {
19002                            outFilters.add(new IntentFilter(pa));
19003                        }
19004                        if (outActivities != null) {
19005                            outActivities.add(pa.mPref.mComponent);
19006                        }
19007                    }
19008                }
19009            }
19010        }
19011
19012        return num;
19013    }
19014
19015    @Override
19016    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19017            int userId) {
19018        int callingUid = Binder.getCallingUid();
19019        if (callingUid != Process.SYSTEM_UID) {
19020            throw new SecurityException(
19021                    "addPersistentPreferredActivity can only be run by the system");
19022        }
19023        if (filter.countActions() == 0) {
19024            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19025            return;
19026        }
19027        synchronized (mPackages) {
19028            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19029                    ":");
19030            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19031            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19032                    new PersistentPreferredActivity(filter, activity));
19033            scheduleWritePackageRestrictionsLocked(userId);
19034            postPreferredActivityChangedBroadcast(userId);
19035        }
19036    }
19037
19038    @Override
19039    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19040        int callingUid = Binder.getCallingUid();
19041        if (callingUid != Process.SYSTEM_UID) {
19042            throw new SecurityException(
19043                    "clearPackagePersistentPreferredActivities can only be run by the system");
19044        }
19045        ArrayList<PersistentPreferredActivity> removed = null;
19046        boolean changed = false;
19047        synchronized (mPackages) {
19048            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19049                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19050                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19051                        .valueAt(i);
19052                if (userId != thisUserId) {
19053                    continue;
19054                }
19055                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19056                while (it.hasNext()) {
19057                    PersistentPreferredActivity ppa = it.next();
19058                    // Mark entry for removal only if it matches the package name.
19059                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19060                        if (removed == null) {
19061                            removed = new ArrayList<PersistentPreferredActivity>();
19062                        }
19063                        removed.add(ppa);
19064                    }
19065                }
19066                if (removed != null) {
19067                    for (int j=0; j<removed.size(); j++) {
19068                        PersistentPreferredActivity ppa = removed.get(j);
19069                        ppir.removeFilter(ppa);
19070                    }
19071                    changed = true;
19072                }
19073            }
19074
19075            if (changed) {
19076                scheduleWritePackageRestrictionsLocked(userId);
19077                postPreferredActivityChangedBroadcast(userId);
19078            }
19079        }
19080    }
19081
19082    /**
19083     * Common machinery for picking apart a restored XML blob and passing
19084     * it to a caller-supplied functor to be applied to the running system.
19085     */
19086    private void restoreFromXml(XmlPullParser parser, int userId,
19087            String expectedStartTag, BlobXmlRestorer functor)
19088            throws IOException, XmlPullParserException {
19089        int type;
19090        while ((type = parser.next()) != XmlPullParser.START_TAG
19091                && type != XmlPullParser.END_DOCUMENT) {
19092        }
19093        if (type != XmlPullParser.START_TAG) {
19094            // oops didn't find a start tag?!
19095            if (DEBUG_BACKUP) {
19096                Slog.e(TAG, "Didn't find start tag during restore");
19097            }
19098            return;
19099        }
19100Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19101        // this is supposed to be TAG_PREFERRED_BACKUP
19102        if (!expectedStartTag.equals(parser.getName())) {
19103            if (DEBUG_BACKUP) {
19104                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19105            }
19106            return;
19107        }
19108
19109        // skip interfering stuff, then we're aligned with the backing implementation
19110        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19111Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19112        functor.apply(parser, userId);
19113    }
19114
19115    private interface BlobXmlRestorer {
19116        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19117    }
19118
19119    /**
19120     * Non-Binder method, support for the backup/restore mechanism: write the
19121     * full set of preferred activities in its canonical XML format.  Returns the
19122     * XML output as a byte array, or null if there is none.
19123     */
19124    @Override
19125    public byte[] getPreferredActivityBackup(int userId) {
19126        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19127            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19128        }
19129
19130        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19131        try {
19132            final XmlSerializer serializer = new FastXmlSerializer();
19133            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19134            serializer.startDocument(null, true);
19135            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19136
19137            synchronized (mPackages) {
19138                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19139            }
19140
19141            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19142            serializer.endDocument();
19143            serializer.flush();
19144        } catch (Exception e) {
19145            if (DEBUG_BACKUP) {
19146                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19147            }
19148            return null;
19149        }
19150
19151        return dataStream.toByteArray();
19152    }
19153
19154    @Override
19155    public void restorePreferredActivities(byte[] backup, int userId) {
19156        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19157            throw new SecurityException("Only the system may call restorePreferredActivities()");
19158        }
19159
19160        try {
19161            final XmlPullParser parser = Xml.newPullParser();
19162            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19163            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19164                    new BlobXmlRestorer() {
19165                        @Override
19166                        public void apply(XmlPullParser parser, int userId)
19167                                throws XmlPullParserException, IOException {
19168                            synchronized (mPackages) {
19169                                mSettings.readPreferredActivitiesLPw(parser, userId);
19170                            }
19171                        }
19172                    } );
19173        } catch (Exception e) {
19174            if (DEBUG_BACKUP) {
19175                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19176            }
19177        }
19178    }
19179
19180    /**
19181     * Non-Binder method, support for the backup/restore mechanism: write the
19182     * default browser (etc) settings in its canonical XML format.  Returns the default
19183     * browser XML representation as a byte array, or null if there is none.
19184     */
19185    @Override
19186    public byte[] getDefaultAppsBackup(int userId) {
19187        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19188            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19189        }
19190
19191        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19192        try {
19193            final XmlSerializer serializer = new FastXmlSerializer();
19194            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19195            serializer.startDocument(null, true);
19196            serializer.startTag(null, TAG_DEFAULT_APPS);
19197
19198            synchronized (mPackages) {
19199                mSettings.writeDefaultAppsLPr(serializer, userId);
19200            }
19201
19202            serializer.endTag(null, TAG_DEFAULT_APPS);
19203            serializer.endDocument();
19204            serializer.flush();
19205        } catch (Exception e) {
19206            if (DEBUG_BACKUP) {
19207                Slog.e(TAG, "Unable to write default apps for backup", e);
19208            }
19209            return null;
19210        }
19211
19212        return dataStream.toByteArray();
19213    }
19214
19215    @Override
19216    public void restoreDefaultApps(byte[] backup, int userId) {
19217        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19218            throw new SecurityException("Only the system may call restoreDefaultApps()");
19219        }
19220
19221        try {
19222            final XmlPullParser parser = Xml.newPullParser();
19223            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19224            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19225                    new BlobXmlRestorer() {
19226                        @Override
19227                        public void apply(XmlPullParser parser, int userId)
19228                                throws XmlPullParserException, IOException {
19229                            synchronized (mPackages) {
19230                                mSettings.readDefaultAppsLPw(parser, userId);
19231                            }
19232                        }
19233                    } );
19234        } catch (Exception e) {
19235            if (DEBUG_BACKUP) {
19236                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19237            }
19238        }
19239    }
19240
19241    @Override
19242    public byte[] getIntentFilterVerificationBackup(int userId) {
19243        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19244            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19245        }
19246
19247        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19248        try {
19249            final XmlSerializer serializer = new FastXmlSerializer();
19250            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19251            serializer.startDocument(null, true);
19252            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19253
19254            synchronized (mPackages) {
19255                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19256            }
19257
19258            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19259            serializer.endDocument();
19260            serializer.flush();
19261        } catch (Exception e) {
19262            if (DEBUG_BACKUP) {
19263                Slog.e(TAG, "Unable to write default apps for backup", e);
19264            }
19265            return null;
19266        }
19267
19268        return dataStream.toByteArray();
19269    }
19270
19271    @Override
19272    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19273        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19274            throw new SecurityException("Only the system may call restorePreferredActivities()");
19275        }
19276
19277        try {
19278            final XmlPullParser parser = Xml.newPullParser();
19279            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19280            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19281                    new BlobXmlRestorer() {
19282                        @Override
19283                        public void apply(XmlPullParser parser, int userId)
19284                                throws XmlPullParserException, IOException {
19285                            synchronized (mPackages) {
19286                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19287                                mSettings.writeLPr();
19288                            }
19289                        }
19290                    } );
19291        } catch (Exception e) {
19292            if (DEBUG_BACKUP) {
19293                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19294            }
19295        }
19296    }
19297
19298    @Override
19299    public byte[] getPermissionGrantBackup(int userId) {
19300        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19301            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19302        }
19303
19304        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19305        try {
19306            final XmlSerializer serializer = new FastXmlSerializer();
19307            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19308            serializer.startDocument(null, true);
19309            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19310
19311            synchronized (mPackages) {
19312                serializeRuntimePermissionGrantsLPr(serializer, userId);
19313            }
19314
19315            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19316            serializer.endDocument();
19317            serializer.flush();
19318        } catch (Exception e) {
19319            if (DEBUG_BACKUP) {
19320                Slog.e(TAG, "Unable to write default apps for backup", e);
19321            }
19322            return null;
19323        }
19324
19325        return dataStream.toByteArray();
19326    }
19327
19328    @Override
19329    public void restorePermissionGrants(byte[] backup, int userId) {
19330        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19331            throw new SecurityException("Only the system may call restorePermissionGrants()");
19332        }
19333
19334        try {
19335            final XmlPullParser parser = Xml.newPullParser();
19336            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19337            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19338                    new BlobXmlRestorer() {
19339                        @Override
19340                        public void apply(XmlPullParser parser, int userId)
19341                                throws XmlPullParserException, IOException {
19342                            synchronized (mPackages) {
19343                                processRestoredPermissionGrantsLPr(parser, userId);
19344                            }
19345                        }
19346                    } );
19347        } catch (Exception e) {
19348            if (DEBUG_BACKUP) {
19349                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19350            }
19351        }
19352    }
19353
19354    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19355            throws IOException {
19356        serializer.startTag(null, TAG_ALL_GRANTS);
19357
19358        final int N = mSettings.mPackages.size();
19359        for (int i = 0; i < N; i++) {
19360            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19361            boolean pkgGrantsKnown = false;
19362
19363            PermissionsState packagePerms = ps.getPermissionsState();
19364
19365            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19366                final int grantFlags = state.getFlags();
19367                // only look at grants that are not system/policy fixed
19368                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19369                    final boolean isGranted = state.isGranted();
19370                    // And only back up the user-twiddled state bits
19371                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19372                        final String packageName = mSettings.mPackages.keyAt(i);
19373                        if (!pkgGrantsKnown) {
19374                            serializer.startTag(null, TAG_GRANT);
19375                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19376                            pkgGrantsKnown = true;
19377                        }
19378
19379                        final boolean userSet =
19380                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19381                        final boolean userFixed =
19382                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19383                        final boolean revoke =
19384                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19385
19386                        serializer.startTag(null, TAG_PERMISSION);
19387                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19388                        if (isGranted) {
19389                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19390                        }
19391                        if (userSet) {
19392                            serializer.attribute(null, ATTR_USER_SET, "true");
19393                        }
19394                        if (userFixed) {
19395                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19396                        }
19397                        if (revoke) {
19398                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19399                        }
19400                        serializer.endTag(null, TAG_PERMISSION);
19401                    }
19402                }
19403            }
19404
19405            if (pkgGrantsKnown) {
19406                serializer.endTag(null, TAG_GRANT);
19407            }
19408        }
19409
19410        serializer.endTag(null, TAG_ALL_GRANTS);
19411    }
19412
19413    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19414            throws XmlPullParserException, IOException {
19415        String pkgName = null;
19416        int outerDepth = parser.getDepth();
19417        int type;
19418        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19419                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19420            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19421                continue;
19422            }
19423
19424            final String tagName = parser.getName();
19425            if (tagName.equals(TAG_GRANT)) {
19426                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19427                if (DEBUG_BACKUP) {
19428                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19429                }
19430            } else if (tagName.equals(TAG_PERMISSION)) {
19431
19432                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19433                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19434
19435                int newFlagSet = 0;
19436                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19437                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19438                }
19439                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19440                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19441                }
19442                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19443                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19444                }
19445                if (DEBUG_BACKUP) {
19446                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19447                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19448                }
19449                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19450                if (ps != null) {
19451                    // Already installed so we apply the grant immediately
19452                    if (DEBUG_BACKUP) {
19453                        Slog.v(TAG, "        + already installed; applying");
19454                    }
19455                    PermissionsState perms = ps.getPermissionsState();
19456                    BasePermission bp = mSettings.mPermissions.get(permName);
19457                    if (bp != null) {
19458                        if (isGranted) {
19459                            perms.grantRuntimePermission(bp, userId);
19460                        }
19461                        if (newFlagSet != 0) {
19462                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19463                        }
19464                    }
19465                } else {
19466                    // Need to wait for post-restore install to apply the grant
19467                    if (DEBUG_BACKUP) {
19468                        Slog.v(TAG, "        - not yet installed; saving for later");
19469                    }
19470                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19471                            isGranted, newFlagSet, userId);
19472                }
19473            } else {
19474                PackageManagerService.reportSettingsProblem(Log.WARN,
19475                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19476                XmlUtils.skipCurrentTag(parser);
19477            }
19478        }
19479
19480        scheduleWriteSettingsLocked();
19481        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19482    }
19483
19484    @Override
19485    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19486            int sourceUserId, int targetUserId, int flags) {
19487        mContext.enforceCallingOrSelfPermission(
19488                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19489        int callingUid = Binder.getCallingUid();
19490        enforceOwnerRights(ownerPackage, callingUid);
19491        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19492        if (intentFilter.countActions() == 0) {
19493            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19494            return;
19495        }
19496        synchronized (mPackages) {
19497            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19498                    ownerPackage, targetUserId, flags);
19499            CrossProfileIntentResolver resolver =
19500                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19501            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19502            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19503            if (existing != null) {
19504                int size = existing.size();
19505                for (int i = 0; i < size; i++) {
19506                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19507                        return;
19508                    }
19509                }
19510            }
19511            resolver.addFilter(newFilter);
19512            scheduleWritePackageRestrictionsLocked(sourceUserId);
19513        }
19514    }
19515
19516    @Override
19517    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19518        mContext.enforceCallingOrSelfPermission(
19519                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19520        int callingUid = Binder.getCallingUid();
19521        enforceOwnerRights(ownerPackage, callingUid);
19522        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19523        synchronized (mPackages) {
19524            CrossProfileIntentResolver resolver =
19525                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19526            ArraySet<CrossProfileIntentFilter> set =
19527                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19528            for (CrossProfileIntentFilter filter : set) {
19529                if (filter.getOwnerPackage().equals(ownerPackage)) {
19530                    resolver.removeFilter(filter);
19531                }
19532            }
19533            scheduleWritePackageRestrictionsLocked(sourceUserId);
19534        }
19535    }
19536
19537    // Enforcing that callingUid is owning pkg on userId
19538    private void enforceOwnerRights(String pkg, int callingUid) {
19539        // The system owns everything.
19540        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19541            return;
19542        }
19543        int callingUserId = UserHandle.getUserId(callingUid);
19544        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19545        if (pi == null) {
19546            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19547                    + callingUserId);
19548        }
19549        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19550            throw new SecurityException("Calling uid " + callingUid
19551                    + " does not own package " + pkg);
19552        }
19553    }
19554
19555    @Override
19556    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19557        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19558    }
19559
19560    private Intent getHomeIntent() {
19561        Intent intent = new Intent(Intent.ACTION_MAIN);
19562        intent.addCategory(Intent.CATEGORY_HOME);
19563        intent.addCategory(Intent.CATEGORY_DEFAULT);
19564        return intent;
19565    }
19566
19567    private IntentFilter getHomeFilter() {
19568        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19569        filter.addCategory(Intent.CATEGORY_HOME);
19570        filter.addCategory(Intent.CATEGORY_DEFAULT);
19571        return filter;
19572    }
19573
19574    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19575            int userId) {
19576        Intent intent  = getHomeIntent();
19577        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19578                PackageManager.GET_META_DATA, userId);
19579        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19580                true, false, false, userId);
19581
19582        allHomeCandidates.clear();
19583        if (list != null) {
19584            for (ResolveInfo ri : list) {
19585                allHomeCandidates.add(ri);
19586            }
19587        }
19588        return (preferred == null || preferred.activityInfo == null)
19589                ? null
19590                : new ComponentName(preferred.activityInfo.packageName,
19591                        preferred.activityInfo.name);
19592    }
19593
19594    @Override
19595    public void setHomeActivity(ComponentName comp, int userId) {
19596        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19597        getHomeActivitiesAsUser(homeActivities, userId);
19598
19599        boolean found = false;
19600
19601        final int size = homeActivities.size();
19602        final ComponentName[] set = new ComponentName[size];
19603        for (int i = 0; i < size; i++) {
19604            final ResolveInfo candidate = homeActivities.get(i);
19605            final ActivityInfo info = candidate.activityInfo;
19606            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19607            set[i] = activityName;
19608            if (!found && activityName.equals(comp)) {
19609                found = true;
19610            }
19611        }
19612        if (!found) {
19613            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19614                    + userId);
19615        }
19616        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19617                set, comp, userId);
19618    }
19619
19620    private @Nullable String getSetupWizardPackageName() {
19621        final Intent intent = new Intent(Intent.ACTION_MAIN);
19622        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19623
19624        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19625                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19626                        | MATCH_DISABLED_COMPONENTS,
19627                UserHandle.myUserId());
19628        if (matches.size() == 1) {
19629            return matches.get(0).getComponentInfo().packageName;
19630        } else {
19631            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19632                    + ": matches=" + matches);
19633            return null;
19634        }
19635    }
19636
19637    private @Nullable String getStorageManagerPackageName() {
19638        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19639
19640        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19641                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19642                        | MATCH_DISABLED_COMPONENTS,
19643                UserHandle.myUserId());
19644        if (matches.size() == 1) {
19645            return matches.get(0).getComponentInfo().packageName;
19646        } else {
19647            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19648                    + matches.size() + ": matches=" + matches);
19649            return null;
19650        }
19651    }
19652
19653    @Override
19654    public void setApplicationEnabledSetting(String appPackageName,
19655            int newState, int flags, int userId, String callingPackage) {
19656        if (!sUserManager.exists(userId)) return;
19657        if (callingPackage == null) {
19658            callingPackage = Integer.toString(Binder.getCallingUid());
19659        }
19660        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19661    }
19662
19663    @Override
19664    public void setComponentEnabledSetting(ComponentName componentName,
19665            int newState, int flags, int userId) {
19666        if (!sUserManager.exists(userId)) return;
19667        setEnabledSetting(componentName.getPackageName(),
19668                componentName.getClassName(), newState, flags, userId, null);
19669    }
19670
19671    private void setEnabledSetting(final String packageName, String className, int newState,
19672            final int flags, int userId, String callingPackage) {
19673        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19674              || newState == COMPONENT_ENABLED_STATE_ENABLED
19675              || newState == COMPONENT_ENABLED_STATE_DISABLED
19676              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19677              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19678            throw new IllegalArgumentException("Invalid new component state: "
19679                    + newState);
19680        }
19681        PackageSetting pkgSetting;
19682        final int uid = Binder.getCallingUid();
19683        final int permission;
19684        if (uid == Process.SYSTEM_UID) {
19685            permission = PackageManager.PERMISSION_GRANTED;
19686        } else {
19687            permission = mContext.checkCallingOrSelfPermission(
19688                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19689        }
19690        enforceCrossUserPermission(uid, userId,
19691                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19692        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19693        boolean sendNow = false;
19694        boolean isApp = (className == null);
19695        String componentName = isApp ? packageName : className;
19696        int packageUid = -1;
19697        ArrayList<String> components;
19698
19699        // writer
19700        synchronized (mPackages) {
19701            pkgSetting = mSettings.mPackages.get(packageName);
19702            if (pkgSetting == null) {
19703                if (className == null) {
19704                    throw new IllegalArgumentException("Unknown package: " + packageName);
19705                }
19706                throw new IllegalArgumentException(
19707                        "Unknown component: " + packageName + "/" + className);
19708            }
19709        }
19710
19711        // Limit who can change which apps
19712        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19713            // Don't allow apps that don't have permission to modify other apps
19714            if (!allowedByPermission) {
19715                throw new SecurityException(
19716                        "Permission Denial: attempt to change component state from pid="
19717                        + Binder.getCallingPid()
19718                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19719            }
19720            // Don't allow changing protected packages.
19721            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19722                throw new SecurityException("Cannot disable a protected package: " + packageName);
19723            }
19724        }
19725
19726        synchronized (mPackages) {
19727            if (uid == Process.SHELL_UID
19728                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19729                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19730                // unless it is a test package.
19731                int oldState = pkgSetting.getEnabled(userId);
19732                if (className == null
19733                    &&
19734                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19735                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19736                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19737                    &&
19738                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19739                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19740                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19741                    // ok
19742                } else {
19743                    throw new SecurityException(
19744                            "Shell cannot change component state for " + packageName + "/"
19745                            + className + " to " + newState);
19746                }
19747            }
19748            if (className == null) {
19749                // We're dealing with an application/package level state change
19750                if (pkgSetting.getEnabled(userId) == newState) {
19751                    // Nothing to do
19752                    return;
19753                }
19754                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19755                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19756                    // Don't care about who enables an app.
19757                    callingPackage = null;
19758                }
19759                pkgSetting.setEnabled(newState, userId, callingPackage);
19760                // pkgSetting.pkg.mSetEnabled = newState;
19761            } else {
19762                // We're dealing with a component level state change
19763                // First, verify that this is a valid class name.
19764                PackageParser.Package pkg = pkgSetting.pkg;
19765                if (pkg == null || !pkg.hasComponentClassName(className)) {
19766                    if (pkg != null &&
19767                            pkg.applicationInfo.targetSdkVersion >=
19768                                    Build.VERSION_CODES.JELLY_BEAN) {
19769                        throw new IllegalArgumentException("Component class " + className
19770                                + " does not exist in " + packageName);
19771                    } else {
19772                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19773                                + className + " does not exist in " + packageName);
19774                    }
19775                }
19776                switch (newState) {
19777                case COMPONENT_ENABLED_STATE_ENABLED:
19778                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19779                        return;
19780                    }
19781                    break;
19782                case COMPONENT_ENABLED_STATE_DISABLED:
19783                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19784                        return;
19785                    }
19786                    break;
19787                case COMPONENT_ENABLED_STATE_DEFAULT:
19788                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19789                        return;
19790                    }
19791                    break;
19792                default:
19793                    Slog.e(TAG, "Invalid new component state: " + newState);
19794                    return;
19795                }
19796            }
19797            scheduleWritePackageRestrictionsLocked(userId);
19798            updateSequenceNumberLP(packageName, new int[] { userId });
19799            components = mPendingBroadcasts.get(userId, packageName);
19800            final boolean newPackage = components == null;
19801            if (newPackage) {
19802                components = new ArrayList<String>();
19803            }
19804            if (!components.contains(componentName)) {
19805                components.add(componentName);
19806            }
19807            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19808                sendNow = true;
19809                // Purge entry from pending broadcast list if another one exists already
19810                // since we are sending one right away.
19811                mPendingBroadcasts.remove(userId, packageName);
19812            } else {
19813                if (newPackage) {
19814                    mPendingBroadcasts.put(userId, packageName, components);
19815                }
19816                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19817                    // Schedule a message
19818                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19819                }
19820            }
19821        }
19822
19823        long callingId = Binder.clearCallingIdentity();
19824        try {
19825            if (sendNow) {
19826                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19827                sendPackageChangedBroadcast(packageName,
19828                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19829            }
19830        } finally {
19831            Binder.restoreCallingIdentity(callingId);
19832        }
19833    }
19834
19835    @Override
19836    public void flushPackageRestrictionsAsUser(int userId) {
19837        if (!sUserManager.exists(userId)) {
19838            return;
19839        }
19840        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19841                false /* checkShell */, "flushPackageRestrictions");
19842        synchronized (mPackages) {
19843            mSettings.writePackageRestrictionsLPr(userId);
19844            mDirtyUsers.remove(userId);
19845            if (mDirtyUsers.isEmpty()) {
19846                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19847            }
19848        }
19849    }
19850
19851    private void sendPackageChangedBroadcast(String packageName,
19852            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19853        if (DEBUG_INSTALL)
19854            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19855                    + componentNames);
19856        Bundle extras = new Bundle(4);
19857        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19858        String nameList[] = new String[componentNames.size()];
19859        componentNames.toArray(nameList);
19860        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19861        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19862        extras.putInt(Intent.EXTRA_UID, packageUid);
19863        // If this is not reporting a change of the overall package, then only send it
19864        // to registered receivers.  We don't want to launch a swath of apps for every
19865        // little component state change.
19866        final int flags = !componentNames.contains(packageName)
19867                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19868        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19869                new int[] {UserHandle.getUserId(packageUid)});
19870    }
19871
19872    @Override
19873    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19874        if (!sUserManager.exists(userId)) return;
19875        final int uid = Binder.getCallingUid();
19876        final int permission = mContext.checkCallingOrSelfPermission(
19877                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19878        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19879        enforceCrossUserPermission(uid, userId,
19880                true /* requireFullPermission */, true /* checkShell */, "stop package");
19881        // writer
19882        synchronized (mPackages) {
19883            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19884                    allowedByPermission, uid, userId)) {
19885                scheduleWritePackageRestrictionsLocked(userId);
19886            }
19887        }
19888    }
19889
19890    @Override
19891    public String getInstallerPackageName(String packageName) {
19892        // reader
19893        synchronized (mPackages) {
19894            return mSettings.getInstallerPackageNameLPr(packageName);
19895        }
19896    }
19897
19898    public boolean isOrphaned(String packageName) {
19899        // reader
19900        synchronized (mPackages) {
19901            return mSettings.isOrphaned(packageName);
19902        }
19903    }
19904
19905    @Override
19906    public int getApplicationEnabledSetting(String packageName, int userId) {
19907        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19908        int uid = Binder.getCallingUid();
19909        enforceCrossUserPermission(uid, userId,
19910                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19911        // reader
19912        synchronized (mPackages) {
19913            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19914        }
19915    }
19916
19917    @Override
19918    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19919        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19920        int uid = Binder.getCallingUid();
19921        enforceCrossUserPermission(uid, userId,
19922                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19923        // reader
19924        synchronized (mPackages) {
19925            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19926        }
19927    }
19928
19929    @Override
19930    public void enterSafeMode() {
19931        enforceSystemOrRoot("Only the system can request entering safe mode");
19932
19933        if (!mSystemReady) {
19934            mSafeMode = true;
19935        }
19936    }
19937
19938    @Override
19939    public void systemReady() {
19940        mSystemReady = true;
19941
19942        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19943        // disabled after already being started.
19944        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19945                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19946
19947        // Read the compatibilty setting when the system is ready.
19948        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19949                mContext.getContentResolver(),
19950                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19951        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19952        if (DEBUG_SETTINGS) {
19953            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19954        }
19955
19956        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19957
19958        synchronized (mPackages) {
19959            // Verify that all of the preferred activity components actually
19960            // exist.  It is possible for applications to be updated and at
19961            // that point remove a previously declared activity component that
19962            // had been set as a preferred activity.  We try to clean this up
19963            // the next time we encounter that preferred activity, but it is
19964            // possible for the user flow to never be able to return to that
19965            // situation so here we do a sanity check to make sure we haven't
19966            // left any junk around.
19967            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19968            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19969                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19970                removed.clear();
19971                for (PreferredActivity pa : pir.filterSet()) {
19972                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19973                        removed.add(pa);
19974                    }
19975                }
19976                if (removed.size() > 0) {
19977                    for (int r=0; r<removed.size(); r++) {
19978                        PreferredActivity pa = removed.get(r);
19979                        Slog.w(TAG, "Removing dangling preferred activity: "
19980                                + pa.mPref.mComponent);
19981                        pir.removeFilter(pa);
19982                    }
19983                    mSettings.writePackageRestrictionsLPr(
19984                            mSettings.mPreferredActivities.keyAt(i));
19985                }
19986            }
19987
19988            for (int userId : UserManagerService.getInstance().getUserIds()) {
19989                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19990                    grantPermissionsUserIds = ArrayUtils.appendInt(
19991                            grantPermissionsUserIds, userId);
19992                }
19993            }
19994        }
19995        sUserManager.systemReady();
19996
19997        // If we upgraded grant all default permissions before kicking off.
19998        for (int userId : grantPermissionsUserIds) {
19999            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20000        }
20001
20002        // If we did not grant default permissions, we preload from this the
20003        // default permission exceptions lazily to ensure we don't hit the
20004        // disk on a new user creation.
20005        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20006            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20007        }
20008
20009        // Kick off any messages waiting for system ready
20010        if (mPostSystemReadyMessages != null) {
20011            for (Message msg : mPostSystemReadyMessages) {
20012                msg.sendToTarget();
20013            }
20014            mPostSystemReadyMessages = null;
20015        }
20016
20017        // Watch for external volumes that come and go over time
20018        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20019        storage.registerListener(mStorageListener);
20020
20021        mInstallerService.systemReady();
20022        mPackageDexOptimizer.systemReady();
20023
20024        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20025                StorageManagerInternal.class);
20026        StorageManagerInternal.addExternalStoragePolicy(
20027                new StorageManagerInternal.ExternalStorageMountPolicy() {
20028            @Override
20029            public int getMountMode(int uid, String packageName) {
20030                if (Process.isIsolated(uid)) {
20031                    return Zygote.MOUNT_EXTERNAL_NONE;
20032                }
20033                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20034                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20035                }
20036                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20037                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20038                }
20039                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20040                    return Zygote.MOUNT_EXTERNAL_READ;
20041                }
20042                return Zygote.MOUNT_EXTERNAL_WRITE;
20043            }
20044
20045            @Override
20046            public boolean hasExternalStorage(int uid, String packageName) {
20047                return true;
20048            }
20049        });
20050
20051        // Now that we're mostly running, clean up stale users and apps
20052        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20053        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20054
20055        if (mPrivappPermissionsViolations != null) {
20056            Slog.wtf(TAG,"Signature|privileged permissions not in "
20057                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20058            mPrivappPermissionsViolations = null;
20059        }
20060    }
20061
20062    @Override
20063    public boolean isSafeMode() {
20064        return mSafeMode;
20065    }
20066
20067    @Override
20068    public boolean hasSystemUidErrors() {
20069        return mHasSystemUidErrors;
20070    }
20071
20072    static String arrayToString(int[] array) {
20073        StringBuffer buf = new StringBuffer(128);
20074        buf.append('[');
20075        if (array != null) {
20076            for (int i=0; i<array.length; i++) {
20077                if (i > 0) buf.append(", ");
20078                buf.append(array[i]);
20079            }
20080        }
20081        buf.append(']');
20082        return buf.toString();
20083    }
20084
20085    static class DumpState {
20086        public static final int DUMP_LIBS = 1 << 0;
20087        public static final int DUMP_FEATURES = 1 << 1;
20088        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20089        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20090        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20091        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20092        public static final int DUMP_PERMISSIONS = 1 << 6;
20093        public static final int DUMP_PACKAGES = 1 << 7;
20094        public static final int DUMP_SHARED_USERS = 1 << 8;
20095        public static final int DUMP_MESSAGES = 1 << 9;
20096        public static final int DUMP_PROVIDERS = 1 << 10;
20097        public static final int DUMP_VERIFIERS = 1 << 11;
20098        public static final int DUMP_PREFERRED = 1 << 12;
20099        public static final int DUMP_PREFERRED_XML = 1 << 13;
20100        public static final int DUMP_KEYSETS = 1 << 14;
20101        public static final int DUMP_VERSION = 1 << 15;
20102        public static final int DUMP_INSTALLS = 1 << 16;
20103        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20104        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20105        public static final int DUMP_FROZEN = 1 << 19;
20106        public static final int DUMP_DEXOPT = 1 << 20;
20107        public static final int DUMP_COMPILER_STATS = 1 << 21;
20108
20109        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20110
20111        private int mTypes;
20112
20113        private int mOptions;
20114
20115        private boolean mTitlePrinted;
20116
20117        private SharedUserSetting mSharedUser;
20118
20119        public boolean isDumping(int type) {
20120            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20121                return true;
20122            }
20123
20124            return (mTypes & type) != 0;
20125        }
20126
20127        public void setDump(int type) {
20128            mTypes |= type;
20129        }
20130
20131        public boolean isOptionEnabled(int option) {
20132            return (mOptions & option) != 0;
20133        }
20134
20135        public void setOptionEnabled(int option) {
20136            mOptions |= option;
20137        }
20138
20139        public boolean onTitlePrinted() {
20140            final boolean printed = mTitlePrinted;
20141            mTitlePrinted = true;
20142            return printed;
20143        }
20144
20145        public boolean getTitlePrinted() {
20146            return mTitlePrinted;
20147        }
20148
20149        public void setTitlePrinted(boolean enabled) {
20150            mTitlePrinted = enabled;
20151        }
20152
20153        public SharedUserSetting getSharedUser() {
20154            return mSharedUser;
20155        }
20156
20157        public void setSharedUser(SharedUserSetting user) {
20158            mSharedUser = user;
20159        }
20160    }
20161
20162    @Override
20163    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20164            FileDescriptor err, String[] args, ShellCallback callback,
20165            ResultReceiver resultReceiver) {
20166        (new PackageManagerShellCommand(this)).exec(
20167                this, in, out, err, args, callback, resultReceiver);
20168    }
20169
20170    @Override
20171    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20172        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20173                != PackageManager.PERMISSION_GRANTED) {
20174            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20175                    + Binder.getCallingPid()
20176                    + ", uid=" + Binder.getCallingUid()
20177                    + " without permission "
20178                    + android.Manifest.permission.DUMP);
20179            return;
20180        }
20181
20182        DumpState dumpState = new DumpState();
20183        boolean fullPreferred = false;
20184        boolean checkin = false;
20185
20186        String packageName = null;
20187        ArraySet<String> permissionNames = null;
20188
20189        int opti = 0;
20190        while (opti < args.length) {
20191            String opt = args[opti];
20192            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20193                break;
20194            }
20195            opti++;
20196
20197            if ("-a".equals(opt)) {
20198                // Right now we only know how to print all.
20199            } else if ("-h".equals(opt)) {
20200                pw.println("Package manager dump options:");
20201                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20202                pw.println("    --checkin: dump for a checkin");
20203                pw.println("    -f: print details of intent filters");
20204                pw.println("    -h: print this help");
20205                pw.println("  cmd may be one of:");
20206                pw.println("    l[ibraries]: list known shared libraries");
20207                pw.println("    f[eatures]: list device features");
20208                pw.println("    k[eysets]: print known keysets");
20209                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20210                pw.println("    perm[issions]: dump permissions");
20211                pw.println("    permission [name ...]: dump declaration and use of given permission");
20212                pw.println("    pref[erred]: print preferred package settings");
20213                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20214                pw.println("    prov[iders]: dump content providers");
20215                pw.println("    p[ackages]: dump installed packages");
20216                pw.println("    s[hared-users]: dump shared user IDs");
20217                pw.println("    m[essages]: print collected runtime messages");
20218                pw.println("    v[erifiers]: print package verifier info");
20219                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20220                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20221                pw.println("    version: print database version info");
20222                pw.println("    write: write current settings now");
20223                pw.println("    installs: details about install sessions");
20224                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20225                pw.println("    dexopt: dump dexopt state");
20226                pw.println("    compiler-stats: dump compiler statistics");
20227                pw.println("    <package.name>: info about given package");
20228                return;
20229            } else if ("--checkin".equals(opt)) {
20230                checkin = true;
20231            } else if ("-f".equals(opt)) {
20232                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20233            } else {
20234                pw.println("Unknown argument: " + opt + "; use -h for help");
20235            }
20236        }
20237
20238        // Is the caller requesting to dump a particular piece of data?
20239        if (opti < args.length) {
20240            String cmd = args[opti];
20241            opti++;
20242            // Is this a package name?
20243            if ("android".equals(cmd) || cmd.contains(".")) {
20244                packageName = cmd;
20245                // When dumping a single package, we always dump all of its
20246                // filter information since the amount of data will be reasonable.
20247                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20248            } else if ("check-permission".equals(cmd)) {
20249                if (opti >= args.length) {
20250                    pw.println("Error: check-permission missing permission argument");
20251                    return;
20252                }
20253                String perm = args[opti];
20254                opti++;
20255                if (opti >= args.length) {
20256                    pw.println("Error: check-permission missing package argument");
20257                    return;
20258                }
20259
20260                String pkg = args[opti];
20261                opti++;
20262                int user = UserHandle.getUserId(Binder.getCallingUid());
20263                if (opti < args.length) {
20264                    try {
20265                        user = Integer.parseInt(args[opti]);
20266                    } catch (NumberFormatException e) {
20267                        pw.println("Error: check-permission user argument is not a number: "
20268                                + args[opti]);
20269                        return;
20270                    }
20271                }
20272
20273                // Normalize package name to handle renamed packages and static libs
20274                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20275
20276                pw.println(checkPermission(perm, pkg, user));
20277                return;
20278            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20279                dumpState.setDump(DumpState.DUMP_LIBS);
20280            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20281                dumpState.setDump(DumpState.DUMP_FEATURES);
20282            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20283                if (opti >= args.length) {
20284                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20285                            | DumpState.DUMP_SERVICE_RESOLVERS
20286                            | DumpState.DUMP_RECEIVER_RESOLVERS
20287                            | DumpState.DUMP_CONTENT_RESOLVERS);
20288                } else {
20289                    while (opti < args.length) {
20290                        String name = args[opti];
20291                        if ("a".equals(name) || "activity".equals(name)) {
20292                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20293                        } else if ("s".equals(name) || "service".equals(name)) {
20294                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20295                        } else if ("r".equals(name) || "receiver".equals(name)) {
20296                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20297                        } else if ("c".equals(name) || "content".equals(name)) {
20298                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20299                        } else {
20300                            pw.println("Error: unknown resolver table type: " + name);
20301                            return;
20302                        }
20303                        opti++;
20304                    }
20305                }
20306            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20307                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20308            } else if ("permission".equals(cmd)) {
20309                if (opti >= args.length) {
20310                    pw.println("Error: permission requires permission name");
20311                    return;
20312                }
20313                permissionNames = new ArraySet<>();
20314                while (opti < args.length) {
20315                    permissionNames.add(args[opti]);
20316                    opti++;
20317                }
20318                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20319                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20320            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20321                dumpState.setDump(DumpState.DUMP_PREFERRED);
20322            } else if ("preferred-xml".equals(cmd)) {
20323                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20324                if (opti < args.length && "--full".equals(args[opti])) {
20325                    fullPreferred = true;
20326                    opti++;
20327                }
20328            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20329                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20330            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20331                dumpState.setDump(DumpState.DUMP_PACKAGES);
20332            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20333                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20334            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20335                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20336            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20337                dumpState.setDump(DumpState.DUMP_MESSAGES);
20338            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20339                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20340            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20341                    || "intent-filter-verifiers".equals(cmd)) {
20342                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20343            } else if ("version".equals(cmd)) {
20344                dumpState.setDump(DumpState.DUMP_VERSION);
20345            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20346                dumpState.setDump(DumpState.DUMP_KEYSETS);
20347            } else if ("installs".equals(cmd)) {
20348                dumpState.setDump(DumpState.DUMP_INSTALLS);
20349            } else if ("frozen".equals(cmd)) {
20350                dumpState.setDump(DumpState.DUMP_FROZEN);
20351            } else if ("dexopt".equals(cmd)) {
20352                dumpState.setDump(DumpState.DUMP_DEXOPT);
20353            } else if ("compiler-stats".equals(cmd)) {
20354                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20355            } else if ("write".equals(cmd)) {
20356                synchronized (mPackages) {
20357                    mSettings.writeLPr();
20358                    pw.println("Settings written.");
20359                    return;
20360                }
20361            }
20362        }
20363
20364        if (checkin) {
20365            pw.println("vers,1");
20366        }
20367
20368        // reader
20369        synchronized (mPackages) {
20370            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20371                if (!checkin) {
20372                    if (dumpState.onTitlePrinted())
20373                        pw.println();
20374                    pw.println("Database versions:");
20375                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20376                }
20377            }
20378
20379            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20380                if (!checkin) {
20381                    if (dumpState.onTitlePrinted())
20382                        pw.println();
20383                    pw.println("Verifiers:");
20384                    pw.print("  Required: ");
20385                    pw.print(mRequiredVerifierPackage);
20386                    pw.print(" (uid=");
20387                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20388                            UserHandle.USER_SYSTEM));
20389                    pw.println(")");
20390                } else if (mRequiredVerifierPackage != null) {
20391                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20392                    pw.print(",");
20393                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20394                            UserHandle.USER_SYSTEM));
20395                }
20396            }
20397
20398            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20399                    packageName == null) {
20400                if (mIntentFilterVerifierComponent != null) {
20401                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20402                    if (!checkin) {
20403                        if (dumpState.onTitlePrinted())
20404                            pw.println();
20405                        pw.println("Intent Filter Verifier:");
20406                        pw.print("  Using: ");
20407                        pw.print(verifierPackageName);
20408                        pw.print(" (uid=");
20409                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20410                                UserHandle.USER_SYSTEM));
20411                        pw.println(")");
20412                    } else if (verifierPackageName != null) {
20413                        pw.print("ifv,"); pw.print(verifierPackageName);
20414                        pw.print(",");
20415                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20416                                UserHandle.USER_SYSTEM));
20417                    }
20418                } else {
20419                    pw.println();
20420                    pw.println("No Intent Filter Verifier available!");
20421                }
20422            }
20423
20424            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20425                boolean printedHeader = false;
20426                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20427                while (it.hasNext()) {
20428                    String libName = it.next();
20429                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20430                    if (versionedLib == null) {
20431                        continue;
20432                    }
20433                    final int versionCount = versionedLib.size();
20434                    for (int i = 0; i < versionCount; i++) {
20435                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20436                        if (!checkin) {
20437                            if (!printedHeader) {
20438                                if (dumpState.onTitlePrinted())
20439                                    pw.println();
20440                                pw.println("Libraries:");
20441                                printedHeader = true;
20442                            }
20443                            pw.print("  ");
20444                        } else {
20445                            pw.print("lib,");
20446                        }
20447                        pw.print(libEntry.info.getName());
20448                        if (libEntry.info.isStatic()) {
20449                            pw.print(" version=" + libEntry.info.getVersion());
20450                        }
20451                        if (!checkin) {
20452                            pw.print(" -> ");
20453                        }
20454                        if (libEntry.path != null) {
20455                            pw.print(" (jar) ");
20456                            pw.print(libEntry.path);
20457                        } else {
20458                            pw.print(" (apk) ");
20459                            pw.print(libEntry.apk);
20460                        }
20461                        pw.println();
20462                    }
20463                }
20464            }
20465
20466            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20467                if (dumpState.onTitlePrinted())
20468                    pw.println();
20469                if (!checkin) {
20470                    pw.println("Features:");
20471                }
20472
20473                synchronized (mAvailableFeatures) {
20474                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20475                        if (checkin) {
20476                            pw.print("feat,");
20477                            pw.print(feat.name);
20478                            pw.print(",");
20479                            pw.println(feat.version);
20480                        } else {
20481                            pw.print("  ");
20482                            pw.print(feat.name);
20483                            if (feat.version > 0) {
20484                                pw.print(" version=");
20485                                pw.print(feat.version);
20486                            }
20487                            pw.println();
20488                        }
20489                    }
20490                }
20491            }
20492
20493            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20494                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20495                        : "Activity Resolver Table:", "  ", packageName,
20496                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20497                    dumpState.setTitlePrinted(true);
20498                }
20499            }
20500            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20501                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20502                        : "Receiver Resolver Table:", "  ", packageName,
20503                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20504                    dumpState.setTitlePrinted(true);
20505                }
20506            }
20507            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20508                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20509                        : "Service Resolver Table:", "  ", packageName,
20510                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20511                    dumpState.setTitlePrinted(true);
20512                }
20513            }
20514            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20515                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20516                        : "Provider Resolver Table:", "  ", packageName,
20517                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20518                    dumpState.setTitlePrinted(true);
20519                }
20520            }
20521
20522            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20523                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20524                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20525                    int user = mSettings.mPreferredActivities.keyAt(i);
20526                    if (pir.dump(pw,
20527                            dumpState.getTitlePrinted()
20528                                ? "\nPreferred Activities User " + user + ":"
20529                                : "Preferred Activities User " + user + ":", "  ",
20530                            packageName, true, false)) {
20531                        dumpState.setTitlePrinted(true);
20532                    }
20533                }
20534            }
20535
20536            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20537                pw.flush();
20538                FileOutputStream fout = new FileOutputStream(fd);
20539                BufferedOutputStream str = new BufferedOutputStream(fout);
20540                XmlSerializer serializer = new FastXmlSerializer();
20541                try {
20542                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20543                    serializer.startDocument(null, true);
20544                    serializer.setFeature(
20545                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20546                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20547                    serializer.endDocument();
20548                    serializer.flush();
20549                } catch (IllegalArgumentException e) {
20550                    pw.println("Failed writing: " + e);
20551                } catch (IllegalStateException e) {
20552                    pw.println("Failed writing: " + e);
20553                } catch (IOException e) {
20554                    pw.println("Failed writing: " + e);
20555                }
20556            }
20557
20558            if (!checkin
20559                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20560                    && packageName == null) {
20561                pw.println();
20562                int count = mSettings.mPackages.size();
20563                if (count == 0) {
20564                    pw.println("No applications!");
20565                    pw.println();
20566                } else {
20567                    final String prefix = "  ";
20568                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20569                    if (allPackageSettings.size() == 0) {
20570                        pw.println("No domain preferred apps!");
20571                        pw.println();
20572                    } else {
20573                        pw.println("App verification status:");
20574                        pw.println();
20575                        count = 0;
20576                        for (PackageSetting ps : allPackageSettings) {
20577                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20578                            if (ivi == null || ivi.getPackageName() == null) continue;
20579                            pw.println(prefix + "Package: " + ivi.getPackageName());
20580                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20581                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20582                            pw.println();
20583                            count++;
20584                        }
20585                        if (count == 0) {
20586                            pw.println(prefix + "No app verification established.");
20587                            pw.println();
20588                        }
20589                        for (int userId : sUserManager.getUserIds()) {
20590                            pw.println("App linkages for user " + userId + ":");
20591                            pw.println();
20592                            count = 0;
20593                            for (PackageSetting ps : allPackageSettings) {
20594                                final long status = ps.getDomainVerificationStatusForUser(userId);
20595                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20596                                        && !DEBUG_DOMAIN_VERIFICATION) {
20597                                    continue;
20598                                }
20599                                pw.println(prefix + "Package: " + ps.name);
20600                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20601                                String statusStr = IntentFilterVerificationInfo.
20602                                        getStatusStringFromValue(status);
20603                                pw.println(prefix + "Status:  " + statusStr);
20604                                pw.println();
20605                                count++;
20606                            }
20607                            if (count == 0) {
20608                                pw.println(prefix + "No configured app linkages.");
20609                                pw.println();
20610                            }
20611                        }
20612                    }
20613                }
20614            }
20615
20616            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20617                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20618                if (packageName == null && permissionNames == null) {
20619                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20620                        if (iperm == 0) {
20621                            if (dumpState.onTitlePrinted())
20622                                pw.println();
20623                            pw.println("AppOp Permissions:");
20624                        }
20625                        pw.print("  AppOp Permission ");
20626                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20627                        pw.println(":");
20628                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20629                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20630                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20631                        }
20632                    }
20633                }
20634            }
20635
20636            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20637                boolean printedSomething = false;
20638                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20639                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20640                        continue;
20641                    }
20642                    if (!printedSomething) {
20643                        if (dumpState.onTitlePrinted())
20644                            pw.println();
20645                        pw.println("Registered ContentProviders:");
20646                        printedSomething = true;
20647                    }
20648                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20649                    pw.print("    "); pw.println(p.toString());
20650                }
20651                printedSomething = false;
20652                for (Map.Entry<String, PackageParser.Provider> entry :
20653                        mProvidersByAuthority.entrySet()) {
20654                    PackageParser.Provider p = entry.getValue();
20655                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20656                        continue;
20657                    }
20658                    if (!printedSomething) {
20659                        if (dumpState.onTitlePrinted())
20660                            pw.println();
20661                        pw.println("ContentProvider Authorities:");
20662                        printedSomething = true;
20663                    }
20664                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20665                    pw.print("    "); pw.println(p.toString());
20666                    if (p.info != null && p.info.applicationInfo != null) {
20667                        final String appInfo = p.info.applicationInfo.toString();
20668                        pw.print("      applicationInfo="); pw.println(appInfo);
20669                    }
20670                }
20671            }
20672
20673            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20674                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20675            }
20676
20677            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20678                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20679            }
20680
20681            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20682                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20683            }
20684
20685            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20686                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20687            }
20688
20689            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20690                // XXX should handle packageName != null by dumping only install data that
20691                // the given package is involved with.
20692                if (dumpState.onTitlePrinted()) pw.println();
20693                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20694            }
20695
20696            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20697                // XXX should handle packageName != null by dumping only install data that
20698                // the given package is involved with.
20699                if (dumpState.onTitlePrinted()) pw.println();
20700
20701                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20702                ipw.println();
20703                ipw.println("Frozen packages:");
20704                ipw.increaseIndent();
20705                if (mFrozenPackages.size() == 0) {
20706                    ipw.println("(none)");
20707                } else {
20708                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20709                        ipw.println(mFrozenPackages.valueAt(i));
20710                    }
20711                }
20712                ipw.decreaseIndent();
20713            }
20714
20715            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20716                if (dumpState.onTitlePrinted()) pw.println();
20717                dumpDexoptStateLPr(pw, packageName);
20718            }
20719
20720            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20721                if (dumpState.onTitlePrinted()) pw.println();
20722                dumpCompilerStatsLPr(pw, packageName);
20723            }
20724
20725            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20726                if (dumpState.onTitlePrinted()) pw.println();
20727                mSettings.dumpReadMessagesLPr(pw, dumpState);
20728
20729                pw.println();
20730                pw.println("Package warning messages:");
20731                BufferedReader in = null;
20732                String line = null;
20733                try {
20734                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20735                    while ((line = in.readLine()) != null) {
20736                        if (line.contains("ignored: updated version")) continue;
20737                        pw.println(line);
20738                    }
20739                } catch (IOException ignored) {
20740                } finally {
20741                    IoUtils.closeQuietly(in);
20742                }
20743            }
20744
20745            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20746                BufferedReader in = null;
20747                String line = null;
20748                try {
20749                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20750                    while ((line = in.readLine()) != null) {
20751                        if (line.contains("ignored: updated version")) continue;
20752                        pw.print("msg,");
20753                        pw.println(line);
20754                    }
20755                } catch (IOException ignored) {
20756                } finally {
20757                    IoUtils.closeQuietly(in);
20758                }
20759            }
20760        }
20761    }
20762
20763    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20764        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20765        ipw.println();
20766        ipw.println("Dexopt state:");
20767        ipw.increaseIndent();
20768        Collection<PackageParser.Package> packages = null;
20769        if (packageName != null) {
20770            PackageParser.Package targetPackage = mPackages.get(packageName);
20771            if (targetPackage != null) {
20772                packages = Collections.singletonList(targetPackage);
20773            } else {
20774                ipw.println("Unable to find package: " + packageName);
20775                return;
20776            }
20777        } else {
20778            packages = mPackages.values();
20779        }
20780
20781        for (PackageParser.Package pkg : packages) {
20782            ipw.println("[" + pkg.packageName + "]");
20783            ipw.increaseIndent();
20784            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20785            ipw.decreaseIndent();
20786        }
20787    }
20788
20789    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20790        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20791        ipw.println();
20792        ipw.println("Compiler stats:");
20793        ipw.increaseIndent();
20794        Collection<PackageParser.Package> packages = null;
20795        if (packageName != null) {
20796            PackageParser.Package targetPackage = mPackages.get(packageName);
20797            if (targetPackage != null) {
20798                packages = Collections.singletonList(targetPackage);
20799            } else {
20800                ipw.println("Unable to find package: " + packageName);
20801                return;
20802            }
20803        } else {
20804            packages = mPackages.values();
20805        }
20806
20807        for (PackageParser.Package pkg : packages) {
20808            ipw.println("[" + pkg.packageName + "]");
20809            ipw.increaseIndent();
20810
20811            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20812            if (stats == null) {
20813                ipw.println("(No recorded stats)");
20814            } else {
20815                stats.dump(ipw);
20816            }
20817            ipw.decreaseIndent();
20818        }
20819    }
20820
20821    private String dumpDomainString(String packageName) {
20822        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20823                .getList();
20824        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20825
20826        ArraySet<String> result = new ArraySet<>();
20827        if (iviList.size() > 0) {
20828            for (IntentFilterVerificationInfo ivi : iviList) {
20829                for (String host : ivi.getDomains()) {
20830                    result.add(host);
20831                }
20832            }
20833        }
20834        if (filters != null && filters.size() > 0) {
20835            for (IntentFilter filter : filters) {
20836                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20837                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20838                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20839                    result.addAll(filter.getHostsList());
20840                }
20841            }
20842        }
20843
20844        StringBuilder sb = new StringBuilder(result.size() * 16);
20845        for (String domain : result) {
20846            if (sb.length() > 0) sb.append(" ");
20847            sb.append(domain);
20848        }
20849        return sb.toString();
20850    }
20851
20852    // ------- apps on sdcard specific code -------
20853    static final boolean DEBUG_SD_INSTALL = false;
20854
20855    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20856
20857    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20858
20859    private boolean mMediaMounted = false;
20860
20861    static String getEncryptKey() {
20862        try {
20863            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20864                    SD_ENCRYPTION_KEYSTORE_NAME);
20865            if (sdEncKey == null) {
20866                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20867                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20868                if (sdEncKey == null) {
20869                    Slog.e(TAG, "Failed to create encryption keys");
20870                    return null;
20871                }
20872            }
20873            return sdEncKey;
20874        } catch (NoSuchAlgorithmException nsae) {
20875            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20876            return null;
20877        } catch (IOException ioe) {
20878            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20879            return null;
20880        }
20881    }
20882
20883    /*
20884     * Update media status on PackageManager.
20885     */
20886    @Override
20887    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20888        int callingUid = Binder.getCallingUid();
20889        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20890            throw new SecurityException("Media status can only be updated by the system");
20891        }
20892        // reader; this apparently protects mMediaMounted, but should probably
20893        // be a different lock in that case.
20894        synchronized (mPackages) {
20895            Log.i(TAG, "Updating external media status from "
20896                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20897                    + (mediaStatus ? "mounted" : "unmounted"));
20898            if (DEBUG_SD_INSTALL)
20899                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20900                        + ", mMediaMounted=" + mMediaMounted);
20901            if (mediaStatus == mMediaMounted) {
20902                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20903                        : 0, -1);
20904                mHandler.sendMessage(msg);
20905                return;
20906            }
20907            mMediaMounted = mediaStatus;
20908        }
20909        // Queue up an async operation since the package installation may take a
20910        // little while.
20911        mHandler.post(new Runnable() {
20912            public void run() {
20913                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20914            }
20915        });
20916    }
20917
20918    /**
20919     * Called by StorageManagerService when the initial ASECs to scan are available.
20920     * Should block until all the ASEC containers are finished being scanned.
20921     */
20922    public void scanAvailableAsecs() {
20923        updateExternalMediaStatusInner(true, false, false);
20924    }
20925
20926    /*
20927     * Collect information of applications on external media, map them against
20928     * existing containers and update information based on current mount status.
20929     * Please note that we always have to report status if reportStatus has been
20930     * set to true especially when unloading packages.
20931     */
20932    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20933            boolean externalStorage) {
20934        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20935        int[] uidArr = EmptyArray.INT;
20936
20937        final String[] list = PackageHelper.getSecureContainerList();
20938        if (ArrayUtils.isEmpty(list)) {
20939            Log.i(TAG, "No secure containers found");
20940        } else {
20941            // Process list of secure containers and categorize them
20942            // as active or stale based on their package internal state.
20943
20944            // reader
20945            synchronized (mPackages) {
20946                for (String cid : list) {
20947                    // Leave stages untouched for now; installer service owns them
20948                    if (PackageInstallerService.isStageName(cid)) continue;
20949
20950                    if (DEBUG_SD_INSTALL)
20951                        Log.i(TAG, "Processing container " + cid);
20952                    String pkgName = getAsecPackageName(cid);
20953                    if (pkgName == null) {
20954                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20955                        continue;
20956                    }
20957                    if (DEBUG_SD_INSTALL)
20958                        Log.i(TAG, "Looking for pkg : " + pkgName);
20959
20960                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20961                    if (ps == null) {
20962                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20963                        continue;
20964                    }
20965
20966                    /*
20967                     * Skip packages that are not external if we're unmounting
20968                     * external storage.
20969                     */
20970                    if (externalStorage && !isMounted && !isExternal(ps)) {
20971                        continue;
20972                    }
20973
20974                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20975                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20976                    // The package status is changed only if the code path
20977                    // matches between settings and the container id.
20978                    if (ps.codePathString != null
20979                            && ps.codePathString.startsWith(args.getCodePath())) {
20980                        if (DEBUG_SD_INSTALL) {
20981                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20982                                    + " at code path: " + ps.codePathString);
20983                        }
20984
20985                        // We do have a valid package installed on sdcard
20986                        processCids.put(args, ps.codePathString);
20987                        final int uid = ps.appId;
20988                        if (uid != -1) {
20989                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20990                        }
20991                    } else {
20992                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20993                                + ps.codePathString);
20994                    }
20995                }
20996            }
20997
20998            Arrays.sort(uidArr);
20999        }
21000
21001        // Process packages with valid entries.
21002        if (isMounted) {
21003            if (DEBUG_SD_INSTALL)
21004                Log.i(TAG, "Loading packages");
21005            loadMediaPackages(processCids, uidArr, externalStorage);
21006            startCleaningPackages();
21007            mInstallerService.onSecureContainersAvailable();
21008        } else {
21009            if (DEBUG_SD_INSTALL)
21010                Log.i(TAG, "Unloading packages");
21011            unloadMediaPackages(processCids, uidArr, reportStatus);
21012        }
21013    }
21014
21015    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21016            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21017        final int size = infos.size();
21018        final String[] packageNames = new String[size];
21019        final int[] packageUids = new int[size];
21020        for (int i = 0; i < size; i++) {
21021            final ApplicationInfo info = infos.get(i);
21022            packageNames[i] = info.packageName;
21023            packageUids[i] = info.uid;
21024        }
21025        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21026                finishedReceiver);
21027    }
21028
21029    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21030            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21031        sendResourcesChangedBroadcast(mediaStatus, replacing,
21032                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21033    }
21034
21035    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21036            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21037        int size = pkgList.length;
21038        if (size > 0) {
21039            // Send broadcasts here
21040            Bundle extras = new Bundle();
21041            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21042            if (uidArr != null) {
21043                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21044            }
21045            if (replacing) {
21046                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21047            }
21048            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21049                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21050            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21051        }
21052    }
21053
21054   /*
21055     * Look at potentially valid container ids from processCids If package
21056     * information doesn't match the one on record or package scanning fails,
21057     * the cid is added to list of removeCids. We currently don't delete stale
21058     * containers.
21059     */
21060    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21061            boolean externalStorage) {
21062        ArrayList<String> pkgList = new ArrayList<String>();
21063        Set<AsecInstallArgs> keys = processCids.keySet();
21064
21065        for (AsecInstallArgs args : keys) {
21066            String codePath = processCids.get(args);
21067            if (DEBUG_SD_INSTALL)
21068                Log.i(TAG, "Loading container : " + args.cid);
21069            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21070            try {
21071                // Make sure there are no container errors first.
21072                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21073                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21074                            + " when installing from sdcard");
21075                    continue;
21076                }
21077                // Check code path here.
21078                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21079                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21080                            + " does not match one in settings " + codePath);
21081                    continue;
21082                }
21083                // Parse package
21084                int parseFlags = mDefParseFlags;
21085                if (args.isExternalAsec()) {
21086                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21087                }
21088                if (args.isFwdLocked()) {
21089                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21090                }
21091
21092                synchronized (mInstallLock) {
21093                    PackageParser.Package pkg = null;
21094                    try {
21095                        // Sadly we don't know the package name yet to freeze it
21096                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21097                                SCAN_IGNORE_FROZEN, 0, null);
21098                    } catch (PackageManagerException e) {
21099                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21100                    }
21101                    // Scan the package
21102                    if (pkg != null) {
21103                        /*
21104                         * TODO why is the lock being held? doPostInstall is
21105                         * called in other places without the lock. This needs
21106                         * to be straightened out.
21107                         */
21108                        // writer
21109                        synchronized (mPackages) {
21110                            retCode = PackageManager.INSTALL_SUCCEEDED;
21111                            pkgList.add(pkg.packageName);
21112                            // Post process args
21113                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21114                                    pkg.applicationInfo.uid);
21115                        }
21116                    } else {
21117                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21118                    }
21119                }
21120
21121            } finally {
21122                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21123                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21124                }
21125            }
21126        }
21127        // writer
21128        synchronized (mPackages) {
21129            // If the platform SDK has changed since the last time we booted,
21130            // we need to re-grant app permission to catch any new ones that
21131            // appear. This is really a hack, and means that apps can in some
21132            // cases get permissions that the user didn't initially explicitly
21133            // allow... it would be nice to have some better way to handle
21134            // this situation.
21135            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21136                    : mSettings.getInternalVersion();
21137            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21138                    : StorageManager.UUID_PRIVATE_INTERNAL;
21139
21140            int updateFlags = UPDATE_PERMISSIONS_ALL;
21141            if (ver.sdkVersion != mSdkVersion) {
21142                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21143                        + mSdkVersion + "; regranting permissions for external");
21144                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21145            }
21146            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21147
21148            // Yay, everything is now upgraded
21149            ver.forceCurrent();
21150
21151            // can downgrade to reader
21152            // Persist settings
21153            mSettings.writeLPr();
21154        }
21155        // Send a broadcast to let everyone know we are done processing
21156        if (pkgList.size() > 0) {
21157            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21158        }
21159    }
21160
21161   /*
21162     * Utility method to unload a list of specified containers
21163     */
21164    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21165        // Just unmount all valid containers.
21166        for (AsecInstallArgs arg : cidArgs) {
21167            synchronized (mInstallLock) {
21168                arg.doPostDeleteLI(false);
21169           }
21170       }
21171   }
21172
21173    /*
21174     * Unload packages mounted on external media. This involves deleting package
21175     * data from internal structures, sending broadcasts about disabled packages,
21176     * gc'ing to free up references, unmounting all secure containers
21177     * corresponding to packages on external media, and posting a
21178     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21179     * that we always have to post this message if status has been requested no
21180     * matter what.
21181     */
21182    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21183            final boolean reportStatus) {
21184        if (DEBUG_SD_INSTALL)
21185            Log.i(TAG, "unloading media packages");
21186        ArrayList<String> pkgList = new ArrayList<String>();
21187        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21188        final Set<AsecInstallArgs> keys = processCids.keySet();
21189        for (AsecInstallArgs args : keys) {
21190            String pkgName = args.getPackageName();
21191            if (DEBUG_SD_INSTALL)
21192                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21193            // Delete package internally
21194            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21195            synchronized (mInstallLock) {
21196                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21197                final boolean res;
21198                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21199                        "unloadMediaPackages")) {
21200                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21201                            null);
21202                }
21203                if (res) {
21204                    pkgList.add(pkgName);
21205                } else {
21206                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21207                    failedList.add(args);
21208                }
21209            }
21210        }
21211
21212        // reader
21213        synchronized (mPackages) {
21214            // We didn't update the settings after removing each package;
21215            // write them now for all packages.
21216            mSettings.writeLPr();
21217        }
21218
21219        // We have to absolutely send UPDATED_MEDIA_STATUS only
21220        // after confirming that all the receivers processed the ordered
21221        // broadcast when packages get disabled, force a gc to clean things up.
21222        // and unload all the containers.
21223        if (pkgList.size() > 0) {
21224            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21225                    new IIntentReceiver.Stub() {
21226                public void performReceive(Intent intent, int resultCode, String data,
21227                        Bundle extras, boolean ordered, boolean sticky,
21228                        int sendingUser) throws RemoteException {
21229                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21230                            reportStatus ? 1 : 0, 1, keys);
21231                    mHandler.sendMessage(msg);
21232                }
21233            });
21234        } else {
21235            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21236                    keys);
21237            mHandler.sendMessage(msg);
21238        }
21239    }
21240
21241    private void loadPrivatePackages(final VolumeInfo vol) {
21242        mHandler.post(new Runnable() {
21243            @Override
21244            public void run() {
21245                loadPrivatePackagesInner(vol);
21246            }
21247        });
21248    }
21249
21250    private void loadPrivatePackagesInner(VolumeInfo vol) {
21251        final String volumeUuid = vol.fsUuid;
21252        if (TextUtils.isEmpty(volumeUuid)) {
21253            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21254            return;
21255        }
21256
21257        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21258        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21259        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21260
21261        final VersionInfo ver;
21262        final List<PackageSetting> packages;
21263        synchronized (mPackages) {
21264            ver = mSettings.findOrCreateVersion(volumeUuid);
21265            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21266        }
21267
21268        for (PackageSetting ps : packages) {
21269            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21270            synchronized (mInstallLock) {
21271                final PackageParser.Package pkg;
21272                try {
21273                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21274                    loaded.add(pkg.applicationInfo);
21275
21276                } catch (PackageManagerException e) {
21277                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21278                }
21279
21280                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21281                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21282                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21283                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21284                }
21285            }
21286        }
21287
21288        // Reconcile app data for all started/unlocked users
21289        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21290        final UserManager um = mContext.getSystemService(UserManager.class);
21291        UserManagerInternal umInternal = getUserManagerInternal();
21292        for (UserInfo user : um.getUsers()) {
21293            final int flags;
21294            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21295                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21296            } else if (umInternal.isUserRunning(user.id)) {
21297                flags = StorageManager.FLAG_STORAGE_DE;
21298            } else {
21299                continue;
21300            }
21301
21302            try {
21303                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21304                synchronized (mInstallLock) {
21305                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21306                }
21307            } catch (IllegalStateException e) {
21308                // Device was probably ejected, and we'll process that event momentarily
21309                Slog.w(TAG, "Failed to prepare storage: " + e);
21310            }
21311        }
21312
21313        synchronized (mPackages) {
21314            int updateFlags = UPDATE_PERMISSIONS_ALL;
21315            if (ver.sdkVersion != mSdkVersion) {
21316                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21317                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21318                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21319            }
21320            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21321
21322            // Yay, everything is now upgraded
21323            ver.forceCurrent();
21324
21325            mSettings.writeLPr();
21326        }
21327
21328        for (PackageFreezer freezer : freezers) {
21329            freezer.close();
21330        }
21331
21332        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21333        sendResourcesChangedBroadcast(true, false, loaded, null);
21334    }
21335
21336    private void unloadPrivatePackages(final VolumeInfo vol) {
21337        mHandler.post(new Runnable() {
21338            @Override
21339            public void run() {
21340                unloadPrivatePackagesInner(vol);
21341            }
21342        });
21343    }
21344
21345    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21346        final String volumeUuid = vol.fsUuid;
21347        if (TextUtils.isEmpty(volumeUuid)) {
21348            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21349            return;
21350        }
21351
21352        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21353        synchronized (mInstallLock) {
21354        synchronized (mPackages) {
21355            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21356            for (PackageSetting ps : packages) {
21357                if (ps.pkg == null) continue;
21358
21359                final ApplicationInfo info = ps.pkg.applicationInfo;
21360                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21361                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21362
21363                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21364                        "unloadPrivatePackagesInner")) {
21365                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21366                            false, null)) {
21367                        unloaded.add(info);
21368                    } else {
21369                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21370                    }
21371                }
21372
21373                // Try very hard to release any references to this package
21374                // so we don't risk the system server being killed due to
21375                // open FDs
21376                AttributeCache.instance().removePackage(ps.name);
21377            }
21378
21379            mSettings.writeLPr();
21380        }
21381        }
21382
21383        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21384        sendResourcesChangedBroadcast(false, false, unloaded, null);
21385
21386        // Try very hard to release any references to this path so we don't risk
21387        // the system server being killed due to open FDs
21388        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21389
21390        for (int i = 0; i < 3; i++) {
21391            System.gc();
21392            System.runFinalization();
21393        }
21394    }
21395
21396    private void assertPackageKnown(String volumeUuid, String packageName)
21397            throws PackageManagerException {
21398        synchronized (mPackages) {
21399            // Normalize package name to handle renamed packages
21400            packageName = normalizePackageNameLPr(packageName);
21401
21402            final PackageSetting ps = mSettings.mPackages.get(packageName);
21403            if (ps == null) {
21404                throw new PackageManagerException("Package " + packageName + " is unknown");
21405            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21406                throw new PackageManagerException(
21407                        "Package " + packageName + " found on unknown volume " + volumeUuid
21408                                + "; expected volume " + ps.volumeUuid);
21409            }
21410        }
21411    }
21412
21413    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21414            throws PackageManagerException {
21415        synchronized (mPackages) {
21416            // Normalize package name to handle renamed packages
21417            packageName = normalizePackageNameLPr(packageName);
21418
21419            final PackageSetting ps = mSettings.mPackages.get(packageName);
21420            if (ps == null) {
21421                throw new PackageManagerException("Package " + packageName + " is unknown");
21422            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21423                throw new PackageManagerException(
21424                        "Package " + packageName + " found on unknown volume " + volumeUuid
21425                                + "; expected volume " + ps.volumeUuid);
21426            } else if (!ps.getInstalled(userId)) {
21427                throw new PackageManagerException(
21428                        "Package " + packageName + " not installed for user " + userId);
21429            }
21430        }
21431    }
21432
21433    private List<String> collectAbsoluteCodePaths() {
21434        synchronized (mPackages) {
21435            List<String> codePaths = new ArrayList<>();
21436            final int packageCount = mSettings.mPackages.size();
21437            for (int i = 0; i < packageCount; i++) {
21438                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21439                codePaths.add(ps.codePath.getAbsolutePath());
21440            }
21441            return codePaths;
21442        }
21443    }
21444
21445    /**
21446     * Examine all apps present on given mounted volume, and destroy apps that
21447     * aren't expected, either due to uninstallation or reinstallation on
21448     * another volume.
21449     */
21450    private void reconcileApps(String volumeUuid) {
21451        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21452        List<File> filesToDelete = null;
21453
21454        final File[] files = FileUtils.listFilesOrEmpty(
21455                Environment.getDataAppDirectory(volumeUuid));
21456        for (File file : files) {
21457            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21458                    && !PackageInstallerService.isStageName(file.getName());
21459            if (!isPackage) {
21460                // Ignore entries which are not packages
21461                continue;
21462            }
21463
21464            String absolutePath = file.getAbsolutePath();
21465
21466            boolean pathValid = false;
21467            final int absoluteCodePathCount = absoluteCodePaths.size();
21468            for (int i = 0; i < absoluteCodePathCount; i++) {
21469                String absoluteCodePath = absoluteCodePaths.get(i);
21470                if (absolutePath.startsWith(absoluteCodePath)) {
21471                    pathValid = true;
21472                    break;
21473                }
21474            }
21475
21476            if (!pathValid) {
21477                if (filesToDelete == null) {
21478                    filesToDelete = new ArrayList<>();
21479                }
21480                filesToDelete.add(file);
21481            }
21482        }
21483
21484        if (filesToDelete != null) {
21485            final int fileToDeleteCount = filesToDelete.size();
21486            for (int i = 0; i < fileToDeleteCount; i++) {
21487                File fileToDelete = filesToDelete.get(i);
21488                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21489                synchronized (mInstallLock) {
21490                    removeCodePathLI(fileToDelete);
21491                }
21492            }
21493        }
21494    }
21495
21496    /**
21497     * Reconcile all app data for the given user.
21498     * <p>
21499     * Verifies that directories exist and that ownership and labeling is
21500     * correct for all installed apps on all mounted volumes.
21501     */
21502    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21503        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21504        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21505            final String volumeUuid = vol.getFsUuid();
21506            synchronized (mInstallLock) {
21507                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21508            }
21509        }
21510    }
21511
21512    /**
21513     * Reconcile all app data on given mounted volume.
21514     * <p>
21515     * Destroys app data that isn't expected, either due to uninstallation or
21516     * reinstallation on another volume.
21517     * <p>
21518     * Verifies that directories exist and that ownership and labeling is
21519     * correct for all installed apps.
21520     */
21521    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21522            boolean migrateAppData) {
21523        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21524                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21525
21526        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21527        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21528
21529        // First look for stale data that doesn't belong, and check if things
21530        // have changed since we did our last restorecon
21531        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21532            if (StorageManager.isFileEncryptedNativeOrEmulated()
21533                    && !StorageManager.isUserKeyUnlocked(userId)) {
21534                throw new RuntimeException(
21535                        "Yikes, someone asked us to reconcile CE storage while " + userId
21536                                + " was still locked; this would have caused massive data loss!");
21537            }
21538
21539            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21540            for (File file : files) {
21541                final String packageName = file.getName();
21542                try {
21543                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21544                } catch (PackageManagerException e) {
21545                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21546                    try {
21547                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21548                                StorageManager.FLAG_STORAGE_CE, 0);
21549                    } catch (InstallerException e2) {
21550                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21551                    }
21552                }
21553            }
21554        }
21555        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21556            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21557            for (File file : files) {
21558                final String packageName = file.getName();
21559                try {
21560                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21561                } catch (PackageManagerException e) {
21562                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21563                    try {
21564                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21565                                StorageManager.FLAG_STORAGE_DE, 0);
21566                    } catch (InstallerException e2) {
21567                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21568                    }
21569                }
21570            }
21571        }
21572
21573        // Ensure that data directories are ready to roll for all packages
21574        // installed for this volume and user
21575        final List<PackageSetting> packages;
21576        synchronized (mPackages) {
21577            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21578        }
21579        int preparedCount = 0;
21580        for (PackageSetting ps : packages) {
21581            final String packageName = ps.name;
21582            if (ps.pkg == null) {
21583                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21584                // TODO: might be due to legacy ASEC apps; we should circle back
21585                // and reconcile again once they're scanned
21586                continue;
21587            }
21588
21589            if (ps.getInstalled(userId)) {
21590                prepareAppDataLIF(ps.pkg, userId, flags);
21591
21592                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21593                    // We may have just shuffled around app data directories, so
21594                    // prepare them one more time
21595                    prepareAppDataLIF(ps.pkg, userId, flags);
21596                }
21597
21598                preparedCount++;
21599            }
21600        }
21601
21602        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21603    }
21604
21605    /**
21606     * Prepare app data for the given app just after it was installed or
21607     * upgraded. This method carefully only touches users that it's installed
21608     * for, and it forces a restorecon to handle any seinfo changes.
21609     * <p>
21610     * Verifies that directories exist and that ownership and labeling is
21611     * correct for all installed apps. If there is an ownership mismatch, it
21612     * will try recovering system apps by wiping data; third-party app data is
21613     * left intact.
21614     * <p>
21615     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21616     */
21617    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21618        final PackageSetting ps;
21619        synchronized (mPackages) {
21620            ps = mSettings.mPackages.get(pkg.packageName);
21621            mSettings.writeKernelMappingLPr(ps);
21622        }
21623
21624        final UserManager um = mContext.getSystemService(UserManager.class);
21625        UserManagerInternal umInternal = getUserManagerInternal();
21626        for (UserInfo user : um.getUsers()) {
21627            final int flags;
21628            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21629                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21630            } else if (umInternal.isUserRunning(user.id)) {
21631                flags = StorageManager.FLAG_STORAGE_DE;
21632            } else {
21633                continue;
21634            }
21635
21636            if (ps.getInstalled(user.id)) {
21637                // TODO: when user data is locked, mark that we're still dirty
21638                prepareAppDataLIF(pkg, user.id, flags);
21639            }
21640        }
21641    }
21642
21643    /**
21644     * Prepare app data for the given app.
21645     * <p>
21646     * Verifies that directories exist and that ownership and labeling is
21647     * correct for all installed apps. If there is an ownership mismatch, this
21648     * will try recovering system apps by wiping data; third-party app data is
21649     * left intact.
21650     */
21651    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21652        if (pkg == null) {
21653            Slog.wtf(TAG, "Package was null!", new Throwable());
21654            return;
21655        }
21656        prepareAppDataLeafLIF(pkg, userId, flags);
21657        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21658        for (int i = 0; i < childCount; i++) {
21659            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21660        }
21661    }
21662
21663    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21664        if (DEBUG_APP_DATA) {
21665            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21666                    + Integer.toHexString(flags));
21667        }
21668
21669        final String volumeUuid = pkg.volumeUuid;
21670        final String packageName = pkg.packageName;
21671        final ApplicationInfo app = pkg.applicationInfo;
21672        final int appId = UserHandle.getAppId(app.uid);
21673
21674        Preconditions.checkNotNull(app.seinfo);
21675
21676        long ceDataInode = -1;
21677        try {
21678            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21679                    appId, app.seinfo, app.targetSdkVersion);
21680        } catch (InstallerException e) {
21681            if (app.isSystemApp()) {
21682                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21683                        + ", but trying to recover: " + e);
21684                destroyAppDataLeafLIF(pkg, userId, flags);
21685                try {
21686                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21687                            appId, app.seinfo, app.targetSdkVersion);
21688                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21689                } catch (InstallerException e2) {
21690                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21691                }
21692            } else {
21693                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21694            }
21695        }
21696
21697        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21698            // TODO: mark this structure as dirty so we persist it!
21699            synchronized (mPackages) {
21700                final PackageSetting ps = mSettings.mPackages.get(packageName);
21701                if (ps != null) {
21702                    ps.setCeDataInode(ceDataInode, userId);
21703                }
21704            }
21705        }
21706
21707        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21708    }
21709
21710    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21711        if (pkg == null) {
21712            Slog.wtf(TAG, "Package was null!", new Throwable());
21713            return;
21714        }
21715        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21716        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21717        for (int i = 0; i < childCount; i++) {
21718            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21719        }
21720    }
21721
21722    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21723        final String volumeUuid = pkg.volumeUuid;
21724        final String packageName = pkg.packageName;
21725        final ApplicationInfo app = pkg.applicationInfo;
21726
21727        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21728            // Create a native library symlink only if we have native libraries
21729            // and if the native libraries are 32 bit libraries. We do not provide
21730            // this symlink for 64 bit libraries.
21731            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21732                final String nativeLibPath = app.nativeLibraryDir;
21733                try {
21734                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21735                            nativeLibPath, userId);
21736                } catch (InstallerException e) {
21737                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21738                }
21739            }
21740        }
21741    }
21742
21743    /**
21744     * For system apps on non-FBE devices, this method migrates any existing
21745     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21746     * requested by the app.
21747     */
21748    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21749        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21750                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21751            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21752                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21753            try {
21754                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21755                        storageTarget);
21756            } catch (InstallerException e) {
21757                logCriticalInfo(Log.WARN,
21758                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21759            }
21760            return true;
21761        } else {
21762            return false;
21763        }
21764    }
21765
21766    public PackageFreezer freezePackage(String packageName, String killReason) {
21767        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21768    }
21769
21770    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21771        return new PackageFreezer(packageName, userId, killReason);
21772    }
21773
21774    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21775            String killReason) {
21776        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21777    }
21778
21779    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21780            String killReason) {
21781        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21782            return new PackageFreezer();
21783        } else {
21784            return freezePackage(packageName, userId, killReason);
21785        }
21786    }
21787
21788    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21789            String killReason) {
21790        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21791    }
21792
21793    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21794            String killReason) {
21795        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21796            return new PackageFreezer();
21797        } else {
21798            return freezePackage(packageName, userId, killReason);
21799        }
21800    }
21801
21802    /**
21803     * Class that freezes and kills the given package upon creation, and
21804     * unfreezes it upon closing. This is typically used when doing surgery on
21805     * app code/data to prevent the app from running while you're working.
21806     */
21807    private class PackageFreezer implements AutoCloseable {
21808        private final String mPackageName;
21809        private final PackageFreezer[] mChildren;
21810
21811        private final boolean mWeFroze;
21812
21813        private final AtomicBoolean mClosed = new AtomicBoolean();
21814        private final CloseGuard mCloseGuard = CloseGuard.get();
21815
21816        /**
21817         * Create and return a stub freezer that doesn't actually do anything,
21818         * typically used when someone requested
21819         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21820         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21821         */
21822        public PackageFreezer() {
21823            mPackageName = null;
21824            mChildren = null;
21825            mWeFroze = false;
21826            mCloseGuard.open("close");
21827        }
21828
21829        public PackageFreezer(String packageName, int userId, String killReason) {
21830            synchronized (mPackages) {
21831                mPackageName = packageName;
21832                mWeFroze = mFrozenPackages.add(mPackageName);
21833
21834                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21835                if (ps != null) {
21836                    killApplication(ps.name, ps.appId, userId, killReason);
21837                }
21838
21839                final PackageParser.Package p = mPackages.get(packageName);
21840                if (p != null && p.childPackages != null) {
21841                    final int N = p.childPackages.size();
21842                    mChildren = new PackageFreezer[N];
21843                    for (int i = 0; i < N; i++) {
21844                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21845                                userId, killReason);
21846                    }
21847                } else {
21848                    mChildren = null;
21849                }
21850            }
21851            mCloseGuard.open("close");
21852        }
21853
21854        @Override
21855        protected void finalize() throws Throwable {
21856            try {
21857                mCloseGuard.warnIfOpen();
21858                close();
21859            } finally {
21860                super.finalize();
21861            }
21862        }
21863
21864        @Override
21865        public void close() {
21866            mCloseGuard.close();
21867            if (mClosed.compareAndSet(false, true)) {
21868                synchronized (mPackages) {
21869                    if (mWeFroze) {
21870                        mFrozenPackages.remove(mPackageName);
21871                    }
21872
21873                    if (mChildren != null) {
21874                        for (PackageFreezer freezer : mChildren) {
21875                            freezer.close();
21876                        }
21877                    }
21878                }
21879            }
21880        }
21881    }
21882
21883    /**
21884     * Verify that given package is currently frozen.
21885     */
21886    private void checkPackageFrozen(String packageName) {
21887        synchronized (mPackages) {
21888            if (!mFrozenPackages.contains(packageName)) {
21889                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21890            }
21891        }
21892    }
21893
21894    @Override
21895    public int movePackage(final String packageName, final String volumeUuid) {
21896        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21897
21898        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21899        final int moveId = mNextMoveId.getAndIncrement();
21900        mHandler.post(new Runnable() {
21901            @Override
21902            public void run() {
21903                try {
21904                    movePackageInternal(packageName, volumeUuid, moveId, user);
21905                } catch (PackageManagerException e) {
21906                    Slog.w(TAG, "Failed to move " + packageName, e);
21907                    mMoveCallbacks.notifyStatusChanged(moveId,
21908                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21909                }
21910            }
21911        });
21912        return moveId;
21913    }
21914
21915    private void movePackageInternal(final String packageName, final String volumeUuid,
21916            final int moveId, UserHandle user) throws PackageManagerException {
21917        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21918        final PackageManager pm = mContext.getPackageManager();
21919
21920        final boolean currentAsec;
21921        final String currentVolumeUuid;
21922        final File codeFile;
21923        final String installerPackageName;
21924        final String packageAbiOverride;
21925        final int appId;
21926        final String seinfo;
21927        final String label;
21928        final int targetSdkVersion;
21929        final PackageFreezer freezer;
21930        final int[] installedUserIds;
21931
21932        // reader
21933        synchronized (mPackages) {
21934            final PackageParser.Package pkg = mPackages.get(packageName);
21935            final PackageSetting ps = mSettings.mPackages.get(packageName);
21936            if (pkg == null || ps == null) {
21937                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21938            }
21939
21940            if (pkg.applicationInfo.isSystemApp()) {
21941                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21942                        "Cannot move system application");
21943            }
21944
21945            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21946            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21947                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21948            if (isInternalStorage && !allow3rdPartyOnInternal) {
21949                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21950                        "3rd party apps are not allowed on internal storage");
21951            }
21952
21953            if (pkg.applicationInfo.isExternalAsec()) {
21954                currentAsec = true;
21955                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21956            } else if (pkg.applicationInfo.isForwardLocked()) {
21957                currentAsec = true;
21958                currentVolumeUuid = "forward_locked";
21959            } else {
21960                currentAsec = false;
21961                currentVolumeUuid = ps.volumeUuid;
21962
21963                final File probe = new File(pkg.codePath);
21964                final File probeOat = new File(probe, "oat");
21965                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21966                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21967                            "Move only supported for modern cluster style installs");
21968                }
21969            }
21970
21971            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21972                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21973                        "Package already moved to " + volumeUuid);
21974            }
21975            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21976                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21977                        "Device admin cannot be moved");
21978            }
21979
21980            if (mFrozenPackages.contains(packageName)) {
21981                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21982                        "Failed to move already frozen package");
21983            }
21984
21985            codeFile = new File(pkg.codePath);
21986            installerPackageName = ps.installerPackageName;
21987            packageAbiOverride = ps.cpuAbiOverrideString;
21988            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21989            seinfo = pkg.applicationInfo.seinfo;
21990            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21991            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21992            freezer = freezePackage(packageName, "movePackageInternal");
21993            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21994        }
21995
21996        final Bundle extras = new Bundle();
21997        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21998        extras.putString(Intent.EXTRA_TITLE, label);
21999        mMoveCallbacks.notifyCreated(moveId, extras);
22000
22001        int installFlags;
22002        final boolean moveCompleteApp;
22003        final File measurePath;
22004
22005        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22006            installFlags = INSTALL_INTERNAL;
22007            moveCompleteApp = !currentAsec;
22008            measurePath = Environment.getDataAppDirectory(volumeUuid);
22009        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22010            installFlags = INSTALL_EXTERNAL;
22011            moveCompleteApp = false;
22012            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22013        } else {
22014            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22015            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22016                    || !volume.isMountedWritable()) {
22017                freezer.close();
22018                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22019                        "Move location not mounted private volume");
22020            }
22021
22022            Preconditions.checkState(!currentAsec);
22023
22024            installFlags = INSTALL_INTERNAL;
22025            moveCompleteApp = true;
22026            measurePath = Environment.getDataAppDirectory(volumeUuid);
22027        }
22028
22029        final PackageStats stats = new PackageStats(null, -1);
22030        synchronized (mInstaller) {
22031            for (int userId : installedUserIds) {
22032                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22033                    freezer.close();
22034                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22035                            "Failed to measure package size");
22036                }
22037            }
22038        }
22039
22040        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22041                + stats.dataSize);
22042
22043        final long startFreeBytes = measurePath.getFreeSpace();
22044        final long sizeBytes;
22045        if (moveCompleteApp) {
22046            sizeBytes = stats.codeSize + stats.dataSize;
22047        } else {
22048            sizeBytes = stats.codeSize;
22049        }
22050
22051        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22052            freezer.close();
22053            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22054                    "Not enough free space to move");
22055        }
22056
22057        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22058
22059        final CountDownLatch installedLatch = new CountDownLatch(1);
22060        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22061            @Override
22062            public void onUserActionRequired(Intent intent) throws RemoteException {
22063                throw new IllegalStateException();
22064            }
22065
22066            @Override
22067            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22068                    Bundle extras) throws RemoteException {
22069                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22070                        + PackageManager.installStatusToString(returnCode, msg));
22071
22072                installedLatch.countDown();
22073                freezer.close();
22074
22075                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22076                switch (status) {
22077                    case PackageInstaller.STATUS_SUCCESS:
22078                        mMoveCallbacks.notifyStatusChanged(moveId,
22079                                PackageManager.MOVE_SUCCEEDED);
22080                        break;
22081                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22082                        mMoveCallbacks.notifyStatusChanged(moveId,
22083                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22084                        break;
22085                    default:
22086                        mMoveCallbacks.notifyStatusChanged(moveId,
22087                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22088                        break;
22089                }
22090            }
22091        };
22092
22093        final MoveInfo move;
22094        if (moveCompleteApp) {
22095            // Kick off a thread to report progress estimates
22096            new Thread() {
22097                @Override
22098                public void run() {
22099                    while (true) {
22100                        try {
22101                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22102                                break;
22103                            }
22104                        } catch (InterruptedException ignored) {
22105                        }
22106
22107                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22108                        final int progress = 10 + (int) MathUtils.constrain(
22109                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22110                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22111                    }
22112                }
22113            }.start();
22114
22115            final String dataAppName = codeFile.getName();
22116            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22117                    dataAppName, appId, seinfo, targetSdkVersion);
22118        } else {
22119            move = null;
22120        }
22121
22122        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22123
22124        final Message msg = mHandler.obtainMessage(INIT_COPY);
22125        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22126        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22127                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22128                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22129                PackageManager.INSTALL_REASON_UNKNOWN);
22130        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22131        msg.obj = params;
22132
22133        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22134                System.identityHashCode(msg.obj));
22135        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22136                System.identityHashCode(msg.obj));
22137
22138        mHandler.sendMessage(msg);
22139    }
22140
22141    @Override
22142    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22143        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22144
22145        final int realMoveId = mNextMoveId.getAndIncrement();
22146        final Bundle extras = new Bundle();
22147        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22148        mMoveCallbacks.notifyCreated(realMoveId, extras);
22149
22150        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22151            @Override
22152            public void onCreated(int moveId, Bundle extras) {
22153                // Ignored
22154            }
22155
22156            @Override
22157            public void onStatusChanged(int moveId, int status, long estMillis) {
22158                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22159            }
22160        };
22161
22162        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22163        storage.setPrimaryStorageUuid(volumeUuid, callback);
22164        return realMoveId;
22165    }
22166
22167    @Override
22168    public int getMoveStatus(int moveId) {
22169        mContext.enforceCallingOrSelfPermission(
22170                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22171        return mMoveCallbacks.mLastStatus.get(moveId);
22172    }
22173
22174    @Override
22175    public void registerMoveCallback(IPackageMoveObserver callback) {
22176        mContext.enforceCallingOrSelfPermission(
22177                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22178        mMoveCallbacks.register(callback);
22179    }
22180
22181    @Override
22182    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22183        mContext.enforceCallingOrSelfPermission(
22184                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22185        mMoveCallbacks.unregister(callback);
22186    }
22187
22188    @Override
22189    public boolean setInstallLocation(int loc) {
22190        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22191                null);
22192        if (getInstallLocation() == loc) {
22193            return true;
22194        }
22195        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22196                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22197            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22198                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22199            return true;
22200        }
22201        return false;
22202   }
22203
22204    @Override
22205    public int getInstallLocation() {
22206        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22207                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22208                PackageHelper.APP_INSTALL_AUTO);
22209    }
22210
22211    /** Called by UserManagerService */
22212    void cleanUpUser(UserManagerService userManager, int userHandle) {
22213        synchronized (mPackages) {
22214            mDirtyUsers.remove(userHandle);
22215            mUserNeedsBadging.delete(userHandle);
22216            mSettings.removeUserLPw(userHandle);
22217            mPendingBroadcasts.remove(userHandle);
22218            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22219            removeUnusedPackagesLPw(userManager, userHandle);
22220        }
22221    }
22222
22223    /**
22224     * We're removing userHandle and would like to remove any downloaded packages
22225     * that are no longer in use by any other user.
22226     * @param userHandle the user being removed
22227     */
22228    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22229        final boolean DEBUG_CLEAN_APKS = false;
22230        int [] users = userManager.getUserIds();
22231        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22232        while (psit.hasNext()) {
22233            PackageSetting ps = psit.next();
22234            if (ps.pkg == null) {
22235                continue;
22236            }
22237            final String packageName = ps.pkg.packageName;
22238            // Skip over if system app
22239            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22240                continue;
22241            }
22242            if (DEBUG_CLEAN_APKS) {
22243                Slog.i(TAG, "Checking package " + packageName);
22244            }
22245            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22246            if (keep) {
22247                if (DEBUG_CLEAN_APKS) {
22248                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22249                }
22250            } else {
22251                for (int i = 0; i < users.length; i++) {
22252                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22253                        keep = true;
22254                        if (DEBUG_CLEAN_APKS) {
22255                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22256                                    + users[i]);
22257                        }
22258                        break;
22259                    }
22260                }
22261            }
22262            if (!keep) {
22263                if (DEBUG_CLEAN_APKS) {
22264                    Slog.i(TAG, "  Removing package " + packageName);
22265                }
22266                mHandler.post(new Runnable() {
22267                    public void run() {
22268                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22269                                userHandle, 0);
22270                    } //end run
22271                });
22272            }
22273        }
22274    }
22275
22276    /** Called by UserManagerService */
22277    void createNewUser(int userId, String[] disallowedPackages) {
22278        synchronized (mInstallLock) {
22279            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22280        }
22281        synchronized (mPackages) {
22282            scheduleWritePackageRestrictionsLocked(userId);
22283            scheduleWritePackageListLocked(userId);
22284            applyFactoryDefaultBrowserLPw(userId);
22285            primeDomainVerificationsLPw(userId);
22286        }
22287    }
22288
22289    void onNewUserCreated(final int userId) {
22290        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22291        // If permission review for legacy apps is required, we represent
22292        // dagerous permissions for such apps as always granted runtime
22293        // permissions to keep per user flag state whether review is needed.
22294        // Hence, if a new user is added we have to propagate dangerous
22295        // permission grants for these legacy apps.
22296        if (mPermissionReviewRequired) {
22297            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22298                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22299        }
22300    }
22301
22302    @Override
22303    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22304        mContext.enforceCallingOrSelfPermission(
22305                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22306                "Only package verification agents can read the verifier device identity");
22307
22308        synchronized (mPackages) {
22309            return mSettings.getVerifierDeviceIdentityLPw();
22310        }
22311    }
22312
22313    @Override
22314    public void setPermissionEnforced(String permission, boolean enforced) {
22315        // TODO: Now that we no longer change GID for storage, this should to away.
22316        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22317                "setPermissionEnforced");
22318        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22319            synchronized (mPackages) {
22320                if (mSettings.mReadExternalStorageEnforced == null
22321                        || mSettings.mReadExternalStorageEnforced != enforced) {
22322                    mSettings.mReadExternalStorageEnforced = enforced;
22323                    mSettings.writeLPr();
22324                }
22325            }
22326            // kill any non-foreground processes so we restart them and
22327            // grant/revoke the GID.
22328            final IActivityManager am = ActivityManager.getService();
22329            if (am != null) {
22330                final long token = Binder.clearCallingIdentity();
22331                try {
22332                    am.killProcessesBelowForeground("setPermissionEnforcement");
22333                } catch (RemoteException e) {
22334                } finally {
22335                    Binder.restoreCallingIdentity(token);
22336                }
22337            }
22338        } else {
22339            throw new IllegalArgumentException("No selective enforcement for " + permission);
22340        }
22341    }
22342
22343    @Override
22344    @Deprecated
22345    public boolean isPermissionEnforced(String permission) {
22346        return true;
22347    }
22348
22349    @Override
22350    public boolean isStorageLow() {
22351        final long token = Binder.clearCallingIdentity();
22352        try {
22353            final DeviceStorageMonitorInternal
22354                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22355            if (dsm != null) {
22356                return dsm.isMemoryLow();
22357            } else {
22358                return false;
22359            }
22360        } finally {
22361            Binder.restoreCallingIdentity(token);
22362        }
22363    }
22364
22365    @Override
22366    public IPackageInstaller getPackageInstaller() {
22367        return mInstallerService;
22368    }
22369
22370    private boolean userNeedsBadging(int userId) {
22371        int index = mUserNeedsBadging.indexOfKey(userId);
22372        if (index < 0) {
22373            final UserInfo userInfo;
22374            final long token = Binder.clearCallingIdentity();
22375            try {
22376                userInfo = sUserManager.getUserInfo(userId);
22377            } finally {
22378                Binder.restoreCallingIdentity(token);
22379            }
22380            final boolean b;
22381            if (userInfo != null && userInfo.isManagedProfile()) {
22382                b = true;
22383            } else {
22384                b = false;
22385            }
22386            mUserNeedsBadging.put(userId, b);
22387            return b;
22388        }
22389        return mUserNeedsBadging.valueAt(index);
22390    }
22391
22392    @Override
22393    public KeySet getKeySetByAlias(String packageName, String alias) {
22394        if (packageName == null || alias == null) {
22395            return null;
22396        }
22397        synchronized(mPackages) {
22398            final PackageParser.Package pkg = mPackages.get(packageName);
22399            if (pkg == null) {
22400                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22401                throw new IllegalArgumentException("Unknown package: " + packageName);
22402            }
22403            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22404            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22405        }
22406    }
22407
22408    @Override
22409    public KeySet getSigningKeySet(String packageName) {
22410        if (packageName == null) {
22411            return null;
22412        }
22413        synchronized(mPackages) {
22414            final PackageParser.Package pkg = mPackages.get(packageName);
22415            if (pkg == null) {
22416                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22417                throw new IllegalArgumentException("Unknown package: " + packageName);
22418            }
22419            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22420                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22421                throw new SecurityException("May not access signing KeySet of other apps.");
22422            }
22423            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22424            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22425        }
22426    }
22427
22428    @Override
22429    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22430        if (packageName == null || ks == null) {
22431            return false;
22432        }
22433        synchronized(mPackages) {
22434            final PackageParser.Package pkg = mPackages.get(packageName);
22435            if (pkg == null) {
22436                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22437                throw new IllegalArgumentException("Unknown package: " + packageName);
22438            }
22439            IBinder ksh = ks.getToken();
22440            if (ksh instanceof KeySetHandle) {
22441                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22442                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22443            }
22444            return false;
22445        }
22446    }
22447
22448    @Override
22449    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22450        if (packageName == null || ks == null) {
22451            return false;
22452        }
22453        synchronized(mPackages) {
22454            final PackageParser.Package pkg = mPackages.get(packageName);
22455            if (pkg == null) {
22456                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22457                throw new IllegalArgumentException("Unknown package: " + packageName);
22458            }
22459            IBinder ksh = ks.getToken();
22460            if (ksh instanceof KeySetHandle) {
22461                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22462                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22463            }
22464            return false;
22465        }
22466    }
22467
22468    private void deletePackageIfUnusedLPr(final String packageName) {
22469        PackageSetting ps = mSettings.mPackages.get(packageName);
22470        if (ps == null) {
22471            return;
22472        }
22473        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22474            // TODO Implement atomic delete if package is unused
22475            // It is currently possible that the package will be deleted even if it is installed
22476            // after this method returns.
22477            mHandler.post(new Runnable() {
22478                public void run() {
22479                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22480                            0, PackageManager.DELETE_ALL_USERS);
22481                }
22482            });
22483        }
22484    }
22485
22486    /**
22487     * Check and throw if the given before/after packages would be considered a
22488     * downgrade.
22489     */
22490    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22491            throws PackageManagerException {
22492        if (after.versionCode < before.mVersionCode) {
22493            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22494                    "Update version code " + after.versionCode + " is older than current "
22495                    + before.mVersionCode);
22496        } else if (after.versionCode == before.mVersionCode) {
22497            if (after.baseRevisionCode < before.baseRevisionCode) {
22498                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22499                        "Update base revision code " + after.baseRevisionCode
22500                        + " is older than current " + before.baseRevisionCode);
22501            }
22502
22503            if (!ArrayUtils.isEmpty(after.splitNames)) {
22504                for (int i = 0; i < after.splitNames.length; i++) {
22505                    final String splitName = after.splitNames[i];
22506                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22507                    if (j != -1) {
22508                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22509                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22510                                    "Update split " + splitName + " revision code "
22511                                    + after.splitRevisionCodes[i] + " is older than current "
22512                                    + before.splitRevisionCodes[j]);
22513                        }
22514                    }
22515                }
22516            }
22517        }
22518    }
22519
22520    private static class MoveCallbacks extends Handler {
22521        private static final int MSG_CREATED = 1;
22522        private static final int MSG_STATUS_CHANGED = 2;
22523
22524        private final RemoteCallbackList<IPackageMoveObserver>
22525                mCallbacks = new RemoteCallbackList<>();
22526
22527        private final SparseIntArray mLastStatus = new SparseIntArray();
22528
22529        public MoveCallbacks(Looper looper) {
22530            super(looper);
22531        }
22532
22533        public void register(IPackageMoveObserver callback) {
22534            mCallbacks.register(callback);
22535        }
22536
22537        public void unregister(IPackageMoveObserver callback) {
22538            mCallbacks.unregister(callback);
22539        }
22540
22541        @Override
22542        public void handleMessage(Message msg) {
22543            final SomeArgs args = (SomeArgs) msg.obj;
22544            final int n = mCallbacks.beginBroadcast();
22545            for (int i = 0; i < n; i++) {
22546                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22547                try {
22548                    invokeCallback(callback, msg.what, args);
22549                } catch (RemoteException ignored) {
22550                }
22551            }
22552            mCallbacks.finishBroadcast();
22553            args.recycle();
22554        }
22555
22556        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22557                throws RemoteException {
22558            switch (what) {
22559                case MSG_CREATED: {
22560                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22561                    break;
22562                }
22563                case MSG_STATUS_CHANGED: {
22564                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22565                    break;
22566                }
22567            }
22568        }
22569
22570        private void notifyCreated(int moveId, Bundle extras) {
22571            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22572
22573            final SomeArgs args = SomeArgs.obtain();
22574            args.argi1 = moveId;
22575            args.arg2 = extras;
22576            obtainMessage(MSG_CREATED, args).sendToTarget();
22577        }
22578
22579        private void notifyStatusChanged(int moveId, int status) {
22580            notifyStatusChanged(moveId, status, -1);
22581        }
22582
22583        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22584            Slog.v(TAG, "Move " + moveId + " status " + status);
22585
22586            final SomeArgs args = SomeArgs.obtain();
22587            args.argi1 = moveId;
22588            args.argi2 = status;
22589            args.arg3 = estMillis;
22590            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22591
22592            synchronized (mLastStatus) {
22593                mLastStatus.put(moveId, status);
22594            }
22595        }
22596    }
22597
22598    private final static class OnPermissionChangeListeners extends Handler {
22599        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22600
22601        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22602                new RemoteCallbackList<>();
22603
22604        public OnPermissionChangeListeners(Looper looper) {
22605            super(looper);
22606        }
22607
22608        @Override
22609        public void handleMessage(Message msg) {
22610            switch (msg.what) {
22611                case MSG_ON_PERMISSIONS_CHANGED: {
22612                    final int uid = msg.arg1;
22613                    handleOnPermissionsChanged(uid);
22614                } break;
22615            }
22616        }
22617
22618        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22619            mPermissionListeners.register(listener);
22620
22621        }
22622
22623        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22624            mPermissionListeners.unregister(listener);
22625        }
22626
22627        public void onPermissionsChanged(int uid) {
22628            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22629                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22630            }
22631        }
22632
22633        private void handleOnPermissionsChanged(int uid) {
22634            final int count = mPermissionListeners.beginBroadcast();
22635            try {
22636                for (int i = 0; i < count; i++) {
22637                    IOnPermissionsChangeListener callback = mPermissionListeners
22638                            .getBroadcastItem(i);
22639                    try {
22640                        callback.onPermissionsChanged(uid);
22641                    } catch (RemoteException e) {
22642                        Log.e(TAG, "Permission listener is dead", e);
22643                    }
22644                }
22645            } finally {
22646                mPermissionListeners.finishBroadcast();
22647            }
22648        }
22649    }
22650
22651    private class PackageManagerInternalImpl extends PackageManagerInternal {
22652        @Override
22653        public void setLocationPackagesProvider(PackagesProvider provider) {
22654            synchronized (mPackages) {
22655                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22656            }
22657        }
22658
22659        @Override
22660        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22661            synchronized (mPackages) {
22662                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22663            }
22664        }
22665
22666        @Override
22667        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22668            synchronized (mPackages) {
22669                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22670            }
22671        }
22672
22673        @Override
22674        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22675            synchronized (mPackages) {
22676                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22677            }
22678        }
22679
22680        @Override
22681        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22682            synchronized (mPackages) {
22683                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22684            }
22685        }
22686
22687        @Override
22688        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22689            synchronized (mPackages) {
22690                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22691            }
22692        }
22693
22694        @Override
22695        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22696            synchronized (mPackages) {
22697                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22698                        packageName, userId);
22699            }
22700        }
22701
22702        @Override
22703        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22704            synchronized (mPackages) {
22705                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22706                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22707                        packageName, userId);
22708            }
22709        }
22710
22711        @Override
22712        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22713            synchronized (mPackages) {
22714                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22715                        packageName, userId);
22716            }
22717        }
22718
22719        @Override
22720        public void setKeepUninstalledPackages(final List<String> packageList) {
22721            Preconditions.checkNotNull(packageList);
22722            List<String> removedFromList = null;
22723            synchronized (mPackages) {
22724                if (mKeepUninstalledPackages != null) {
22725                    final int packagesCount = mKeepUninstalledPackages.size();
22726                    for (int i = 0; i < packagesCount; i++) {
22727                        String oldPackage = mKeepUninstalledPackages.get(i);
22728                        if (packageList != null && packageList.contains(oldPackage)) {
22729                            continue;
22730                        }
22731                        if (removedFromList == null) {
22732                            removedFromList = new ArrayList<>();
22733                        }
22734                        removedFromList.add(oldPackage);
22735                    }
22736                }
22737                mKeepUninstalledPackages = new ArrayList<>(packageList);
22738                if (removedFromList != null) {
22739                    final int removedCount = removedFromList.size();
22740                    for (int i = 0; i < removedCount; i++) {
22741                        deletePackageIfUnusedLPr(removedFromList.get(i));
22742                    }
22743                }
22744            }
22745        }
22746
22747        @Override
22748        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22749            synchronized (mPackages) {
22750                // If we do not support permission review, done.
22751                if (!mPermissionReviewRequired) {
22752                    return false;
22753                }
22754
22755                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22756                if (packageSetting == null) {
22757                    return false;
22758                }
22759
22760                // Permission review applies only to apps not supporting the new permission model.
22761                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22762                    return false;
22763                }
22764
22765                // Legacy apps have the permission and get user consent on launch.
22766                PermissionsState permissionsState = packageSetting.getPermissionsState();
22767                return permissionsState.isPermissionReviewRequired(userId);
22768            }
22769        }
22770
22771        @Override
22772        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22773            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22774        }
22775
22776        @Override
22777        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22778                int userId) {
22779            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22780        }
22781
22782        @Override
22783        public void setDeviceAndProfileOwnerPackages(
22784                int deviceOwnerUserId, String deviceOwnerPackage,
22785                SparseArray<String> profileOwnerPackages) {
22786            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22787                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22788        }
22789
22790        @Override
22791        public boolean isPackageDataProtected(int userId, String packageName) {
22792            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22793        }
22794
22795        @Override
22796        public boolean isPackageEphemeral(int userId, String packageName) {
22797            synchronized (mPackages) {
22798                PackageParser.Package p = mPackages.get(packageName);
22799                return p != null ? p.applicationInfo.isInstantApp() : false;
22800            }
22801        }
22802
22803        @Override
22804        public boolean wasPackageEverLaunched(String packageName, int userId) {
22805            synchronized (mPackages) {
22806                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22807            }
22808        }
22809
22810        @Override
22811        public void grantRuntimePermission(String packageName, String name, int userId,
22812                boolean overridePolicy) {
22813            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22814                    overridePolicy);
22815        }
22816
22817        @Override
22818        public void revokeRuntimePermission(String packageName, String name, int userId,
22819                boolean overridePolicy) {
22820            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22821                    overridePolicy);
22822        }
22823
22824        @Override
22825        public String getNameForUid(int uid) {
22826            return PackageManagerService.this.getNameForUid(uid);
22827        }
22828
22829        @Override
22830        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22831                Intent origIntent, String resolvedType, Intent launchIntent,
22832                String callingPackage, int userId) {
22833            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22834                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22835        }
22836
22837        @Override
22838        public void grantEphemeralAccess(int userId, Intent intent,
22839                int targetAppId, int ephemeralAppId) {
22840            synchronized (mPackages) {
22841                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22842                        targetAppId, ephemeralAppId);
22843            }
22844        }
22845
22846        @Override
22847        public void pruneInstantApps() {
22848            synchronized (mPackages) {
22849                mInstantAppRegistry.pruneInstantAppsLPw();
22850            }
22851        }
22852
22853        @Override
22854        public String getSetupWizardPackageName() {
22855            return mSetupWizardPackage;
22856        }
22857
22858        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22859            if (policy != null) {
22860                mExternalSourcesPolicy = policy;
22861            }
22862        }
22863
22864        @Override
22865        public boolean isPackagePersistent(String packageName) {
22866            synchronized (mPackages) {
22867                PackageParser.Package pkg = mPackages.get(packageName);
22868                return pkg != null
22869                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22870                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22871                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22872                        : false;
22873            }
22874        }
22875
22876        @Override
22877        public List<PackageInfo> getOverlayPackages(int userId) {
22878            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22879            synchronized (mPackages) {
22880                for (PackageParser.Package p : mPackages.values()) {
22881                    if (p.mOverlayTarget != null) {
22882                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22883                        if (pkg != null) {
22884                            overlayPackages.add(pkg);
22885                        }
22886                    }
22887                }
22888            }
22889            return overlayPackages;
22890        }
22891
22892        @Override
22893        public List<String> getTargetPackageNames(int userId) {
22894            List<String> targetPackages = new ArrayList<>();
22895            synchronized (mPackages) {
22896                for (PackageParser.Package p : mPackages.values()) {
22897                    if (p.mOverlayTarget == null) {
22898                        targetPackages.add(p.packageName);
22899                    }
22900                }
22901            }
22902            return targetPackages;
22903        }
22904
22905
22906        @Override
22907        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22908                List<String> overlayPackageNames) {
22909            // TODO: implement when we integrate OMS properly
22910            return false;
22911        }
22912    }
22913
22914    @Override
22915    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22916        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22917        synchronized (mPackages) {
22918            final long identity = Binder.clearCallingIdentity();
22919            try {
22920                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22921                        packageNames, userId);
22922            } finally {
22923                Binder.restoreCallingIdentity(identity);
22924            }
22925        }
22926    }
22927
22928    @Override
22929    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22930        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22931        synchronized (mPackages) {
22932            final long identity = Binder.clearCallingIdentity();
22933            try {
22934                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
22935                        packageNames, userId);
22936            } finally {
22937                Binder.restoreCallingIdentity(identity);
22938            }
22939        }
22940    }
22941
22942    private static void enforceSystemOrPhoneCaller(String tag) {
22943        int callingUid = Binder.getCallingUid();
22944        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22945            throw new SecurityException(
22946                    "Cannot call " + tag + " from UID " + callingUid);
22947        }
22948    }
22949
22950    boolean isHistoricalPackageUsageAvailable() {
22951        return mPackageUsage.isHistoricalPackageUsageAvailable();
22952    }
22953
22954    /**
22955     * Return a <b>copy</b> of the collection of packages known to the package manager.
22956     * @return A copy of the values of mPackages.
22957     */
22958    Collection<PackageParser.Package> getPackages() {
22959        synchronized (mPackages) {
22960            return new ArrayList<>(mPackages.values());
22961        }
22962    }
22963
22964    /**
22965     * Logs process start information (including base APK hash) to the security log.
22966     * @hide
22967     */
22968    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22969            String apkFile, int pid) {
22970        if (!SecurityLog.isLoggingEnabled()) {
22971            return;
22972        }
22973        Bundle data = new Bundle();
22974        data.putLong("startTimestamp", System.currentTimeMillis());
22975        data.putString("processName", processName);
22976        data.putInt("uid", uid);
22977        data.putString("seinfo", seinfo);
22978        data.putString("apkFile", apkFile);
22979        data.putInt("pid", pid);
22980        Message msg = mProcessLoggingHandler.obtainMessage(
22981                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22982        msg.setData(data);
22983        mProcessLoggingHandler.sendMessage(msg);
22984    }
22985
22986    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22987        return mCompilerStats.getPackageStats(pkgName);
22988    }
22989
22990    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22991        return getOrCreateCompilerPackageStats(pkg.packageName);
22992    }
22993
22994    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22995        return mCompilerStats.getOrCreatePackageStats(pkgName);
22996    }
22997
22998    public void deleteCompilerPackageStats(String pkgName) {
22999        mCompilerStats.deletePackageStats(pkgName);
23000    }
23001
23002    @Override
23003    public int getInstallReason(String packageName, int userId) {
23004        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23005                true /* requireFullPermission */, false /* checkShell */,
23006                "get install reason");
23007        synchronized (mPackages) {
23008            final PackageSetting ps = mSettings.mPackages.get(packageName);
23009            if (ps != null) {
23010                return ps.getInstallReason(userId);
23011            }
23012        }
23013        return PackageManager.INSTALL_REASON_UNKNOWN;
23014    }
23015
23016    @Override
23017    public boolean canRequestPackageInstalls(String packageName, int userId) {
23018        int callingUid = Binder.getCallingUid();
23019        int uid = getPackageUid(packageName, 0, userId);
23020        if (callingUid != uid && callingUid != Process.ROOT_UID
23021                && callingUid != Process.SYSTEM_UID) {
23022            throw new SecurityException(
23023                    "Caller uid " + callingUid + " does not own package " + packageName);
23024        }
23025        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23026        if (info == null) {
23027            return false;
23028        }
23029        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23030            throw new UnsupportedOperationException(
23031                    "Operation only supported on apps targeting Android O or higher");
23032        }
23033        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23034        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23035        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23036            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23037        }
23038        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23039            return false;
23040        }
23041        if (mExternalSourcesPolicy != null) {
23042            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23043            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23044                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23045            }
23046        }
23047        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23048    }
23049}
23050