PackageManagerService.java revision 47698882f90b762b1bc960b5f6757a120d41bb78
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_INSTANT_APP_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.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
103
104import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
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.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
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.database.ContentObserver;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.BootTimingsTraceLog;
225import android.util.DisplayMetrics;
226import android.util.EventLog;
227import android.util.ExceptionUtils;
228import android.util.Log;
229import android.util.LogPrinter;
230import android.util.MathUtils;
231import android.util.PackageUtils;
232import android.util.Pair;
233import android.util.PrintStreamPrinter;
234import android.util.Slog;
235import android.util.SparseArray;
236import android.util.SparseBooleanArray;
237import android.util.SparseIntArray;
238import android.util.Xml;
239import android.util.jar.StrictJarFile;
240import android.util.proto.ProtoOutputStream;
241import android.view.Display;
242
243import com.android.internal.R;
244import com.android.internal.annotations.GuardedBy;
245import com.android.internal.app.IMediaContainerService;
246import com.android.internal.app.ResolverActivity;
247import com.android.internal.content.NativeLibraryHelper;
248import com.android.internal.content.PackageHelper;
249import com.android.internal.logging.MetricsLogger;
250import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
251import com.android.internal.os.IParcelFileDescriptorFactory;
252import com.android.internal.os.RoSystemProperties;
253import com.android.internal.os.SomeArgs;
254import com.android.internal.os.Zygote;
255import com.android.internal.telephony.CarrierAppUtils;
256import com.android.internal.util.ArrayUtils;
257import com.android.internal.util.ConcurrentUtils;
258import com.android.internal.util.DumpUtils;
259import com.android.internal.util.FastPrintWriter;
260import com.android.internal.util.FastXmlSerializer;
261import com.android.internal.util.IndentingPrintWriter;
262import com.android.internal.util.Preconditions;
263import com.android.internal.util.XmlUtils;
264import com.android.server.AttributeCache;
265import com.android.server.DeviceIdleController;
266import com.android.server.EventLogTags;
267import com.android.server.FgThread;
268import com.android.server.IntentResolver;
269import com.android.server.LocalServices;
270import com.android.server.LockGuard;
271import com.android.server.ServiceThread;
272import com.android.server.SystemConfig;
273import com.android.server.SystemServerInitThreadPool;
274import com.android.server.Watchdog;
275import com.android.server.net.NetworkPolicyManagerInternal;
276import com.android.server.pm.Installer.InstallerException;
277import com.android.server.pm.PermissionsState.PermissionState;
278import com.android.server.pm.Settings.DatabaseVersion;
279import com.android.server.pm.Settings.VersionInfo;
280import com.android.server.pm.dex.DexManager;
281import com.android.server.storage.DeviceStorageMonitorInternal;
282
283import dalvik.system.CloseGuard;
284import dalvik.system.DexFile;
285import dalvik.system.VMRuntime;
286
287import libcore.io.IoUtils;
288import libcore.util.EmptyArray;
289
290import org.xmlpull.v1.XmlPullParser;
291import org.xmlpull.v1.XmlPullParserException;
292import org.xmlpull.v1.XmlSerializer;
293
294import java.io.BufferedOutputStream;
295import java.io.BufferedReader;
296import java.io.ByteArrayInputStream;
297import java.io.ByteArrayOutputStream;
298import java.io.File;
299import java.io.FileDescriptor;
300import java.io.FileInputStream;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub
369        implements PackageSender {
370    static final String TAG = "PackageManager";
371    static final boolean DEBUG_SETTINGS = false;
372    static final boolean DEBUG_PREFERRED = false;
373    static final boolean DEBUG_UPGRADE = false;
374    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
375    private static final boolean DEBUG_BACKUP = false;
376    private static final boolean DEBUG_INSTALL = false;
377    private static final boolean DEBUG_REMOVE = false;
378    private static final boolean DEBUG_BROADCASTS = false;
379    private static final boolean DEBUG_SHOW_INFO = false;
380    private static final boolean DEBUG_PACKAGE_INFO = false;
381    private static final boolean DEBUG_INTENT_MATCHING = false;
382    private static final boolean DEBUG_PACKAGE_SCANNING = false;
383    private static final boolean DEBUG_VERIFY = false;
384    private static final boolean DEBUG_FILTERS = false;
385    private static final boolean DEBUG_PERMISSIONS = false;
386    private static final boolean DEBUG_SHARED_LIBRARIES = false;
387
388    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
389    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
390    // user, but by default initialize to this.
391    public static final boolean DEBUG_DEXOPT = false;
392
393    private static final boolean DEBUG_ABI_SELECTION = false;
394    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
395    private static final boolean DEBUG_TRIAGED_MISSING = false;
396    private static final boolean DEBUG_APP_DATA = false;
397
398    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
399    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
400
401    private static final boolean HIDE_EPHEMERAL_APIS = false;
402
403    private static final boolean ENABLE_FREE_CACHE_V2 =
404            SystemProperties.getBoolean("fw.free_cache_v2", true);
405
406    private static final int RADIO_UID = Process.PHONE_UID;
407    private static final int LOG_UID = Process.LOG_UID;
408    private static final int NFC_UID = Process.NFC_UID;
409    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
410    private static final int SHELL_UID = Process.SHELL_UID;
411
412    // Cap the size of permission trees that 3rd party apps can define
413    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
414
415    // Suffix used during package installation when copying/moving
416    // package apks to install directory.
417    private static final String INSTALL_PACKAGE_SUFFIX = "-";
418
419    static final int SCAN_NO_DEX = 1<<1;
420    static final int SCAN_FORCE_DEX = 1<<2;
421    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
422    static final int SCAN_NEW_INSTALL = 1<<4;
423    static final int SCAN_UPDATE_TIME = 1<<5;
424    static final int SCAN_BOOTING = 1<<6;
425    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
426    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
427    static final int SCAN_REPLACING = 1<<9;
428    static final int SCAN_REQUIRE_KNOWN = 1<<10;
429    static final int SCAN_MOVE = 1<<11;
430    static final int SCAN_INITIAL = 1<<12;
431    static final int SCAN_CHECK_ONLY = 1<<13;
432    static final int SCAN_DONT_KILL_APP = 1<<14;
433    static final int SCAN_IGNORE_FROZEN = 1<<15;
434    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
435    static final int SCAN_AS_INSTANT_APP = 1<<17;
436    static final int SCAN_AS_FULL_APP = 1<<18;
437    /** Should not be with the scan flags */
438    static final int FLAGS_REMOVE_CHATTY = 1<<31;
439
440    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
441
442    private static final int[] EMPTY_INT_ARRAY = new int[0];
443
444    /**
445     * Timeout (in milliseconds) after which the watchdog should declare that
446     * our handler thread is wedged.  The usual default for such things is one
447     * minute but we sometimes do very lengthy I/O operations on this thread,
448     * such as installing multi-gigabyte applications, so ours needs to be longer.
449     */
450    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
451
452    /**
453     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
454     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
455     * settings entry if available, otherwise we use the hardcoded default.  If it's been
456     * more than this long since the last fstrim, we force one during the boot sequence.
457     *
458     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
459     * one gets run at the next available charging+idle time.  This final mandatory
460     * no-fstrim check kicks in only of the other scheduling criteria is never met.
461     */
462    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
463
464    /**
465     * Whether verification is enabled by default.
466     */
467    private static final boolean DEFAULT_VERIFY_ENABLE = true;
468
469    /**
470     * The default maximum time to wait for the verification agent to return in
471     * milliseconds.
472     */
473    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
474
475    /**
476     * The default response for package verification timeout.
477     *
478     * This can be either PackageManager.VERIFICATION_ALLOW or
479     * PackageManager.VERIFICATION_REJECT.
480     */
481    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
482
483    static final String PLATFORM_PACKAGE_NAME = "android";
484
485    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
486
487    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
488            DEFAULT_CONTAINER_PACKAGE,
489            "com.android.defcontainer.DefaultContainerService");
490
491    private static final String KILL_APP_REASON_GIDS_CHANGED =
492            "permission grant or revoke changed gids";
493
494    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
495            "permissions revoked";
496
497    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
498
499    private static final String PACKAGE_SCHEME = "package";
500
501    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
502
503    /** Permission grant: not grant the permission. */
504    private static final int GRANT_DENIED = 1;
505
506    /** Permission grant: grant the permission as an install permission. */
507    private static final int GRANT_INSTALL = 2;
508
509    /** Permission grant: grant the permission as a runtime one. */
510    private static final int GRANT_RUNTIME = 3;
511
512    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
513    private static final int GRANT_UPGRADE = 4;
514
515    /** Canonical intent used to identify what counts as a "web browser" app */
516    private static final Intent sBrowserIntent;
517    static {
518        sBrowserIntent = new Intent();
519        sBrowserIntent.setAction(Intent.ACTION_VIEW);
520        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
521        sBrowserIntent.setData(Uri.parse("http:"));
522    }
523
524    /**
525     * The set of all protected actions [i.e. those actions for which a high priority
526     * intent filter is disallowed].
527     */
528    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
529    static {
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
531        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
532        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
533        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
534    }
535
536    // Compilation reasons.
537    public static final int REASON_FIRST_BOOT = 0;
538    public static final int REASON_BOOT = 1;
539    public static final int REASON_INSTALL = 2;
540    public static final int REASON_BACKGROUND_DEXOPT = 3;
541    public static final int REASON_AB_OTA = 4;
542
543    public static final int REASON_LAST = REASON_AB_OTA;
544
545    /** All dangerous permission names in the same order as the events in MetricsEvent */
546    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
547            Manifest.permission.READ_CALENDAR,
548            Manifest.permission.WRITE_CALENDAR,
549            Manifest.permission.CAMERA,
550            Manifest.permission.READ_CONTACTS,
551            Manifest.permission.WRITE_CONTACTS,
552            Manifest.permission.GET_ACCOUNTS,
553            Manifest.permission.ACCESS_FINE_LOCATION,
554            Manifest.permission.ACCESS_COARSE_LOCATION,
555            Manifest.permission.RECORD_AUDIO,
556            Manifest.permission.READ_PHONE_STATE,
557            Manifest.permission.CALL_PHONE,
558            Manifest.permission.READ_CALL_LOG,
559            Manifest.permission.WRITE_CALL_LOG,
560            Manifest.permission.ADD_VOICEMAIL,
561            Manifest.permission.USE_SIP,
562            Manifest.permission.PROCESS_OUTGOING_CALLS,
563            Manifest.permission.READ_CELL_BROADCASTS,
564            Manifest.permission.BODY_SENSORS,
565            Manifest.permission.SEND_SMS,
566            Manifest.permission.RECEIVE_SMS,
567            Manifest.permission.READ_SMS,
568            Manifest.permission.RECEIVE_WAP_PUSH,
569            Manifest.permission.RECEIVE_MMS,
570            Manifest.permission.READ_EXTERNAL_STORAGE,
571            Manifest.permission.WRITE_EXTERNAL_STORAGE,
572            Manifest.permission.READ_PHONE_NUMBERS,
573            Manifest.permission.ANSWER_PHONE_CALLS);
574
575
576    /**
577     * Version number for the package parser cache. Increment this whenever the format or
578     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
579     */
580    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
581
582    /**
583     * Whether the package parser cache is enabled.
584     */
585    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
586
587    final ServiceThread mHandlerThread;
588
589    final PackageHandler mHandler;
590
591    private final ProcessLoggingHandler mProcessLoggingHandler;
592
593    /**
594     * Messages for {@link #mHandler} that need to wait for system ready before
595     * being dispatched.
596     */
597    private ArrayList<Message> mPostSystemReadyMessages;
598
599    final int mSdkVersion = Build.VERSION.SDK_INT;
600
601    final Context mContext;
602    final boolean mFactoryTest;
603    final boolean mOnlyCore;
604    final DisplayMetrics mMetrics;
605    final int mDefParseFlags;
606    final String[] mSeparateProcesses;
607    final boolean mIsUpgrade;
608    final boolean mIsPreNUpgrade;
609    final boolean mIsPreNMR1Upgrade;
610
611    // Have we told the Activity Manager to whitelist the default container service by uid yet?
612    @GuardedBy("mPackages")
613    boolean mDefaultContainerWhitelisted = false;
614
615    @GuardedBy("mPackages")
616    private boolean mDexOptDialogShown;
617
618    /** The location for ASEC container files on internal storage. */
619    final String mAsecInternalPath;
620
621    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
622    // LOCK HELD.  Can be called with mInstallLock held.
623    @GuardedBy("mInstallLock")
624    final Installer mInstaller;
625
626    /** Directory where installed third-party apps stored */
627    final File mAppInstallDir;
628
629    /**
630     * Directory to which applications installed internally have their
631     * 32 bit native libraries copied.
632     */
633    private File mAppLib32InstallDir;
634
635    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
636    // apps.
637    final File mDrmAppPrivateInstallDir;
638
639    // ----------------------------------------------------------------
640
641    // Lock for state used when installing and doing other long running
642    // operations.  Methods that must be called with this lock held have
643    // the suffix "LI".
644    final Object mInstallLock = new Object();
645
646    // ----------------------------------------------------------------
647
648    // Keys are String (package name), values are Package.  This also serves
649    // as the lock for the global state.  Methods that must be called with
650    // this lock held have the prefix "LP".
651    @GuardedBy("mPackages")
652    final ArrayMap<String, PackageParser.Package> mPackages =
653            new ArrayMap<String, PackageParser.Package>();
654
655    final ArrayMap<String, Set<String>> mKnownCodebase =
656            new ArrayMap<String, Set<String>>();
657
658    // Keys are isolated uids and values are the uid of the application
659    // that created the isolated proccess.
660    @GuardedBy("mPackages")
661    final SparseIntArray mIsolatedOwners = new SparseIntArray();
662
663    // List of APK paths to load for each user and package. This data is never
664    // persisted by the package manager. Instead, the overlay manager will
665    // ensure the data is up-to-date in runtime.
666    @GuardedBy("mPackages")
667    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
668        new SparseArray<ArrayMap<String, ArrayList<String>>>();
669
670    /**
671     * Tracks new system packages [received in an OTA] that we expect to
672     * find updated user-installed versions. Keys are package name, values
673     * are package location.
674     */
675    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
676    /**
677     * Tracks high priority intent filters for protected actions. During boot, certain
678     * filter actions are protected and should never be allowed to have a high priority
679     * intent filter for them. However, there is one, and only one exception -- the
680     * setup wizard. It must be able to define a high priority intent filter for these
681     * actions to ensure there are no escapes from the wizard. We need to delay processing
682     * of these during boot as we need to look at all of the system packages in order
683     * to know which component is the setup wizard.
684     */
685    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
686    /**
687     * Whether or not processing protected filters should be deferred.
688     */
689    private boolean mDeferProtectedFilters = true;
690
691    /**
692     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
693     */
694    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
695    /**
696     * Whether or not system app permissions should be promoted from install to runtime.
697     */
698    boolean mPromoteSystemApps;
699
700    @GuardedBy("mPackages")
701    final Settings mSettings;
702
703    /**
704     * Set of package names that are currently "frozen", which means active
705     * surgery is being done on the code/data for that package. The platform
706     * will refuse to launch frozen packages to avoid race conditions.
707     *
708     * @see PackageFreezer
709     */
710    @GuardedBy("mPackages")
711    final ArraySet<String> mFrozenPackages = new ArraySet<>();
712
713    final ProtectedPackages mProtectedPackages;
714
715    boolean mFirstBoot;
716
717    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
718
719    // System configuration read by SystemConfig.
720    final int[] mGlobalGids;
721    final SparseArray<ArraySet<String>> mSystemPermissions;
722    @GuardedBy("mAvailableFeatures")
723    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
724
725    // If mac_permissions.xml was found for seinfo labeling.
726    boolean mFoundPolicyFile;
727
728    private final InstantAppRegistry mInstantAppRegistry;
729
730    @GuardedBy("mPackages")
731    int mChangedPackagesSequenceNumber;
732    /**
733     * List of changed [installed, removed or updated] packages.
734     * mapping from user id -> sequence number -> package name
735     */
736    @GuardedBy("mPackages")
737    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
738    /**
739     * The sequence number of the last change to a package.
740     * mapping from user id -> package name -> sequence number
741     */
742    @GuardedBy("mPackages")
743    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
744
745    class PackageParserCallback implements PackageParser.Callback {
746        @Override public final boolean hasFeature(String feature) {
747            return PackageManagerService.this.hasSystemFeature(feature, 0);
748        }
749
750        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
751                Collection<PackageParser.Package> allPackages, String targetPackageName) {
752            List<PackageParser.Package> overlayPackages = null;
753            for (PackageParser.Package p : allPackages) {
754                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
755                    if (overlayPackages == null) {
756                        overlayPackages = new ArrayList<PackageParser.Package>();
757                    }
758                    overlayPackages.add(p);
759                }
760            }
761            if (overlayPackages != null) {
762                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
763                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
764                        return p1.mOverlayPriority - p2.mOverlayPriority;
765                    }
766                };
767                Collections.sort(overlayPackages, cmp);
768            }
769            return overlayPackages;
770        }
771
772        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
773                String targetPackageName, String targetPath) {
774            if ("android".equals(targetPackageName)) {
775                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
776                // native AssetManager.
777                return null;
778            }
779            List<PackageParser.Package> overlayPackages =
780                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
781            if (overlayPackages == null || overlayPackages.isEmpty()) {
782                return null;
783            }
784            List<String> overlayPathList = null;
785            for (PackageParser.Package overlayPackage : overlayPackages) {
786                if (targetPath == null) {
787                    if (overlayPathList == null) {
788                        overlayPathList = new ArrayList<String>();
789                    }
790                    overlayPathList.add(overlayPackage.baseCodePath);
791                    continue;
792                }
793
794                try {
795                    // Creates idmaps for system to parse correctly the Android manifest of the
796                    // target package.
797                    //
798                    // OverlayManagerService will update each of them with a correct gid from its
799                    // target package app id.
800                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
801                            UserHandle.getSharedAppGid(
802                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
803                    if (overlayPathList == null) {
804                        overlayPathList = new ArrayList<String>();
805                    }
806                    overlayPathList.add(overlayPackage.baseCodePath);
807                } catch (InstallerException e) {
808                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
809                            overlayPackage.baseCodePath);
810                }
811            }
812            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
813        }
814
815        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
816            synchronized (mPackages) {
817                return getStaticOverlayPathsLocked(
818                        mPackages.values(), targetPackageName, targetPath);
819            }
820        }
821
822        @Override public final String[] getOverlayApks(String targetPackageName) {
823            return getStaticOverlayPaths(targetPackageName, null);
824        }
825
826        @Override public final String[] getOverlayPaths(String targetPackageName,
827                String targetPath) {
828            return getStaticOverlayPaths(targetPackageName, targetPath);
829        }
830    };
831
832    class ParallelPackageParserCallback extends PackageParserCallback {
833        List<PackageParser.Package> mOverlayPackages = null;
834
835        void findStaticOverlayPackages() {
836            synchronized (mPackages) {
837                for (PackageParser.Package p : mPackages.values()) {
838                    if (p.mIsStaticOverlay) {
839                        if (mOverlayPackages == null) {
840                            mOverlayPackages = new ArrayList<PackageParser.Package>();
841                        }
842                        mOverlayPackages.add(p);
843                    }
844                }
845            }
846        }
847
848        @Override
849        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            // We can trust mOverlayPackages without holding mPackages because package uninstall
851            // can't happen while running parallel parsing.
852            // Moreover holding mPackages on each parsing thread causes dead-lock.
853            return mOverlayPackages == null ? null :
854                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
855        }
856    }
857
858    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
859    final ParallelPackageParserCallback mParallelPackageParserCallback =
860            new ParallelPackageParserCallback();
861
862    public static final class SharedLibraryEntry {
863        public final String path;
864        public final String apk;
865        public final SharedLibraryInfo info;
866
867        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
868                String declaringPackageName, int declaringPackageVersionCode) {
869            path = _path;
870            apk = _apk;
871            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
872                    declaringPackageName, declaringPackageVersionCode), null);
873        }
874    }
875
876    // Currently known shared libraries.
877    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
878    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
879            new ArrayMap<>();
880
881    // All available activities, for your resolving pleasure.
882    final ActivityIntentResolver mActivities =
883            new ActivityIntentResolver();
884
885    // All available receivers, for your resolving pleasure.
886    final ActivityIntentResolver mReceivers =
887            new ActivityIntentResolver();
888
889    // All available services, for your resolving pleasure.
890    final ServiceIntentResolver mServices = new ServiceIntentResolver();
891
892    // All available providers, for your resolving pleasure.
893    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
894
895    // Mapping from provider base names (first directory in content URI codePath)
896    // to the provider information.
897    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
898            new ArrayMap<String, PackageParser.Provider>();
899
900    // Mapping from instrumentation class names to info about them.
901    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
902            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
903
904    // Mapping from permission names to info about them.
905    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
906            new ArrayMap<String, PackageParser.PermissionGroup>();
907
908    // Packages whose data we have transfered into another package, thus
909    // should no longer exist.
910    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
911
912    // Broadcast actions that are only available to the system.
913    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
914
915    /** List of packages waiting for verification. */
916    final SparseArray<PackageVerificationState> mPendingVerification
917            = new SparseArray<PackageVerificationState>();
918
919    /** Set of packages associated with each app op permission. */
920    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
921
922    final PackageInstallerService mInstallerService;
923
924    private final PackageDexOptimizer mPackageDexOptimizer;
925    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
926    // is used by other apps).
927    private final DexManager mDexManager;
928
929    private AtomicInteger mNextMoveId = new AtomicInteger();
930    private final MoveCallbacks mMoveCallbacks;
931
932    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
933
934    // Cache of users who need badging.
935    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
936
937    /** Token for keys in mPendingVerification. */
938    private int mPendingVerificationToken = 0;
939
940    volatile boolean mSystemReady;
941    volatile boolean mSafeMode;
942    volatile boolean mHasSystemUidErrors;
943    private volatile boolean mEphemeralAppsDisabled;
944
945    ApplicationInfo mAndroidApplication;
946    final ActivityInfo mResolveActivity = new ActivityInfo();
947    final ResolveInfo mResolveInfo = new ResolveInfo();
948    ComponentName mResolveComponentName;
949    PackageParser.Package mPlatformPackage;
950    ComponentName mCustomResolverComponentName;
951
952    boolean mResolverReplaced = false;
953
954    private final @Nullable ComponentName mIntentFilterVerifierComponent;
955    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
956
957    private int mIntentFilterVerificationToken = 0;
958
959    /** The service connection to the ephemeral resolver */
960    final EphemeralResolverConnection mInstantAppResolverConnection;
961    /** Component used to show resolver settings for Instant Apps */
962    final ComponentName mInstantAppResolverSettingsComponent;
963
964    /** Activity used to install instant applications */
965    ActivityInfo mInstantAppInstallerActivity;
966    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
967
968    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
969            = new SparseArray<IntentFilterVerificationState>();
970
971    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
972
973    // List of packages names to keep cached, even if they are uninstalled for all users
974    private List<String> mKeepUninstalledPackages;
975
976    private UserManagerInternal mUserManagerInternal;
977
978    private DeviceIdleController.LocalService mDeviceIdleController;
979
980    private File mCacheDir;
981
982    private ArraySet<String> mPrivappPermissionsViolations;
983
984    private Future<?> mPrepareAppDataFuture;
985
986    private static class IFVerificationParams {
987        PackageParser.Package pkg;
988        boolean replacing;
989        int userId;
990        int verifierUid;
991
992        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
993                int _userId, int _verifierUid) {
994            pkg = _pkg;
995            replacing = _replacing;
996            userId = _userId;
997            replacing = _replacing;
998            verifierUid = _verifierUid;
999        }
1000    }
1001
1002    private interface IntentFilterVerifier<T extends IntentFilter> {
1003        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1004                                               T filter, String packageName);
1005        void startVerifications(int userId);
1006        void receiveVerificationResponse(int verificationId);
1007    }
1008
1009    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1010        private Context mContext;
1011        private ComponentName mIntentFilterVerifierComponent;
1012        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1013
1014        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1015            mContext = context;
1016            mIntentFilterVerifierComponent = verifierComponent;
1017        }
1018
1019        private String getDefaultScheme() {
1020            return IntentFilter.SCHEME_HTTPS;
1021        }
1022
1023        @Override
1024        public void startVerifications(int userId) {
1025            // Launch verifications requests
1026            int count = mCurrentIntentFilterVerifications.size();
1027            for (int n=0; n<count; n++) {
1028                int verificationId = mCurrentIntentFilterVerifications.get(n);
1029                final IntentFilterVerificationState ivs =
1030                        mIntentFilterVerificationStates.get(verificationId);
1031
1032                String packageName = ivs.getPackageName();
1033
1034                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1035                final int filterCount = filters.size();
1036                ArraySet<String> domainsSet = new ArraySet<>();
1037                for (int m=0; m<filterCount; m++) {
1038                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1039                    domainsSet.addAll(filter.getHostsList());
1040                }
1041                synchronized (mPackages) {
1042                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1043                            packageName, domainsSet) != null) {
1044                        scheduleWriteSettingsLocked();
1045                    }
1046                }
1047                sendVerificationRequest(userId, verificationId, ivs);
1048            }
1049            mCurrentIntentFilterVerifications.clear();
1050        }
1051
1052        private void sendVerificationRequest(int userId, int verificationId,
1053                IntentFilterVerificationState ivs) {
1054
1055            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1056            verificationIntent.putExtra(
1057                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1058                    verificationId);
1059            verificationIntent.putExtra(
1060                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1061                    getDefaultScheme());
1062            verificationIntent.putExtra(
1063                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1064                    ivs.getHostsString());
1065            verificationIntent.putExtra(
1066                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1067                    ivs.getPackageName());
1068            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1069            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1070
1071            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1072            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1073                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1074                    userId, false, "intent filter verifier");
1075
1076            UserHandle user = new UserHandle(userId);
1077            mContext.sendBroadcastAsUser(verificationIntent, user);
1078            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1079                    "Sending IntentFilter verification broadcast");
1080        }
1081
1082        public void receiveVerificationResponse(int verificationId) {
1083            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1084
1085            final boolean verified = ivs.isVerified();
1086
1087            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1088            final int count = filters.size();
1089            if (DEBUG_DOMAIN_VERIFICATION) {
1090                Slog.i(TAG, "Received verification response " + verificationId
1091                        + " for " + count + " filters, verified=" + verified);
1092            }
1093            for (int n=0; n<count; n++) {
1094                PackageParser.ActivityIntentInfo filter = filters.get(n);
1095                filter.setVerified(verified);
1096
1097                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1098                        + " verified with result:" + verified + " and hosts:"
1099                        + ivs.getHostsString());
1100            }
1101
1102            mIntentFilterVerificationStates.remove(verificationId);
1103
1104            final String packageName = ivs.getPackageName();
1105            IntentFilterVerificationInfo ivi = null;
1106
1107            synchronized (mPackages) {
1108                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1109            }
1110            if (ivi == null) {
1111                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1112                        + verificationId + " packageName:" + packageName);
1113                return;
1114            }
1115            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1116                    "Updating IntentFilterVerificationInfo for package " + packageName
1117                            +" verificationId:" + verificationId);
1118
1119            synchronized (mPackages) {
1120                if (verified) {
1121                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1122                } else {
1123                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1124                }
1125                scheduleWriteSettingsLocked();
1126
1127                final int userId = ivs.getUserId();
1128                if (userId != UserHandle.USER_ALL) {
1129                    final int userStatus =
1130                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1131
1132                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1133                    boolean needUpdate = false;
1134
1135                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1136                    // already been set by the User thru the Disambiguation dialog
1137                    switch (userStatus) {
1138                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1139                            if (verified) {
1140                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1141                            } else {
1142                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1143                            }
1144                            needUpdate = true;
1145                            break;
1146
1147                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1148                            if (verified) {
1149                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1150                                needUpdate = true;
1151                            }
1152                            break;
1153
1154                        default:
1155                            // Nothing to do
1156                    }
1157
1158                    if (needUpdate) {
1159                        mSettings.updateIntentFilterVerificationStatusLPw(
1160                                packageName, updatedStatus, userId);
1161                        scheduleWritePackageRestrictionsLocked(userId);
1162                    }
1163                }
1164            }
1165        }
1166
1167        @Override
1168        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1169                    ActivityIntentInfo filter, String packageName) {
1170            if (!hasValidDomains(filter)) {
1171                return false;
1172            }
1173            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1174            if (ivs == null) {
1175                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1176                        packageName);
1177            }
1178            if (DEBUG_DOMAIN_VERIFICATION) {
1179                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1180            }
1181            ivs.addFilter(filter);
1182            return true;
1183        }
1184
1185        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1186                int userId, int verificationId, String packageName) {
1187            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1188                    verifierUid, userId, packageName);
1189            ivs.setPendingState();
1190            synchronized (mPackages) {
1191                mIntentFilterVerificationStates.append(verificationId, ivs);
1192                mCurrentIntentFilterVerifications.add(verificationId);
1193            }
1194            return ivs;
1195        }
1196    }
1197
1198    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1199        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1200                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1201                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1202    }
1203
1204    // Set of pending broadcasts for aggregating enable/disable of components.
1205    static class PendingPackageBroadcasts {
1206        // for each user id, a map of <package name -> components within that package>
1207        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1208
1209        public PendingPackageBroadcasts() {
1210            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1211        }
1212
1213        public ArrayList<String> get(int userId, String packageName) {
1214            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1215            return packages.get(packageName);
1216        }
1217
1218        public void put(int userId, String packageName, ArrayList<String> components) {
1219            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1220            packages.put(packageName, components);
1221        }
1222
1223        public void remove(int userId, String packageName) {
1224            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1225            if (packages != null) {
1226                packages.remove(packageName);
1227            }
1228        }
1229
1230        public void remove(int userId) {
1231            mUidMap.remove(userId);
1232        }
1233
1234        public int userIdCount() {
1235            return mUidMap.size();
1236        }
1237
1238        public int userIdAt(int n) {
1239            return mUidMap.keyAt(n);
1240        }
1241
1242        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1243            return mUidMap.get(userId);
1244        }
1245
1246        public int size() {
1247            // total number of pending broadcast entries across all userIds
1248            int num = 0;
1249            for (int i = 0; i< mUidMap.size(); i++) {
1250                num += mUidMap.valueAt(i).size();
1251            }
1252            return num;
1253        }
1254
1255        public void clear() {
1256            mUidMap.clear();
1257        }
1258
1259        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1260            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1261            if (map == null) {
1262                map = new ArrayMap<String, ArrayList<String>>();
1263                mUidMap.put(userId, map);
1264            }
1265            return map;
1266        }
1267    }
1268    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1269
1270    // Service Connection to remote media container service to copy
1271    // package uri's from external media onto secure containers
1272    // or internal storage.
1273    private IMediaContainerService mContainerService = null;
1274
1275    static final int SEND_PENDING_BROADCAST = 1;
1276    static final int MCS_BOUND = 3;
1277    static final int END_COPY = 4;
1278    static final int INIT_COPY = 5;
1279    static final int MCS_UNBIND = 6;
1280    static final int START_CLEANING_PACKAGE = 7;
1281    static final int FIND_INSTALL_LOC = 8;
1282    static final int POST_INSTALL = 9;
1283    static final int MCS_RECONNECT = 10;
1284    static final int MCS_GIVE_UP = 11;
1285    static final int UPDATED_MEDIA_STATUS = 12;
1286    static final int WRITE_SETTINGS = 13;
1287    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1288    static final int PACKAGE_VERIFIED = 15;
1289    static final int CHECK_PENDING_VERIFICATION = 16;
1290    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1291    static final int INTENT_FILTER_VERIFIED = 18;
1292    static final int WRITE_PACKAGE_LIST = 19;
1293    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1294
1295    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1296
1297    // Delay time in millisecs
1298    static final int BROADCAST_DELAY = 10 * 1000;
1299
1300    static UserManagerService sUserManager;
1301
1302    // Stores a list of users whose package restrictions file needs to be updated
1303    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1304
1305    final private DefaultContainerConnection mDefContainerConn =
1306            new DefaultContainerConnection();
1307    class DefaultContainerConnection implements ServiceConnection {
1308        public void onServiceConnected(ComponentName name, IBinder service) {
1309            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1310            final IMediaContainerService imcs = IMediaContainerService.Stub
1311                    .asInterface(Binder.allowBlocking(service));
1312            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1313        }
1314
1315        public void onServiceDisconnected(ComponentName name) {
1316            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1317        }
1318    }
1319
1320    // Recordkeeping of restore-after-install operations that are currently in flight
1321    // between the Package Manager and the Backup Manager
1322    static class PostInstallData {
1323        public InstallArgs args;
1324        public PackageInstalledInfo res;
1325
1326        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1327            args = _a;
1328            res = _r;
1329        }
1330    }
1331
1332    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1333    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1334
1335    // XML tags for backup/restore of various bits of state
1336    private static final String TAG_PREFERRED_BACKUP = "pa";
1337    private static final String TAG_DEFAULT_APPS = "da";
1338    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1339
1340    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1341    private static final String TAG_ALL_GRANTS = "rt-grants";
1342    private static final String TAG_GRANT = "grant";
1343    private static final String ATTR_PACKAGE_NAME = "pkg";
1344
1345    private static final String TAG_PERMISSION = "perm";
1346    private static final String ATTR_PERMISSION_NAME = "name";
1347    private static final String ATTR_IS_GRANTED = "g";
1348    private static final String ATTR_USER_SET = "set";
1349    private static final String ATTR_USER_FIXED = "fixed";
1350    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1351
1352    // System/policy permission grants are not backed up
1353    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1354            FLAG_PERMISSION_POLICY_FIXED
1355            | FLAG_PERMISSION_SYSTEM_FIXED
1356            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1357
1358    // And we back up these user-adjusted states
1359    private static final int USER_RUNTIME_GRANT_MASK =
1360            FLAG_PERMISSION_USER_SET
1361            | FLAG_PERMISSION_USER_FIXED
1362            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1363
1364    final @Nullable String mRequiredVerifierPackage;
1365    final @NonNull String mRequiredInstallerPackage;
1366    final @NonNull String mRequiredUninstallerPackage;
1367    final @Nullable String mSetupWizardPackage;
1368    final @Nullable String mStorageManagerPackage;
1369    final @NonNull String mServicesSystemSharedLibraryPackageName;
1370    final @NonNull String mSharedSystemSharedLibraryPackageName;
1371
1372    final boolean mPermissionReviewRequired;
1373
1374    private final PackageUsage mPackageUsage = new PackageUsage();
1375    private final CompilerStats mCompilerStats = new CompilerStats();
1376
1377    class PackageHandler extends Handler {
1378        private boolean mBound = false;
1379        final ArrayList<HandlerParams> mPendingInstalls =
1380            new ArrayList<HandlerParams>();
1381
1382        private boolean connectToService() {
1383            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1384                    " DefaultContainerService");
1385            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1386            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1387            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1388                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1389                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1390                mBound = true;
1391                return true;
1392            }
1393            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1394            return false;
1395        }
1396
1397        private void disconnectService() {
1398            mContainerService = null;
1399            mBound = false;
1400            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401            mContext.unbindService(mDefContainerConn);
1402            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1403        }
1404
1405        PackageHandler(Looper looper) {
1406            super(looper);
1407        }
1408
1409        public void handleMessage(Message msg) {
1410            try {
1411                doHandleMessage(msg);
1412            } finally {
1413                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414            }
1415        }
1416
1417        void doHandleMessage(Message msg) {
1418            switch (msg.what) {
1419                case INIT_COPY: {
1420                    HandlerParams params = (HandlerParams) msg.obj;
1421                    int idx = mPendingInstalls.size();
1422                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1423                    // If a bind was already initiated we dont really
1424                    // need to do anything. The pending install
1425                    // will be processed later on.
1426                    if (!mBound) {
1427                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1428                                System.identityHashCode(mHandler));
1429                        // If this is the only one pending we might
1430                        // have to bind to the service again.
1431                        if (!connectToService()) {
1432                            Slog.e(TAG, "Failed to bind to media container service");
1433                            params.serviceError();
1434                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1435                                    System.identityHashCode(mHandler));
1436                            if (params.traceMethod != null) {
1437                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1438                                        params.traceCookie);
1439                            }
1440                            return;
1441                        } else {
1442                            // Once we bind to the service, the first
1443                            // pending request will be processed.
1444                            mPendingInstalls.add(idx, params);
1445                        }
1446                    } else {
1447                        mPendingInstalls.add(idx, params);
1448                        // Already bound to the service. Just make
1449                        // sure we trigger off processing the first request.
1450                        if (idx == 0) {
1451                            mHandler.sendEmptyMessage(MCS_BOUND);
1452                        }
1453                    }
1454                    break;
1455                }
1456                case MCS_BOUND: {
1457                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1458                    if (msg.obj != null) {
1459                        mContainerService = (IMediaContainerService) msg.obj;
1460                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                System.identityHashCode(mHandler));
1462                    }
1463                    if (mContainerService == null) {
1464                        if (!mBound) {
1465                            // Something seriously wrong since we are not bound and we are not
1466                            // waiting for connection. Bail out.
1467                            Slog.e(TAG, "Cannot bind to media container service");
1468                            for (HandlerParams params : mPendingInstalls) {
1469                                // Indicate service bind error
1470                                params.serviceError();
1471                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1472                                        System.identityHashCode(params));
1473                                if (params.traceMethod != null) {
1474                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1475                                            params.traceMethod, params.traceCookie);
1476                                }
1477                                return;
1478                            }
1479                            mPendingInstalls.clear();
1480                        } else {
1481                            Slog.w(TAG, "Waiting to connect to media container service");
1482                        }
1483                    } else if (mPendingInstalls.size() > 0) {
1484                        HandlerParams params = mPendingInstalls.get(0);
1485                        if (params != null) {
1486                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1487                                    System.identityHashCode(params));
1488                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1489                            if (params.startCopy()) {
1490                                // We are done...  look for more work or to
1491                                // go idle.
1492                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1493                                        "Checking for more work or unbind...");
1494                                // Delete pending install
1495                                if (mPendingInstalls.size() > 0) {
1496                                    mPendingInstalls.remove(0);
1497                                }
1498                                if (mPendingInstalls.size() == 0) {
1499                                    if (mBound) {
1500                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1501                                                "Posting delayed MCS_UNBIND");
1502                                        removeMessages(MCS_UNBIND);
1503                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1504                                        // Unbind after a little delay, to avoid
1505                                        // continual thrashing.
1506                                        sendMessageDelayed(ubmsg, 10000);
1507                                    }
1508                                } else {
1509                                    // There are more pending requests in queue.
1510                                    // Just post MCS_BOUND message to trigger processing
1511                                    // of next pending install.
1512                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1513                                            "Posting MCS_BOUND for next work");
1514                                    mHandler.sendEmptyMessage(MCS_BOUND);
1515                                }
1516                            }
1517                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1518                        }
1519                    } else {
1520                        // Should never happen ideally.
1521                        Slog.w(TAG, "Empty queue");
1522                    }
1523                    break;
1524                }
1525                case MCS_RECONNECT: {
1526                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1527                    if (mPendingInstalls.size() > 0) {
1528                        if (mBound) {
1529                            disconnectService();
1530                        }
1531                        if (!connectToService()) {
1532                            Slog.e(TAG, "Failed to bind to media container service");
1533                            for (HandlerParams params : mPendingInstalls) {
1534                                // Indicate service bind error
1535                                params.serviceError();
1536                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1537                                        System.identityHashCode(params));
1538                            }
1539                            mPendingInstalls.clear();
1540                        }
1541                    }
1542                    break;
1543                }
1544                case MCS_UNBIND: {
1545                    // If there is no actual work left, then time to unbind.
1546                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1547
1548                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1549                        if (mBound) {
1550                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1551
1552                            disconnectService();
1553                        }
1554                    } else if (mPendingInstalls.size() > 0) {
1555                        // There are more pending requests in queue.
1556                        // Just post MCS_BOUND message to trigger processing
1557                        // of next pending install.
1558                        mHandler.sendEmptyMessage(MCS_BOUND);
1559                    }
1560
1561                    break;
1562                }
1563                case MCS_GIVE_UP: {
1564                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1565                    HandlerParams params = mPendingInstalls.remove(0);
1566                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1567                            System.identityHashCode(params));
1568                    break;
1569                }
1570                case SEND_PENDING_BROADCAST: {
1571                    String packages[];
1572                    ArrayList<String> components[];
1573                    int size = 0;
1574                    int uids[];
1575                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1576                    synchronized (mPackages) {
1577                        if (mPendingBroadcasts == null) {
1578                            return;
1579                        }
1580                        size = mPendingBroadcasts.size();
1581                        if (size <= 0) {
1582                            // Nothing to be done. Just return
1583                            return;
1584                        }
1585                        packages = new String[size];
1586                        components = new ArrayList[size];
1587                        uids = new int[size];
1588                        int i = 0;  // filling out the above arrays
1589
1590                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1591                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1592                            Iterator<Map.Entry<String, ArrayList<String>>> it
1593                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1594                                            .entrySet().iterator();
1595                            while (it.hasNext() && i < size) {
1596                                Map.Entry<String, ArrayList<String>> ent = it.next();
1597                                packages[i] = ent.getKey();
1598                                components[i] = ent.getValue();
1599                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1600                                uids[i] = (ps != null)
1601                                        ? UserHandle.getUid(packageUserId, ps.appId)
1602                                        : -1;
1603                                i++;
1604                            }
1605                        }
1606                        size = i;
1607                        mPendingBroadcasts.clear();
1608                    }
1609                    // Send broadcasts
1610                    for (int i = 0; i < size; i++) {
1611                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1612                    }
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1614                    break;
1615                }
1616                case START_CLEANING_PACKAGE: {
1617                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1618                    final String packageName = (String)msg.obj;
1619                    final int userId = msg.arg1;
1620                    final boolean andCode = msg.arg2 != 0;
1621                    synchronized (mPackages) {
1622                        if (userId == UserHandle.USER_ALL) {
1623                            int[] users = sUserManager.getUserIds();
1624                            for (int user : users) {
1625                                mSettings.addPackageToCleanLPw(
1626                                        new PackageCleanItem(user, packageName, andCode));
1627                            }
1628                        } else {
1629                            mSettings.addPackageToCleanLPw(
1630                                    new PackageCleanItem(userId, packageName, andCode));
1631                        }
1632                    }
1633                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1634                    startCleaningPackages();
1635                } break;
1636                case POST_INSTALL: {
1637                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1638
1639                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1640                    final boolean didRestore = (msg.arg2 != 0);
1641                    mRunningInstalls.delete(msg.arg1);
1642
1643                    if (data != null) {
1644                        InstallArgs args = data.args;
1645                        PackageInstalledInfo parentRes = data.res;
1646
1647                        final boolean grantPermissions = (args.installFlags
1648                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1649                        final boolean killApp = (args.installFlags
1650                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1651                        final String[] grantedPermissions = args.installGrantPermissions;
1652
1653                        // Handle the parent package
1654                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1655                                grantedPermissions, didRestore, args.installerPackageName,
1656                                args.observer);
1657
1658                        // Handle the child packages
1659                        final int childCount = (parentRes.addedChildPackages != null)
1660                                ? parentRes.addedChildPackages.size() : 0;
1661                        for (int i = 0; i < childCount; i++) {
1662                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1663                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1664                                    grantedPermissions, false, args.installerPackageName,
1665                                    args.observer);
1666                        }
1667
1668                        // Log tracing if needed
1669                        if (args.traceMethod != null) {
1670                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1671                                    args.traceCookie);
1672                        }
1673                    } else {
1674                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1675                    }
1676
1677                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1678                } break;
1679                case UPDATED_MEDIA_STATUS: {
1680                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1681                    boolean reportStatus = msg.arg1 == 1;
1682                    boolean doGc = msg.arg2 == 1;
1683                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1684                    if (doGc) {
1685                        // Force a gc to clear up stale containers.
1686                        Runtime.getRuntime().gc();
1687                    }
1688                    if (msg.obj != null) {
1689                        @SuppressWarnings("unchecked")
1690                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1691                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1692                        // Unload containers
1693                        unloadAllContainers(args);
1694                    }
1695                    if (reportStatus) {
1696                        try {
1697                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1698                                    "Invoking StorageManagerService call back");
1699                            PackageHelper.getStorageManager().finishMediaUpdate();
1700                        } catch (RemoteException e) {
1701                            Log.e(TAG, "StorageManagerService not running?");
1702                        }
1703                    }
1704                } break;
1705                case WRITE_SETTINGS: {
1706                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1707                    synchronized (mPackages) {
1708                        removeMessages(WRITE_SETTINGS);
1709                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1710                        mSettings.writeLPr();
1711                        mDirtyUsers.clear();
1712                    }
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1714                } break;
1715                case WRITE_PACKAGE_RESTRICTIONS: {
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1717                    synchronized (mPackages) {
1718                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1719                        for (int userId : mDirtyUsers) {
1720                            mSettings.writePackageRestrictionsLPr(userId);
1721                        }
1722                        mDirtyUsers.clear();
1723                    }
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1725                } break;
1726                case WRITE_PACKAGE_LIST: {
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1728                    synchronized (mPackages) {
1729                        removeMessages(WRITE_PACKAGE_LIST);
1730                        mSettings.writePackageListLPr(msg.arg1);
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case CHECK_PENDING_VERIFICATION: {
1735                    final int verificationId = msg.arg1;
1736                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1737
1738                    if ((state != null) && !state.timeoutExtended()) {
1739                        final InstallArgs args = state.getInstallArgs();
1740                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1741
1742                        Slog.i(TAG, "Verification timed out for " + originUri);
1743                        mPendingVerification.remove(verificationId);
1744
1745                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1746
1747                        final UserHandle user = args.getUser();
1748                        if (getDefaultVerificationResponse(user)
1749                                == PackageManager.VERIFICATION_ALLOW) {
1750                            Slog.i(TAG, "Continuing with installation of " + originUri);
1751                            state.setVerifierResponse(Binder.getCallingUid(),
1752                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1753                            broadcastPackageVerified(verificationId, originUri,
1754                                    PackageManager.VERIFICATION_ALLOW, user);
1755                            try {
1756                                ret = args.copyApk(mContainerService, true);
1757                            } catch (RemoteException e) {
1758                                Slog.e(TAG, "Could not contact the ContainerService");
1759                            }
1760                        } else {
1761                            broadcastPackageVerified(verificationId, originUri,
1762                                    PackageManager.VERIFICATION_REJECT, user);
1763                        }
1764
1765                        Trace.asyncTraceEnd(
1766                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1767
1768                        processPendingInstall(args, ret);
1769                        mHandler.sendEmptyMessage(MCS_UNBIND);
1770                    }
1771                    break;
1772                }
1773                case PACKAGE_VERIFIED: {
1774                    final int verificationId = msg.arg1;
1775
1776                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1777                    if (state == null) {
1778                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1779                        break;
1780                    }
1781
1782                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1783
1784                    state.setVerifierResponse(response.callerUid, response.code);
1785
1786                    if (state.isVerificationComplete()) {
1787                        mPendingVerification.remove(verificationId);
1788
1789                        final InstallArgs args = state.getInstallArgs();
1790                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1791
1792                        int ret;
1793                        if (state.isInstallAllowed()) {
1794                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1795                            broadcastPackageVerified(verificationId, originUri,
1796                                    response.code, state.getInstallArgs().getUser());
1797                            try {
1798                                ret = args.copyApk(mContainerService, true);
1799                            } catch (RemoteException e) {
1800                                Slog.e(TAG, "Could not contact the ContainerService");
1801                            }
1802                        } else {
1803                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1804                        }
1805
1806                        Trace.asyncTraceEnd(
1807                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1808
1809                        processPendingInstall(args, ret);
1810                        mHandler.sendEmptyMessage(MCS_UNBIND);
1811                    }
1812
1813                    break;
1814                }
1815                case START_INTENT_FILTER_VERIFICATIONS: {
1816                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1817                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1818                            params.replacing, params.pkg);
1819                    break;
1820                }
1821                case INTENT_FILTER_VERIFIED: {
1822                    final int verificationId = msg.arg1;
1823
1824                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1825                            verificationId);
1826                    if (state == null) {
1827                        Slog.w(TAG, "Invalid IntentFilter verification token "
1828                                + verificationId + " received");
1829                        break;
1830                    }
1831
1832                    final int userId = state.getUserId();
1833
1834                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1835                            "Processing IntentFilter verification with token:"
1836                            + verificationId + " and userId:" + userId);
1837
1838                    final IntentFilterVerificationResponse response =
1839                            (IntentFilterVerificationResponse) msg.obj;
1840
1841                    state.setVerifierResponse(response.callerUid, response.code);
1842
1843                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1844                            "IntentFilter verification with token:" + verificationId
1845                            + " and userId:" + userId
1846                            + " is settings verifier response with response code:"
1847                            + response.code);
1848
1849                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1850                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1851                                + response.getFailedDomainsString());
1852                    }
1853
1854                    if (state.isVerificationComplete()) {
1855                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1856                    } else {
1857                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                                "IntentFilter verification with token:" + verificationId
1859                                + " was not said to be complete");
1860                    }
1861
1862                    break;
1863                }
1864                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1865                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1866                            mInstantAppResolverConnection,
1867                            (InstantAppRequest) msg.obj,
1868                            mInstantAppInstallerActivity,
1869                            mHandler);
1870                }
1871            }
1872        }
1873    }
1874
1875    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1876            boolean killApp, String[] grantedPermissions,
1877            boolean launchedForRestore, String installerPackage,
1878            IPackageInstallObserver2 installObserver) {
1879        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1880            // Send the removed broadcasts
1881            if (res.removedInfo != null) {
1882                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1883            }
1884
1885            // Now that we successfully installed the package, grant runtime
1886            // permissions if requested before broadcasting the install. Also
1887            // for legacy apps in permission review mode we clear the permission
1888            // review flag which is used to emulate runtime permissions for
1889            // legacy apps.
1890            if (grantPermissions) {
1891                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1892            }
1893
1894            final boolean update = res.removedInfo != null
1895                    && res.removedInfo.removedPackage != null;
1896            final String origInstallerPackageName = res.removedInfo != null
1897                    ? res.removedInfo.installerPackageName : null;
1898
1899            // If this is the first time we have child packages for a disabled privileged
1900            // app that had no children, we grant requested runtime permissions to the new
1901            // children if the parent on the system image had them already granted.
1902            if (res.pkg.parentPackage != null) {
1903                synchronized (mPackages) {
1904                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1905                }
1906            }
1907
1908            synchronized (mPackages) {
1909                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1910            }
1911
1912            final String packageName = res.pkg.applicationInfo.packageName;
1913
1914            // Determine the set of users who are adding this package for
1915            // the first time vs. those who are seeing an update.
1916            int[] firstUsers = EMPTY_INT_ARRAY;
1917            int[] updateUsers = EMPTY_INT_ARRAY;
1918            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1919            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1920            for (int newUser : res.newUsers) {
1921                if (ps.getInstantApp(newUser)) {
1922                    continue;
1923                }
1924                if (allNewUsers) {
1925                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1926                    continue;
1927                }
1928                boolean isNew = true;
1929                for (int origUser : res.origUsers) {
1930                    if (origUser == newUser) {
1931                        isNew = false;
1932                        break;
1933                    }
1934                }
1935                if (isNew) {
1936                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1937                } else {
1938                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1939                }
1940            }
1941
1942            // Send installed broadcasts if the package is not a static shared lib.
1943            if (res.pkg.staticSharedLibName == null) {
1944                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1945
1946                // Send added for users that see the package for the first time
1947                // sendPackageAddedForNewUsers also deals with system apps
1948                int appId = UserHandle.getAppId(res.uid);
1949                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1950                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1951
1952                // Send added for users that don't see the package for the first time
1953                Bundle extras = new Bundle(1);
1954                extras.putInt(Intent.EXTRA_UID, res.uid);
1955                if (update) {
1956                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1957                }
1958                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1959                        extras, 0 /*flags*/,
1960                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1961                if (origInstallerPackageName != null) {
1962                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1963                            extras, 0 /*flags*/,
1964                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1965                }
1966
1967                // Send replaced for users that don't see the package for the first time
1968                if (update) {
1969                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1970                            packageName, extras, 0 /*flags*/,
1971                            null /*targetPackage*/, null /*finishedReceiver*/,
1972                            updateUsers);
1973                    if (origInstallerPackageName != null) {
1974                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1975                                extras, 0 /*flags*/,
1976                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1977                    }
1978                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1979                            null /*package*/, null /*extras*/, 0 /*flags*/,
1980                            packageName /*targetPackage*/,
1981                            null /*finishedReceiver*/, updateUsers);
1982                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1983                    // First-install and we did a restore, so we're responsible for the
1984                    // first-launch broadcast.
1985                    if (DEBUG_BACKUP) {
1986                        Slog.i(TAG, "Post-restore of " + packageName
1987                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1988                    }
1989                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1990                }
1991
1992                // Send broadcast package appeared if forward locked/external for all users
1993                // treat asec-hosted packages like removable media on upgrade
1994                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1995                    if (DEBUG_INSTALL) {
1996                        Slog.i(TAG, "upgrading pkg " + res.pkg
1997                                + " is ASEC-hosted -> AVAILABLE");
1998                    }
1999                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2000                    ArrayList<String> pkgList = new ArrayList<>(1);
2001                    pkgList.add(packageName);
2002                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2003                }
2004            }
2005
2006            // Work that needs to happen on first install within each user
2007            if (firstUsers != null && firstUsers.length > 0) {
2008                synchronized (mPackages) {
2009                    for (int userId : firstUsers) {
2010                        // If this app is a browser and it's newly-installed for some
2011                        // users, clear any default-browser state in those users. The
2012                        // app's nature doesn't depend on the user, so we can just check
2013                        // its browser nature in any user and generalize.
2014                        if (packageIsBrowser(packageName, userId)) {
2015                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2016                        }
2017
2018                        // We may also need to apply pending (restored) runtime
2019                        // permission grants within these users.
2020                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2021                    }
2022                }
2023            }
2024
2025            // Log current value of "unknown sources" setting
2026            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2027                    getUnknownSourcesSettings());
2028
2029            // Remove the replaced package's older resources safely now
2030            // We delete after a gc for applications  on sdcard.
2031            if (res.removedInfo != null && res.removedInfo.args != null) {
2032                Runtime.getRuntime().gc();
2033                synchronized (mInstallLock) {
2034                    res.removedInfo.args.doPostDeleteLI(true);
2035                }
2036            } else {
2037                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2038                // and not block here.
2039                VMRuntime.getRuntime().requestConcurrentGC();
2040            }
2041
2042            // Notify DexManager that the package was installed for new users.
2043            // The updated users should already be indexed and the package code paths
2044            // should not change.
2045            // Don't notify the manager for ephemeral apps as they are not expected to
2046            // survive long enough to benefit of background optimizations.
2047            for (int userId : firstUsers) {
2048                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2049                // There's a race currently where some install events may interleave with an uninstall.
2050                // This can lead to package info being null (b/36642664).
2051                if (info != null) {
2052                    mDexManager.notifyPackageInstalled(info, userId);
2053                }
2054            }
2055        }
2056
2057        // If someone is watching installs - notify them
2058        if (installObserver != null) {
2059            try {
2060                Bundle extras = extrasForInstallResult(res);
2061                installObserver.onPackageInstalled(res.name, res.returnCode,
2062                        res.returnMsg, extras);
2063            } catch (RemoteException e) {
2064                Slog.i(TAG, "Observer no longer exists.");
2065            }
2066        }
2067    }
2068
2069    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2070            PackageParser.Package pkg) {
2071        if (pkg.parentPackage == null) {
2072            return;
2073        }
2074        if (pkg.requestedPermissions == null) {
2075            return;
2076        }
2077        final PackageSetting disabledSysParentPs = mSettings
2078                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2079        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2080                || !disabledSysParentPs.isPrivileged()
2081                || (disabledSysParentPs.childPackageNames != null
2082                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2083            return;
2084        }
2085        final int[] allUserIds = sUserManager.getUserIds();
2086        final int permCount = pkg.requestedPermissions.size();
2087        for (int i = 0; i < permCount; i++) {
2088            String permission = pkg.requestedPermissions.get(i);
2089            BasePermission bp = mSettings.mPermissions.get(permission);
2090            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2091                continue;
2092            }
2093            for (int userId : allUserIds) {
2094                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2095                        permission, userId)) {
2096                    grantRuntimePermission(pkg.packageName, permission, userId);
2097                }
2098            }
2099        }
2100    }
2101
2102    private StorageEventListener mStorageListener = new StorageEventListener() {
2103        @Override
2104        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2105            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2106                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2107                    final String volumeUuid = vol.getFsUuid();
2108
2109                    // Clean up any users or apps that were removed or recreated
2110                    // while this volume was missing
2111                    sUserManager.reconcileUsers(volumeUuid);
2112                    reconcileApps(volumeUuid);
2113
2114                    // Clean up any install sessions that expired or were
2115                    // cancelled while this volume was missing
2116                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2117
2118                    loadPrivatePackages(vol);
2119
2120                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2121                    unloadPrivatePackages(vol);
2122                }
2123            }
2124
2125            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2126                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2127                    updateExternalMediaStatus(true, false);
2128                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2129                    updateExternalMediaStatus(false, false);
2130                }
2131            }
2132        }
2133
2134        @Override
2135        public void onVolumeForgotten(String fsUuid) {
2136            if (TextUtils.isEmpty(fsUuid)) {
2137                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2138                return;
2139            }
2140
2141            // Remove any apps installed on the forgotten volume
2142            synchronized (mPackages) {
2143                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2144                for (PackageSetting ps : packages) {
2145                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2146                    deletePackageVersioned(new VersionedPackage(ps.name,
2147                            PackageManager.VERSION_CODE_HIGHEST),
2148                            new LegacyPackageDeleteObserver(null).getBinder(),
2149                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2150                    // Try very hard to release any references to this package
2151                    // so we don't risk the system server being killed due to
2152                    // open FDs
2153                    AttributeCache.instance().removePackage(ps.name);
2154                }
2155
2156                mSettings.onVolumeForgotten(fsUuid);
2157                mSettings.writeLPr();
2158            }
2159        }
2160    };
2161
2162    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2163            String[] grantedPermissions) {
2164        for (int userId : userIds) {
2165            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2166        }
2167    }
2168
2169    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2170            String[] grantedPermissions) {
2171        SettingBase sb = (SettingBase) pkg.mExtras;
2172        if (sb == null) {
2173            return;
2174        }
2175
2176        PermissionsState permissionsState = sb.getPermissionsState();
2177
2178        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2179                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2180
2181        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2182                >= Build.VERSION_CODES.M;
2183
2184        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2185
2186        for (String permission : pkg.requestedPermissions) {
2187            final BasePermission bp;
2188            synchronized (mPackages) {
2189                bp = mSettings.mPermissions.get(permission);
2190            }
2191            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2192                    && (!instantApp || bp.isInstant())
2193                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2194                    && (grantedPermissions == null
2195                           || ArrayUtils.contains(grantedPermissions, permission))) {
2196                final int flags = permissionsState.getPermissionFlags(permission, userId);
2197                if (supportsRuntimePermissions) {
2198                    // Installer cannot change immutable permissions.
2199                    if ((flags & immutableFlags) == 0) {
2200                        grantRuntimePermission(pkg.packageName, permission, userId);
2201                    }
2202                } else if (mPermissionReviewRequired) {
2203                    // In permission review mode we clear the review flag when we
2204                    // are asked to install the app with all permissions granted.
2205                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2206                        updatePermissionFlags(permission, pkg.packageName,
2207                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2208                    }
2209                }
2210            }
2211        }
2212    }
2213
2214    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2215        Bundle extras = null;
2216        switch (res.returnCode) {
2217            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2218                extras = new Bundle();
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2220                        res.origPermission);
2221                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2222                        res.origPackage);
2223                break;
2224            }
2225            case PackageManager.INSTALL_SUCCEEDED: {
2226                extras = new Bundle();
2227                extras.putBoolean(Intent.EXTRA_REPLACING,
2228                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2229                break;
2230            }
2231        }
2232        return extras;
2233    }
2234
2235    void scheduleWriteSettingsLocked() {
2236        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2237            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2238        }
2239    }
2240
2241    void scheduleWritePackageListLocked(int userId) {
2242        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2243            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2244            msg.arg1 = userId;
2245            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2246        }
2247    }
2248
2249    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2250        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2251        scheduleWritePackageRestrictionsLocked(userId);
2252    }
2253
2254    void scheduleWritePackageRestrictionsLocked(int userId) {
2255        final int[] userIds = (userId == UserHandle.USER_ALL)
2256                ? sUserManager.getUserIds() : new int[]{userId};
2257        for (int nextUserId : userIds) {
2258            if (!sUserManager.exists(nextUserId)) return;
2259            mDirtyUsers.add(nextUserId);
2260            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2261                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2262            }
2263        }
2264    }
2265
2266    public static PackageManagerService main(Context context, Installer installer,
2267            boolean factoryTest, boolean onlyCore) {
2268        // Self-check for initial settings.
2269        PackageManagerServiceCompilerMapping.checkProperties();
2270
2271        PackageManagerService m = new PackageManagerService(context, installer,
2272                factoryTest, onlyCore);
2273        m.enableSystemUserPackages();
2274        ServiceManager.addService("package", m);
2275        return m;
2276    }
2277
2278    private void enableSystemUserPackages() {
2279        if (!UserManager.isSplitSystemUser()) {
2280            return;
2281        }
2282        // For system user, enable apps based on the following conditions:
2283        // - app is whitelisted or belong to one of these groups:
2284        //   -- system app which has no launcher icons
2285        //   -- system app which has INTERACT_ACROSS_USERS permission
2286        //   -- system IME app
2287        // - app is not in the blacklist
2288        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2289        Set<String> enableApps = new ArraySet<>();
2290        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2291                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2292                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2293        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2294        enableApps.addAll(wlApps);
2295        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2296                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2297        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2298        enableApps.removeAll(blApps);
2299        Log.i(TAG, "Applications installed for system user: " + enableApps);
2300        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2301                UserHandle.SYSTEM);
2302        final int allAppsSize = allAps.size();
2303        synchronized (mPackages) {
2304            for (int i = 0; i < allAppsSize; i++) {
2305                String pName = allAps.get(i);
2306                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2307                // Should not happen, but we shouldn't be failing if it does
2308                if (pkgSetting == null) {
2309                    continue;
2310                }
2311                boolean install = enableApps.contains(pName);
2312                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2313                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2314                            + " for system user");
2315                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2316                }
2317            }
2318            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2319        }
2320    }
2321
2322    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2323        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2324                Context.DISPLAY_SERVICE);
2325        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2326    }
2327
2328    /**
2329     * Requests that files preopted on a secondary system partition be copied to the data partition
2330     * if possible.  Note that the actual copying of the files is accomplished by init for security
2331     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2332     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2333     */
2334    private static void requestCopyPreoptedFiles() {
2335        final int WAIT_TIME_MS = 100;
2336        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2337        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2338            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2339            // We will wait for up to 100 seconds.
2340            final long timeStart = SystemClock.uptimeMillis();
2341            final long timeEnd = timeStart + 100 * 1000;
2342            long timeNow = timeStart;
2343            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2344                try {
2345                    Thread.sleep(WAIT_TIME_MS);
2346                } catch (InterruptedException e) {
2347                    // Do nothing
2348                }
2349                timeNow = SystemClock.uptimeMillis();
2350                if (timeNow > timeEnd) {
2351                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2352                    Slog.wtf(TAG, "cppreopt did not finish!");
2353                    break;
2354                }
2355            }
2356
2357            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2358        }
2359    }
2360
2361    public PackageManagerService(Context context, Installer installer,
2362            boolean factoryTest, boolean onlyCore) {
2363        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2365        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2366                SystemClock.uptimeMillis());
2367
2368        if (mSdkVersion <= 0) {
2369            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2370        }
2371
2372        mContext = context;
2373
2374        mPermissionReviewRequired = context.getResources().getBoolean(
2375                R.bool.config_permissionReviewRequired);
2376
2377        mFactoryTest = factoryTest;
2378        mOnlyCore = onlyCore;
2379        mMetrics = new DisplayMetrics();
2380        mSettings = new Settings(mPackages);
2381        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2382                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2383        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2384                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2385        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2386                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2387        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2388                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2389        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2390                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2391        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2392                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2393
2394        String separateProcesses = SystemProperties.get("debug.separate_processes");
2395        if (separateProcesses != null && separateProcesses.length() > 0) {
2396            if ("*".equals(separateProcesses)) {
2397                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2398                mSeparateProcesses = null;
2399                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2400            } else {
2401                mDefParseFlags = 0;
2402                mSeparateProcesses = separateProcesses.split(",");
2403                Slog.w(TAG, "Running with debug.separate_processes: "
2404                        + separateProcesses);
2405            }
2406        } else {
2407            mDefParseFlags = 0;
2408            mSeparateProcesses = null;
2409        }
2410
2411        mInstaller = installer;
2412        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2413                "*dexopt*");
2414        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2415        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2416
2417        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2418                FgThread.get().getLooper());
2419
2420        getDefaultDisplayMetrics(context, mMetrics);
2421
2422        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2423        SystemConfig systemConfig = SystemConfig.getInstance();
2424        mGlobalGids = systemConfig.getGlobalGids();
2425        mSystemPermissions = systemConfig.getSystemPermissions();
2426        mAvailableFeatures = systemConfig.getAvailableFeatures();
2427        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2428
2429        mProtectedPackages = new ProtectedPackages(mContext);
2430
2431        synchronized (mInstallLock) {
2432        // writer
2433        synchronized (mPackages) {
2434            mHandlerThread = new ServiceThread(TAG,
2435                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2436            mHandlerThread.start();
2437            mHandler = new PackageHandler(mHandlerThread.getLooper());
2438            mProcessLoggingHandler = new ProcessLoggingHandler();
2439            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2440
2441            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2442            mInstantAppRegistry = new InstantAppRegistry(this);
2443
2444            File dataDir = Environment.getDataDirectory();
2445            mAppInstallDir = new File(dataDir, "app");
2446            mAppLib32InstallDir = new File(dataDir, "app-lib");
2447            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2448            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2449            sUserManager = new UserManagerService(context, this,
2450                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2451
2452            // Propagate permission configuration in to package manager.
2453            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2454                    = systemConfig.getPermissions();
2455            for (int i=0; i<permConfig.size(); i++) {
2456                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2457                BasePermission bp = mSettings.mPermissions.get(perm.name);
2458                if (bp == null) {
2459                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2460                    mSettings.mPermissions.put(perm.name, bp);
2461                }
2462                if (perm.gids != null) {
2463                    bp.setGids(perm.gids, perm.perUser);
2464                }
2465            }
2466
2467            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2468            final int builtInLibCount = libConfig.size();
2469            for (int i = 0; i < builtInLibCount; i++) {
2470                String name = libConfig.keyAt(i);
2471                String path = libConfig.valueAt(i);
2472                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2473                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2474            }
2475
2476            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2477
2478            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2479            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2480            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2481
2482            // Clean up orphaned packages for which the code path doesn't exist
2483            // and they are an update to a system app - caused by bug/32321269
2484            final int packageSettingCount = mSettings.mPackages.size();
2485            for (int i = packageSettingCount - 1; i >= 0; i--) {
2486                PackageSetting ps = mSettings.mPackages.valueAt(i);
2487                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2488                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2489                    mSettings.mPackages.removeAt(i);
2490                    mSettings.enableSystemPackageLPw(ps.name);
2491                }
2492            }
2493
2494            if (mFirstBoot) {
2495                requestCopyPreoptedFiles();
2496            }
2497
2498            String customResolverActivity = Resources.getSystem().getString(
2499                    R.string.config_customResolverActivity);
2500            if (TextUtils.isEmpty(customResolverActivity)) {
2501                customResolverActivity = null;
2502            } else {
2503                mCustomResolverComponentName = ComponentName.unflattenFromString(
2504                        customResolverActivity);
2505            }
2506
2507            long startTime = SystemClock.uptimeMillis();
2508
2509            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2510                    startTime);
2511
2512            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2513            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2514
2515            if (bootClassPath == null) {
2516                Slog.w(TAG, "No BOOTCLASSPATH found!");
2517            }
2518
2519            if (systemServerClassPath == null) {
2520                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2521            }
2522
2523            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2524
2525            final VersionInfo ver = mSettings.getInternalVersion();
2526            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2527            if (mIsUpgrade) {
2528                logCriticalInfo(Log.INFO,
2529                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2530            }
2531
2532            // when upgrading from pre-M, promote system app permissions from install to runtime
2533            mPromoteSystemApps =
2534                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2535
2536            // When upgrading from pre-N, we need to handle package extraction like first boot,
2537            // as there is no profiling data available.
2538            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2539
2540            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2541
2542            // save off the names of pre-existing system packages prior to scanning; we don't
2543            // want to automatically grant runtime permissions for new system apps
2544            if (mPromoteSystemApps) {
2545                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2546                while (pkgSettingIter.hasNext()) {
2547                    PackageSetting ps = pkgSettingIter.next();
2548                    if (isSystemApp(ps)) {
2549                        mExistingSystemPackages.add(ps.name);
2550                    }
2551                }
2552            }
2553
2554            mCacheDir = preparePackageParserCache(mIsUpgrade);
2555
2556            // Set flag to monitor and not change apk file paths when
2557            // scanning install directories.
2558            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2559
2560            if (mIsUpgrade || mFirstBoot) {
2561                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2562            }
2563
2564            // Collect vendor overlay packages. (Do this before scanning any apps.)
2565            // For security and version matching reason, only consider
2566            // overlay packages if they reside in the right directory.
2567            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2568                    | PackageParser.PARSE_IS_SYSTEM
2569                    | PackageParser.PARSE_IS_SYSTEM_DIR
2570                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2571
2572            mParallelPackageParserCallback.findStaticOverlayPackages();
2573
2574            // Find base frameworks (resource packages without code).
2575            scanDirTracedLI(frameworkDir, mDefParseFlags
2576                    | PackageParser.PARSE_IS_SYSTEM
2577                    | PackageParser.PARSE_IS_SYSTEM_DIR
2578                    | PackageParser.PARSE_IS_PRIVILEGED,
2579                    scanFlags | SCAN_NO_DEX, 0);
2580
2581            // Collected privileged system packages.
2582            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2583            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM
2585                    | PackageParser.PARSE_IS_SYSTEM_DIR
2586                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2587
2588            // Collect ordinary system packages.
2589            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2590            scanDirTracedLI(systemAppDir, mDefParseFlags
2591                    | PackageParser.PARSE_IS_SYSTEM
2592                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2593
2594            // Collect all vendor packages.
2595            File vendorAppDir = new File("/vendor/app");
2596            try {
2597                vendorAppDir = vendorAppDir.getCanonicalFile();
2598            } catch (IOException e) {
2599                // failed to look up canonical path, continue with original one
2600            }
2601            scanDirTracedLI(vendorAppDir, mDefParseFlags
2602                    | PackageParser.PARSE_IS_SYSTEM
2603                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2604
2605            // Collect all OEM packages.
2606            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2607            scanDirTracedLI(oemAppDir, mDefParseFlags
2608                    | PackageParser.PARSE_IS_SYSTEM
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2610
2611            // Prune any system packages that no longer exist.
2612            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2613            if (!mOnlyCore) {
2614                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2615                while (psit.hasNext()) {
2616                    PackageSetting ps = psit.next();
2617
2618                    /*
2619                     * If this is not a system app, it can't be a
2620                     * disable system app.
2621                     */
2622                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2623                        continue;
2624                    }
2625
2626                    /*
2627                     * If the package is scanned, it's not erased.
2628                     */
2629                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2630                    if (scannedPkg != null) {
2631                        /*
2632                         * If the system app is both scanned and in the
2633                         * disabled packages list, then it must have been
2634                         * added via OTA. Remove it from the currently
2635                         * scanned package so the previously user-installed
2636                         * application can be scanned.
2637                         */
2638                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2639                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2640                                    + ps.name + "; removing system app.  Last known codePath="
2641                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2642                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2643                                    + scannedPkg.mVersionCode);
2644                            removePackageLI(scannedPkg, true);
2645                            mExpectingBetter.put(ps.name, ps.codePath);
2646                        }
2647
2648                        continue;
2649                    }
2650
2651                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2652                        psit.remove();
2653                        logCriticalInfo(Log.WARN, "System package " + ps.name
2654                                + " no longer exists; it's data will be wiped");
2655                        // Actual deletion of code and data will be handled by later
2656                        // reconciliation step
2657                    } else {
2658                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2659                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2660                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2661                        }
2662                    }
2663                }
2664            }
2665
2666            //look for any incomplete package installations
2667            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2668            for (int i = 0; i < deletePkgsList.size(); i++) {
2669                // Actual deletion of code and data will be handled by later
2670                // reconciliation step
2671                final String packageName = deletePkgsList.get(i).name;
2672                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2673                synchronized (mPackages) {
2674                    mSettings.removePackageLPw(packageName);
2675                }
2676            }
2677
2678            //delete tmp files
2679            deleteTempPackageFiles();
2680
2681            // Remove any shared userIDs that have no associated packages
2682            mSettings.pruneSharedUsersLPw();
2683
2684            if (!mOnlyCore) {
2685                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2686                        SystemClock.uptimeMillis());
2687                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2688
2689                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2690                        | PackageParser.PARSE_FORWARD_LOCK,
2691                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2692
2693                /**
2694                 * Remove disable package settings for any updated system
2695                 * apps that were removed via an OTA. If they're not a
2696                 * previously-updated app, remove them completely.
2697                 * Otherwise, just revoke their system-level permissions.
2698                 */
2699                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2700                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2701                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2702
2703                    String msg;
2704                    if (deletedPkg == null) {
2705                        msg = "Updated system package " + deletedAppName
2706                                + " no longer exists; it's data will be wiped";
2707                        // Actual deletion of code and data will be handled by later
2708                        // reconciliation step
2709                    } else {
2710                        msg = "Updated system app + " + deletedAppName
2711                                + " no longer present; removing system privileges for "
2712                                + deletedAppName;
2713
2714                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2715
2716                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2717                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2718                    }
2719                    logCriticalInfo(Log.WARN, msg);
2720                }
2721
2722                /**
2723                 * Make sure all system apps that we expected to appear on
2724                 * the userdata partition actually showed up. If they never
2725                 * appeared, crawl back and revive the system version.
2726                 */
2727                for (int i = 0; i < mExpectingBetter.size(); i++) {
2728                    final String packageName = mExpectingBetter.keyAt(i);
2729                    if (!mPackages.containsKey(packageName)) {
2730                        final File scanFile = mExpectingBetter.valueAt(i);
2731
2732                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2733                                + " but never showed up; reverting to system");
2734
2735                        int reparseFlags = mDefParseFlags;
2736                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2737                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2738                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2739                                    | PackageParser.PARSE_IS_PRIVILEGED;
2740                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2741                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2742                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2743                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2744                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2745                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2746                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2747                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2748                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2749                        } else {
2750                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2751                            continue;
2752                        }
2753
2754                        mSettings.enableSystemPackageLPw(packageName);
2755
2756                        try {
2757                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2758                        } catch (PackageManagerException e) {
2759                            Slog.e(TAG, "Failed to parse original system package: "
2760                                    + e.getMessage());
2761                        }
2762                    }
2763                }
2764            }
2765            mExpectingBetter.clear();
2766
2767            // Resolve the storage manager.
2768            mStorageManagerPackage = getStorageManagerPackageName();
2769
2770            // Resolve protected action filters. Only the setup wizard is allowed to
2771            // have a high priority filter for these actions.
2772            mSetupWizardPackage = getSetupWizardPackageName();
2773            if (mProtectedFilters.size() > 0) {
2774                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2775                    Slog.i(TAG, "No setup wizard;"
2776                        + " All protected intents capped to priority 0");
2777                }
2778                for (ActivityIntentInfo filter : mProtectedFilters) {
2779                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2780                        if (DEBUG_FILTERS) {
2781                            Slog.i(TAG, "Found setup wizard;"
2782                                + " allow priority " + filter.getPriority() + ";"
2783                                + " package: " + filter.activity.info.packageName
2784                                + " activity: " + filter.activity.className
2785                                + " priority: " + filter.getPriority());
2786                        }
2787                        // skip setup wizard; allow it to keep the high priority filter
2788                        continue;
2789                    }
2790                    if (DEBUG_FILTERS) {
2791                        Slog.i(TAG, "Protected action; cap priority to 0;"
2792                                + " package: " + filter.activity.info.packageName
2793                                + " activity: " + filter.activity.className
2794                                + " origPrio: " + filter.getPriority());
2795                    }
2796                    filter.setPriority(0);
2797                }
2798            }
2799            mDeferProtectedFilters = false;
2800            mProtectedFilters.clear();
2801
2802            // Now that we know all of the shared libraries, update all clients to have
2803            // the correct library paths.
2804            updateAllSharedLibrariesLPw(null);
2805
2806            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2807                // NOTE: We ignore potential failures here during a system scan (like
2808                // the rest of the commands above) because there's precious little we
2809                // can do about it. A settings error is reported, though.
2810                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2811            }
2812
2813            // Now that we know all the packages we are keeping,
2814            // read and update their last usage times.
2815            mPackageUsage.read(mPackages);
2816            mCompilerStats.read();
2817
2818            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2819                    SystemClock.uptimeMillis());
2820            Slog.i(TAG, "Time to scan packages: "
2821                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2822                    + " seconds");
2823
2824            // If the platform SDK has changed since the last time we booted,
2825            // we need to re-grant app permission to catch any new ones that
2826            // appear.  This is really a hack, and means that apps can in some
2827            // cases get permissions that the user didn't initially explicitly
2828            // allow...  it would be nice to have some better way to handle
2829            // this situation.
2830            int updateFlags = UPDATE_PERMISSIONS_ALL;
2831            if (ver.sdkVersion != mSdkVersion) {
2832                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2833                        + mSdkVersion + "; regranting permissions for internal storage");
2834                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2835            }
2836            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2837            ver.sdkVersion = mSdkVersion;
2838
2839            // If this is the first boot or an update from pre-M, and it is a normal
2840            // boot, then we need to initialize the default preferred apps across
2841            // all defined users.
2842            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2843                for (UserInfo user : sUserManager.getUsers(true)) {
2844                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2845                    applyFactoryDefaultBrowserLPw(user.id);
2846                    primeDomainVerificationsLPw(user.id);
2847                }
2848            }
2849
2850            // Prepare storage for system user really early during boot,
2851            // since core system apps like SettingsProvider and SystemUI
2852            // can't wait for user to start
2853            final int storageFlags;
2854            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2855                storageFlags = StorageManager.FLAG_STORAGE_DE;
2856            } else {
2857                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2858            }
2859            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2860                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2861                    true /* onlyCoreApps */);
2862            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2863                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2864                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2865                traceLog.traceBegin("AppDataFixup");
2866                try {
2867                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2868                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2869                } catch (InstallerException e) {
2870                    Slog.w(TAG, "Trouble fixing GIDs", e);
2871                }
2872                traceLog.traceEnd();
2873
2874                traceLog.traceBegin("AppDataPrepare");
2875                if (deferPackages == null || deferPackages.isEmpty()) {
2876                    return;
2877                }
2878                int count = 0;
2879                for (String pkgName : deferPackages) {
2880                    PackageParser.Package pkg = null;
2881                    synchronized (mPackages) {
2882                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2883                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2884                            pkg = ps.pkg;
2885                        }
2886                    }
2887                    if (pkg != null) {
2888                        synchronized (mInstallLock) {
2889                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2890                                    true /* maybeMigrateAppData */);
2891                        }
2892                        count++;
2893                    }
2894                }
2895                traceLog.traceEnd();
2896                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2897            }, "prepareAppData");
2898
2899            // If this is first boot after an OTA, and a normal boot, then
2900            // we need to clear code cache directories.
2901            // Note that we do *not* clear the application profiles. These remain valid
2902            // across OTAs and are used to drive profile verification (post OTA) and
2903            // profile compilation (without waiting to collect a fresh set of profiles).
2904            if (mIsUpgrade && !onlyCore) {
2905                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2906                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2907                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2908                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2909                        // No apps are running this early, so no need to freeze
2910                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2911                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2912                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2913                    }
2914                }
2915                ver.fingerprint = Build.FINGERPRINT;
2916            }
2917
2918            checkDefaultBrowser();
2919
2920            // clear only after permissions and other defaults have been updated
2921            mExistingSystemPackages.clear();
2922            mPromoteSystemApps = false;
2923
2924            // All the changes are done during package scanning.
2925            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2926
2927            // can downgrade to reader
2928            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2929            mSettings.writeLPr();
2930            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2931
2932            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2933                    SystemClock.uptimeMillis());
2934
2935            if (!mOnlyCore) {
2936                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2937                mRequiredInstallerPackage = getRequiredInstallerLPr();
2938                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2939                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2940                if (mIntentFilterVerifierComponent != null) {
2941                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2942                            mIntentFilterVerifierComponent);
2943                } else {
2944                    mIntentFilterVerifier = null;
2945                }
2946                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2947                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2948                        SharedLibraryInfo.VERSION_UNDEFINED);
2949                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2950                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2951                        SharedLibraryInfo.VERSION_UNDEFINED);
2952            } else {
2953                mRequiredVerifierPackage = null;
2954                mRequiredInstallerPackage = null;
2955                mRequiredUninstallerPackage = null;
2956                mIntentFilterVerifierComponent = null;
2957                mIntentFilterVerifier = null;
2958                mServicesSystemSharedLibraryPackageName = null;
2959                mSharedSystemSharedLibraryPackageName = null;
2960            }
2961
2962            mInstallerService = new PackageInstallerService(context, this);
2963            final Pair<ComponentName, String> instantAppResolverComponent =
2964                    getInstantAppResolverLPr();
2965            if (instantAppResolverComponent != null) {
2966                if (DEBUG_EPHEMERAL) {
2967                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2968                }
2969                mInstantAppResolverConnection = new EphemeralResolverConnection(
2970                        mContext, instantAppResolverComponent.first,
2971                        instantAppResolverComponent.second);
2972                mInstantAppResolverSettingsComponent =
2973                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2974            } else {
2975                mInstantAppResolverConnection = null;
2976                mInstantAppResolverSettingsComponent = null;
2977            }
2978            updateInstantAppInstallerLocked(null);
2979
2980            // Read and update the usage of dex files.
2981            // Do this at the end of PM init so that all the packages have their
2982            // data directory reconciled.
2983            // At this point we know the code paths of the packages, so we can validate
2984            // the disk file and build the internal cache.
2985            // The usage file is expected to be small so loading and verifying it
2986            // should take a fairly small time compare to the other activities (e.g. package
2987            // scanning).
2988            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2989            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2990            for (int userId : currentUserIds) {
2991                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2992            }
2993            mDexManager.load(userPackages);
2994        } // synchronized (mPackages)
2995        } // synchronized (mInstallLock)
2996
2997        // Now after opening every single application zip, make sure they
2998        // are all flushed.  Not really needed, but keeps things nice and
2999        // tidy.
3000        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3001        Runtime.getRuntime().gc();
3002        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3003
3004        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3005        FallbackCategoryProvider.loadFallbacks();
3006        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3007
3008        // The initial scanning above does many calls into installd while
3009        // holding the mPackages lock, but we're mostly interested in yelling
3010        // once we have a booted system.
3011        mInstaller.setWarnIfHeld(mPackages);
3012
3013        // Expose private service for system components to use.
3014        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3015        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3016    }
3017
3018    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3019        // we're only interested in updating the installer appliction when 1) it's not
3020        // already set or 2) the modified package is the installer
3021        if (mInstantAppInstallerActivity != null
3022                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3023                        .equals(modifiedPackage)) {
3024            return;
3025        }
3026        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3027    }
3028
3029    private static File preparePackageParserCache(boolean isUpgrade) {
3030        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3031            return null;
3032        }
3033
3034        // Disable package parsing on eng builds to allow for faster incremental development.
3035        if ("eng".equals(Build.TYPE)) {
3036            return null;
3037        }
3038
3039        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3040            Slog.i(TAG, "Disabling package parser cache due to system property.");
3041            return null;
3042        }
3043
3044        // The base directory for the package parser cache lives under /data/system/.
3045        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3046                "package_cache");
3047        if (cacheBaseDir == null) {
3048            return null;
3049        }
3050
3051        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3052        // This also serves to "GC" unused entries when the package cache version changes (which
3053        // can only happen during upgrades).
3054        if (isUpgrade) {
3055            FileUtils.deleteContents(cacheBaseDir);
3056        }
3057
3058
3059        // Return the versioned package cache directory. This is something like
3060        // "/data/system/package_cache/1"
3061        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3062
3063        // The following is a workaround to aid development on non-numbered userdebug
3064        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3065        // the system partition is newer.
3066        //
3067        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3068        // that starts with "eng." to signify that this is an engineering build and not
3069        // destined for release.
3070        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3071            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3072
3073            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3074            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3075            // in general and should not be used for production changes. In this specific case,
3076            // we know that they will work.
3077            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3078            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3079                FileUtils.deleteContents(cacheBaseDir);
3080                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3081            }
3082        }
3083
3084        return cacheDir;
3085    }
3086
3087    @Override
3088    public boolean isFirstBoot() {
3089        return mFirstBoot;
3090    }
3091
3092    @Override
3093    public boolean isOnlyCoreApps() {
3094        return mOnlyCore;
3095    }
3096
3097    @Override
3098    public boolean isUpgrade() {
3099        return mIsUpgrade;
3100    }
3101
3102    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3103        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3104
3105        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3106                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3107                UserHandle.USER_SYSTEM);
3108        if (matches.size() == 1) {
3109            return matches.get(0).getComponentInfo().packageName;
3110        } else if (matches.size() == 0) {
3111            Log.e(TAG, "There should probably be a verifier, but, none were found");
3112            return null;
3113        }
3114        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3115    }
3116
3117    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3118        synchronized (mPackages) {
3119            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3120            if (libraryEntry == null) {
3121                throw new IllegalStateException("Missing required shared library:" + name);
3122            }
3123            return libraryEntry.apk;
3124        }
3125    }
3126
3127    private @NonNull String getRequiredInstallerLPr() {
3128        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3129        intent.addCategory(Intent.CATEGORY_DEFAULT);
3130        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3131
3132        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3133                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3134                UserHandle.USER_SYSTEM);
3135        if (matches.size() == 1) {
3136            ResolveInfo resolveInfo = matches.get(0);
3137            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3138                throw new RuntimeException("The installer must be a privileged app");
3139            }
3140            return matches.get(0).getComponentInfo().packageName;
3141        } else {
3142            throw new RuntimeException("There must be exactly one installer; found " + matches);
3143        }
3144    }
3145
3146    private @NonNull String getRequiredUninstallerLPr() {
3147        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3148        intent.addCategory(Intent.CATEGORY_DEFAULT);
3149        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3150
3151        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3152                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3153                UserHandle.USER_SYSTEM);
3154        if (resolveInfo == null ||
3155                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3156            throw new RuntimeException("There must be exactly one uninstaller; found "
3157                    + resolveInfo);
3158        }
3159        return resolveInfo.getComponentInfo().packageName;
3160    }
3161
3162    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3163        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3164
3165        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3166                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3167                UserHandle.USER_SYSTEM);
3168        ResolveInfo best = null;
3169        final int N = matches.size();
3170        for (int i = 0; i < N; i++) {
3171            final ResolveInfo cur = matches.get(i);
3172            final String packageName = cur.getComponentInfo().packageName;
3173            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3174                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3175                continue;
3176            }
3177
3178            if (best == null || cur.priority > best.priority) {
3179                best = cur;
3180            }
3181        }
3182
3183        if (best != null) {
3184            return best.getComponentInfo().getComponentName();
3185        }
3186        Slog.w(TAG, "Intent filter verifier not found");
3187        return null;
3188    }
3189
3190    @Override
3191    public @Nullable ComponentName getInstantAppResolverComponent() {
3192        synchronized (mPackages) {
3193            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3194            if (instantAppResolver == null) {
3195                return null;
3196            }
3197            return instantAppResolver.first;
3198        }
3199    }
3200
3201    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3202        final String[] packageArray =
3203                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3204        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3205            if (DEBUG_EPHEMERAL) {
3206                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3207            }
3208            return null;
3209        }
3210
3211        final int callingUid = Binder.getCallingUid();
3212        final int resolveFlags =
3213                MATCH_DIRECT_BOOT_AWARE
3214                | MATCH_DIRECT_BOOT_UNAWARE
3215                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3216        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3217        final Intent resolverIntent = new Intent(actionName);
3218        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3219                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3220        // temporarily look for the old action
3221        if (resolvers.size() == 0) {
3222            if (DEBUG_EPHEMERAL) {
3223                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3224            }
3225            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3226            resolverIntent.setAction(actionName);
3227            resolvers = queryIntentServicesInternal(resolverIntent, null,
3228                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3229        }
3230        final int N = resolvers.size();
3231        if (N == 0) {
3232            if (DEBUG_EPHEMERAL) {
3233                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3234            }
3235            return null;
3236        }
3237
3238        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3239        for (int i = 0; i < N; i++) {
3240            final ResolveInfo info = resolvers.get(i);
3241
3242            if (info.serviceInfo == null) {
3243                continue;
3244            }
3245
3246            final String packageName = info.serviceInfo.packageName;
3247            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3248                if (DEBUG_EPHEMERAL) {
3249                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3250                            + " pkg: " + packageName + ", info:" + info);
3251                }
3252                continue;
3253            }
3254
3255            if (DEBUG_EPHEMERAL) {
3256                Slog.v(TAG, "Ephemeral resolver found;"
3257                        + " pkg: " + packageName + ", info:" + info);
3258            }
3259            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3260        }
3261        if (DEBUG_EPHEMERAL) {
3262            Slog.v(TAG, "Ephemeral resolver NOT found");
3263        }
3264        return null;
3265    }
3266
3267    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3268        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3269        intent.addCategory(Intent.CATEGORY_DEFAULT);
3270        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3271
3272        final int resolveFlags =
3273                MATCH_DIRECT_BOOT_AWARE
3274                | MATCH_DIRECT_BOOT_UNAWARE
3275                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3276        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3277                resolveFlags, UserHandle.USER_SYSTEM);
3278        // temporarily look for the old action
3279        if (matches.isEmpty()) {
3280            if (DEBUG_EPHEMERAL) {
3281                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3282            }
3283            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3284            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3285                    resolveFlags, UserHandle.USER_SYSTEM);
3286        }
3287        Iterator<ResolveInfo> iter = matches.iterator();
3288        while (iter.hasNext()) {
3289            final ResolveInfo rInfo = iter.next();
3290            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3291            if (ps != null) {
3292                final PermissionsState permissionsState = ps.getPermissionsState();
3293                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3294                    continue;
3295                }
3296            }
3297            iter.remove();
3298        }
3299        if (matches.size() == 0) {
3300            return null;
3301        } else if (matches.size() == 1) {
3302            return (ActivityInfo) matches.get(0).getComponentInfo();
3303        } else {
3304            throw new RuntimeException(
3305                    "There must be at most one ephemeral installer; found " + matches);
3306        }
3307    }
3308
3309    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3310            @NonNull ComponentName resolver) {
3311        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3312                .addCategory(Intent.CATEGORY_DEFAULT)
3313                .setPackage(resolver.getPackageName());
3314        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3315        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3316                UserHandle.USER_SYSTEM);
3317        // temporarily look for the old action
3318        if (matches.isEmpty()) {
3319            if (DEBUG_EPHEMERAL) {
3320                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3321            }
3322            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3323            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3324                    UserHandle.USER_SYSTEM);
3325        }
3326        if (matches.isEmpty()) {
3327            return null;
3328        }
3329        return matches.get(0).getComponentInfo().getComponentName();
3330    }
3331
3332    private void primeDomainVerificationsLPw(int userId) {
3333        if (DEBUG_DOMAIN_VERIFICATION) {
3334            Slog.d(TAG, "Priming domain verifications in user " + userId);
3335        }
3336
3337        SystemConfig systemConfig = SystemConfig.getInstance();
3338        ArraySet<String> packages = systemConfig.getLinkedApps();
3339
3340        for (String packageName : packages) {
3341            PackageParser.Package pkg = mPackages.get(packageName);
3342            if (pkg != null) {
3343                if (!pkg.isSystemApp()) {
3344                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3345                    continue;
3346                }
3347
3348                ArraySet<String> domains = null;
3349                for (PackageParser.Activity a : pkg.activities) {
3350                    for (ActivityIntentInfo filter : a.intents) {
3351                        if (hasValidDomains(filter)) {
3352                            if (domains == null) {
3353                                domains = new ArraySet<String>();
3354                            }
3355                            domains.addAll(filter.getHostsList());
3356                        }
3357                    }
3358                }
3359
3360                if (domains != null && domains.size() > 0) {
3361                    if (DEBUG_DOMAIN_VERIFICATION) {
3362                        Slog.v(TAG, "      + " + packageName);
3363                    }
3364                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3365                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3366                    // and then 'always' in the per-user state actually used for intent resolution.
3367                    final IntentFilterVerificationInfo ivi;
3368                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3369                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3370                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3371                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3372                } else {
3373                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3374                            + "' does not handle web links");
3375                }
3376            } else {
3377                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3378            }
3379        }
3380
3381        scheduleWritePackageRestrictionsLocked(userId);
3382        scheduleWriteSettingsLocked();
3383    }
3384
3385    private void applyFactoryDefaultBrowserLPw(int userId) {
3386        // The default browser app's package name is stored in a string resource,
3387        // with a product-specific overlay used for vendor customization.
3388        String browserPkg = mContext.getResources().getString(
3389                com.android.internal.R.string.default_browser);
3390        if (!TextUtils.isEmpty(browserPkg)) {
3391            // non-empty string => required to be a known package
3392            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3393            if (ps == null) {
3394                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3395                browserPkg = null;
3396            } else {
3397                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3398            }
3399        }
3400
3401        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3402        // default.  If there's more than one, just leave everything alone.
3403        if (browserPkg == null) {
3404            calculateDefaultBrowserLPw(userId);
3405        }
3406    }
3407
3408    private void calculateDefaultBrowserLPw(int userId) {
3409        List<String> allBrowsers = resolveAllBrowserApps(userId);
3410        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3411        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3412    }
3413
3414    private List<String> resolveAllBrowserApps(int userId) {
3415        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3416        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3417                PackageManager.MATCH_ALL, userId);
3418
3419        final int count = list.size();
3420        List<String> result = new ArrayList<String>(count);
3421        for (int i=0; i<count; i++) {
3422            ResolveInfo info = list.get(i);
3423            if (info.activityInfo == null
3424                    || !info.handleAllWebDataURI
3425                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3426                    || result.contains(info.activityInfo.packageName)) {
3427                continue;
3428            }
3429            result.add(info.activityInfo.packageName);
3430        }
3431
3432        return result;
3433    }
3434
3435    private boolean packageIsBrowser(String packageName, int userId) {
3436        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3437                PackageManager.MATCH_ALL, userId);
3438        final int N = list.size();
3439        for (int i = 0; i < N; i++) {
3440            ResolveInfo info = list.get(i);
3441            if (packageName.equals(info.activityInfo.packageName)) {
3442                return true;
3443            }
3444        }
3445        return false;
3446    }
3447
3448    private void checkDefaultBrowser() {
3449        final int myUserId = UserHandle.myUserId();
3450        final String packageName = getDefaultBrowserPackageName(myUserId);
3451        if (packageName != null) {
3452            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3453            if (info == null) {
3454                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3455                synchronized (mPackages) {
3456                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3457                }
3458            }
3459        }
3460    }
3461
3462    @Override
3463    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3464            throws RemoteException {
3465        try {
3466            return super.onTransact(code, data, reply, flags);
3467        } catch (RuntimeException e) {
3468            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3469                Slog.wtf(TAG, "Package Manager Crash", e);
3470            }
3471            throw e;
3472        }
3473    }
3474
3475    static int[] appendInts(int[] cur, int[] add) {
3476        if (add == null) return cur;
3477        if (cur == null) return add;
3478        final int N = add.length;
3479        for (int i=0; i<N; i++) {
3480            cur = appendInt(cur, add[i]);
3481        }
3482        return cur;
3483    }
3484
3485    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3486        if (!sUserManager.exists(userId)) return null;
3487        if (ps == null) {
3488            return null;
3489        }
3490        final PackageParser.Package p = ps.pkg;
3491        if (p == null) {
3492            return null;
3493        }
3494        // Filter out ephemeral app metadata:
3495        //   * The system/shell/root can see metadata for any app
3496        //   * An installed app can see metadata for 1) other installed apps
3497        //     and 2) ephemeral apps that have explicitly interacted with it
3498        //   * Ephemeral apps can only see their own data and exposed installed apps
3499        //   * Holding a signature permission allows seeing instant apps
3500        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3501        if (callingAppId != Process.SYSTEM_UID
3502                && callingAppId != Process.SHELL_UID
3503                && callingAppId != Process.ROOT_UID
3504                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3505                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3506            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3507            if (instantAppPackageName != null) {
3508                // ephemeral apps can only get information on themselves or
3509                // installed apps that are exposed.
3510                if (!instantAppPackageName.equals(p.packageName)
3511                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3512                    return null;
3513                }
3514            } else {
3515                if (ps.getInstantApp(userId)) {
3516                    // only get access to the ephemeral app if we've been granted access
3517                    if (!mInstantAppRegistry.isInstantAccessGranted(
3518                            userId, callingAppId, ps.appId)) {
3519                        return null;
3520                    }
3521                }
3522            }
3523        }
3524
3525        final PermissionsState permissionsState = ps.getPermissionsState();
3526
3527        // Compute GIDs only if requested
3528        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3529                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3530        // Compute granted permissions only if package has requested permissions
3531        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3532                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3533        final PackageUserState state = ps.readUserState(userId);
3534
3535        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3536                && ps.isSystem()) {
3537            flags |= MATCH_ANY_USER;
3538        }
3539
3540        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3541                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3542
3543        if (packageInfo == null) {
3544            return null;
3545        }
3546
3547        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3548
3549        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3550                resolveExternalPackageNameLPr(p);
3551
3552        return packageInfo;
3553    }
3554
3555    @Override
3556    public void checkPackageStartable(String packageName, int userId) {
3557        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3558
3559        synchronized (mPackages) {
3560            final PackageSetting ps = mSettings.mPackages.get(packageName);
3561            if (ps == null) {
3562                throw new SecurityException("Package " + packageName + " was not found!");
3563            }
3564
3565            if (!ps.getInstalled(userId)) {
3566                throw new SecurityException(
3567                        "Package " + packageName + " was not installed for user " + userId + "!");
3568            }
3569
3570            if (mSafeMode && !ps.isSystem()) {
3571                throw new SecurityException("Package " + packageName + " not a system app!");
3572            }
3573
3574            if (mFrozenPackages.contains(packageName)) {
3575                throw new SecurityException("Package " + packageName + " is currently frozen!");
3576            }
3577
3578            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3579                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3580                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3581            }
3582        }
3583    }
3584
3585    @Override
3586    public boolean isPackageAvailable(String packageName, int userId) {
3587        if (!sUserManager.exists(userId)) return false;
3588        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3589                false /* requireFullPermission */, false /* checkShell */, "is package available");
3590        synchronized (mPackages) {
3591            PackageParser.Package p = mPackages.get(packageName);
3592            if (p != null) {
3593                final PackageSetting ps = (PackageSetting) p.mExtras;
3594                if (ps != null) {
3595                    final PackageUserState state = ps.readUserState(userId);
3596                    if (state != null) {
3597                        return PackageParser.isAvailable(state);
3598                    }
3599                }
3600            }
3601        }
3602        return false;
3603    }
3604
3605    @Override
3606    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3607        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3608                flags, userId);
3609    }
3610
3611    @Override
3612    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3613            int flags, int userId) {
3614        return getPackageInfoInternal(versionedPackage.getPackageName(),
3615                versionedPackage.getVersionCode(), flags, userId);
3616    }
3617
3618    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3619            int flags, int userId) {
3620        if (!sUserManager.exists(userId)) return null;
3621        flags = updateFlagsForPackage(flags, userId, packageName);
3622        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3623                false /* requireFullPermission */, false /* checkShell */, "get package info");
3624
3625        // reader
3626        synchronized (mPackages) {
3627            // Normalize package name to handle renamed packages and static libs
3628            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3629
3630            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3631            if (matchFactoryOnly) {
3632                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3633                if (ps != null) {
3634                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3635                        return null;
3636                    }
3637                    return generatePackageInfo(ps, flags, userId);
3638                }
3639            }
3640
3641            PackageParser.Package p = mPackages.get(packageName);
3642            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3643                return null;
3644            }
3645            if (DEBUG_PACKAGE_INFO)
3646                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3647            if (p != null) {
3648                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3649                        Binder.getCallingUid(), userId, flags)) {
3650                    return null;
3651                }
3652                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3653            }
3654            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3655                final PackageSetting ps = mSettings.mPackages.get(packageName);
3656                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3657                    return null;
3658                }
3659                return generatePackageInfo(ps, flags, userId);
3660            }
3661        }
3662        return null;
3663    }
3664
3665    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3666            int flags) {
3667        // Callers can access only the libs they depend on, otherwise they need to explicitly
3668        // ask for the shared libraries given the caller is allowed to access all static libs.
3669        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3670            // System/shell/root get to see all static libs
3671            final int appId = UserHandle.getAppId(uid);
3672            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3673                    || appId == Process.ROOT_UID) {
3674                return false;
3675            }
3676        }
3677
3678        // No package means no static lib as it is always on internal storage
3679        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3680            return false;
3681        }
3682
3683        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3684                ps.pkg.staticSharedLibVersion);
3685        if (libEntry == null) {
3686            return false;
3687        }
3688
3689        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3690        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3691        if (uidPackageNames == null) {
3692            return true;
3693        }
3694
3695        for (String uidPackageName : uidPackageNames) {
3696            if (ps.name.equals(uidPackageName)) {
3697                return false;
3698            }
3699            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3700            if (uidPs != null) {
3701                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3702                        libEntry.info.getName());
3703                if (index < 0) {
3704                    continue;
3705                }
3706                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3707                    return false;
3708                }
3709            }
3710        }
3711        return true;
3712    }
3713
3714    @Override
3715    public String[] currentToCanonicalPackageNames(String[] names) {
3716        String[] out = new String[names.length];
3717        // reader
3718        synchronized (mPackages) {
3719            for (int i=names.length-1; i>=0; i--) {
3720                PackageSetting ps = mSettings.mPackages.get(names[i]);
3721                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3722            }
3723        }
3724        return out;
3725    }
3726
3727    @Override
3728    public String[] canonicalToCurrentPackageNames(String[] names) {
3729        String[] out = new String[names.length];
3730        // reader
3731        synchronized (mPackages) {
3732            for (int i=names.length-1; i>=0; i--) {
3733                String cur = mSettings.getRenamedPackageLPr(names[i]);
3734                out[i] = cur != null ? cur : names[i];
3735            }
3736        }
3737        return out;
3738    }
3739
3740    @Override
3741    public int getPackageUid(String packageName, int flags, int userId) {
3742        if (!sUserManager.exists(userId)) return -1;
3743        flags = updateFlagsForPackage(flags, userId, packageName);
3744        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3745                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3746
3747        // reader
3748        synchronized (mPackages) {
3749            final PackageParser.Package p = mPackages.get(packageName);
3750            if (p != null && p.isMatch(flags)) {
3751                return UserHandle.getUid(userId, p.applicationInfo.uid);
3752            }
3753            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3754                final PackageSetting ps = mSettings.mPackages.get(packageName);
3755                if (ps != null && ps.isMatch(flags)) {
3756                    return UserHandle.getUid(userId, ps.appId);
3757                }
3758            }
3759        }
3760
3761        return -1;
3762    }
3763
3764    @Override
3765    public int[] getPackageGids(String packageName, int flags, int userId) {
3766        if (!sUserManager.exists(userId)) return null;
3767        flags = updateFlagsForPackage(flags, userId, packageName);
3768        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3769                false /* requireFullPermission */, false /* checkShell */,
3770                "getPackageGids");
3771
3772        // reader
3773        synchronized (mPackages) {
3774            final PackageParser.Package p = mPackages.get(packageName);
3775            if (p != null && p.isMatch(flags)) {
3776                PackageSetting ps = (PackageSetting) p.mExtras;
3777                // TODO: Shouldn't this be checking for package installed state for userId and
3778                // return null?
3779                return ps.getPermissionsState().computeGids(userId);
3780            }
3781            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3782                final PackageSetting ps = mSettings.mPackages.get(packageName);
3783                if (ps != null && ps.isMatch(flags)) {
3784                    return ps.getPermissionsState().computeGids(userId);
3785                }
3786            }
3787        }
3788
3789        return null;
3790    }
3791
3792    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3793        if (bp.perm != null) {
3794            return PackageParser.generatePermissionInfo(bp.perm, flags);
3795        }
3796        PermissionInfo pi = new PermissionInfo();
3797        pi.name = bp.name;
3798        pi.packageName = bp.sourcePackage;
3799        pi.nonLocalizedLabel = bp.name;
3800        pi.protectionLevel = bp.protectionLevel;
3801        return pi;
3802    }
3803
3804    @Override
3805    public PermissionInfo getPermissionInfo(String name, int flags) {
3806        // reader
3807        synchronized (mPackages) {
3808            final BasePermission p = mSettings.mPermissions.get(name);
3809            if (p != null) {
3810                return generatePermissionInfo(p, flags);
3811            }
3812            return null;
3813        }
3814    }
3815
3816    @Override
3817    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3818            int flags) {
3819        // reader
3820        synchronized (mPackages) {
3821            if (group != null && !mPermissionGroups.containsKey(group)) {
3822                // This is thrown as NameNotFoundException
3823                return null;
3824            }
3825
3826            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3827            for (BasePermission p : mSettings.mPermissions.values()) {
3828                if (group == null) {
3829                    if (p.perm == null || p.perm.info.group == null) {
3830                        out.add(generatePermissionInfo(p, flags));
3831                    }
3832                } else {
3833                    if (p.perm != null && group.equals(p.perm.info.group)) {
3834                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3835                    }
3836                }
3837            }
3838            return new ParceledListSlice<>(out);
3839        }
3840    }
3841
3842    @Override
3843    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3844        // reader
3845        synchronized (mPackages) {
3846            return PackageParser.generatePermissionGroupInfo(
3847                    mPermissionGroups.get(name), flags);
3848        }
3849    }
3850
3851    @Override
3852    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3853        // reader
3854        synchronized (mPackages) {
3855            final int N = mPermissionGroups.size();
3856            ArrayList<PermissionGroupInfo> out
3857                    = new ArrayList<PermissionGroupInfo>(N);
3858            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3859                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3860            }
3861            return new ParceledListSlice<>(out);
3862        }
3863    }
3864
3865    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3866            int uid, int userId) {
3867        if (!sUserManager.exists(userId)) return null;
3868        PackageSetting ps = mSettings.mPackages.get(packageName);
3869        if (ps != null) {
3870            if (filterSharedLibPackageLPr(ps, uid, userId, flags)) {
3871                return null;
3872            }
3873            if (ps.pkg == null) {
3874                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3875                if (pInfo != null) {
3876                    return pInfo.applicationInfo;
3877                }
3878                return null;
3879            }
3880            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3881                    ps.readUserState(userId), userId);
3882            if (ai != null) {
3883                rebaseEnabledOverlays(ai, userId);
3884                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3885            }
3886            return ai;
3887        }
3888        return null;
3889    }
3890
3891    @Override
3892    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3893        if (!sUserManager.exists(userId)) return null;
3894        flags = updateFlagsForApplication(flags, userId, packageName);
3895        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3896                false /* requireFullPermission */, false /* checkShell */, "get application info");
3897
3898        // writer
3899        synchronized (mPackages) {
3900            // Normalize package name to handle renamed packages and static libs
3901            packageName = resolveInternalPackageNameLPr(packageName,
3902                    PackageManager.VERSION_CODE_HIGHEST);
3903
3904            PackageParser.Package p = mPackages.get(packageName);
3905            if (DEBUG_PACKAGE_INFO) Log.v(
3906                    TAG, "getApplicationInfo " + packageName
3907                    + ": " + p);
3908            if (p != null) {
3909                PackageSetting ps = mSettings.mPackages.get(packageName);
3910                if (ps == null) return null;
3911                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
3912                    return null;
3913                }
3914                // Note: isEnabledLP() does not apply here - always return info
3915                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3916                        p, flags, ps.readUserState(userId), userId);
3917                if (ai != null) {
3918                    rebaseEnabledOverlays(ai, userId);
3919                    ai.packageName = resolveExternalPackageNameLPr(p);
3920                }
3921                return ai;
3922            }
3923            if ("android".equals(packageName)||"system".equals(packageName)) {
3924                return mAndroidApplication;
3925            }
3926            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3927                // Already generates the external package name
3928                return generateApplicationInfoFromSettingsLPw(packageName,
3929                        Binder.getCallingUid(), flags, userId);
3930            }
3931        }
3932        return null;
3933    }
3934
3935    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3936        List<String> paths = new ArrayList<>();
3937        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3938            mEnabledOverlayPaths.get(userId);
3939        if (userSpecificOverlays != null) {
3940            if (!"android".equals(ai.packageName)) {
3941                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3942                if (frameworkOverlays != null) {
3943                    paths.addAll(frameworkOverlays);
3944                }
3945            }
3946
3947            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3948            if (appOverlays != null) {
3949                paths.addAll(appOverlays);
3950            }
3951        }
3952        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3953    }
3954
3955    private String normalizePackageNameLPr(String packageName) {
3956        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3957        return normalizedPackageName != null ? normalizedPackageName : packageName;
3958    }
3959
3960    @Override
3961    public void deletePreloadsFileCache() {
3962        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3963            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3964        }
3965        File dir = Environment.getDataPreloadsFileCacheDirectory();
3966        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3967        FileUtils.deleteContents(dir);
3968    }
3969
3970    @Override
3971    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3972            final IPackageDataObserver observer) {
3973        mContext.enforceCallingOrSelfPermission(
3974                android.Manifest.permission.CLEAR_APP_CACHE, null);
3975        mHandler.post(() -> {
3976            boolean success = false;
3977            try {
3978                freeStorage(volumeUuid, freeStorageSize, 0);
3979                success = true;
3980            } catch (IOException e) {
3981                Slog.w(TAG, e);
3982            }
3983            if (observer != null) {
3984                try {
3985                    observer.onRemoveCompleted(null, success);
3986                } catch (RemoteException e) {
3987                    Slog.w(TAG, e);
3988                }
3989            }
3990        });
3991    }
3992
3993    @Override
3994    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3995            final IntentSender pi) {
3996        mContext.enforceCallingOrSelfPermission(
3997                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3998        mHandler.post(() -> {
3999            boolean success = false;
4000            try {
4001                freeStorage(volumeUuid, freeStorageSize, 0);
4002                success = true;
4003            } catch (IOException e) {
4004                Slog.w(TAG, e);
4005            }
4006            if (pi != null) {
4007                try {
4008                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4009                } catch (SendIntentException e) {
4010                    Slog.w(TAG, e);
4011                }
4012            }
4013        });
4014    }
4015
4016    /**
4017     * Blocking call to clear various types of cached data across the system
4018     * until the requested bytes are available.
4019     */
4020    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4021        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4022        final File file = storage.findPathForUuid(volumeUuid);
4023        if (file.getUsableSpace() >= bytes) return;
4024
4025        if (ENABLE_FREE_CACHE_V2) {
4026            final boolean aggressive = (storageFlags
4027                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4028            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4029                    volumeUuid);
4030
4031            // 1. Pre-flight to determine if we have any chance to succeed
4032            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4033            if (internalVolume && (aggressive || SystemProperties
4034                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4035                deletePreloadsFileCache();
4036                if (file.getUsableSpace() >= bytes) return;
4037            }
4038
4039            // 3. Consider parsed APK data (aggressive only)
4040            if (internalVolume && aggressive) {
4041                FileUtils.deleteContents(mCacheDir);
4042                if (file.getUsableSpace() >= bytes) return;
4043            }
4044
4045            // 4. Consider cached app data (above quotas)
4046            try {
4047                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
4048            } catch (InstallerException ignored) {
4049            }
4050            if (file.getUsableSpace() >= bytes) return;
4051
4052            // 5. Consider shared libraries with refcount=0 and age>2h
4053            // 6. Consider dexopt output (aggressive only)
4054            // 7. Consider ephemeral apps not used in last week
4055
4056            // 8. Consider cached app data (below quotas)
4057            try {
4058                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
4059                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4060            } catch (InstallerException ignored) {
4061            }
4062            if (file.getUsableSpace() >= bytes) return;
4063
4064            // 9. Consider DropBox entries
4065            // 10. Consider ephemeral cookies
4066
4067        } else {
4068            try {
4069                mInstaller.freeCache(volumeUuid, bytes, 0);
4070            } catch (InstallerException ignored) {
4071            }
4072            if (file.getUsableSpace() >= bytes) return;
4073        }
4074
4075        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4076    }
4077
4078    /**
4079     * Update given flags based on encryption status of current user.
4080     */
4081    private int updateFlags(int flags, int userId) {
4082        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4083                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4084            // Caller expressed an explicit opinion about what encryption
4085            // aware/unaware components they want to see, so fall through and
4086            // give them what they want
4087        } else {
4088            // Caller expressed no opinion, so match based on user state
4089            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4090                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4091            } else {
4092                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4093            }
4094        }
4095        return flags;
4096    }
4097
4098    private UserManagerInternal getUserManagerInternal() {
4099        if (mUserManagerInternal == null) {
4100            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4101        }
4102        return mUserManagerInternal;
4103    }
4104
4105    private DeviceIdleController.LocalService getDeviceIdleController() {
4106        if (mDeviceIdleController == null) {
4107            mDeviceIdleController =
4108                    LocalServices.getService(DeviceIdleController.LocalService.class);
4109        }
4110        return mDeviceIdleController;
4111    }
4112
4113    /**
4114     * Update given flags when being used to request {@link PackageInfo}.
4115     */
4116    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4117        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4118        boolean triaged = true;
4119        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4120                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4121            // Caller is asking for component details, so they'd better be
4122            // asking for specific encryption matching behavior, or be triaged
4123            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4124                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4125                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4126                triaged = false;
4127            }
4128        }
4129        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4130                | PackageManager.MATCH_SYSTEM_ONLY
4131                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4132            triaged = false;
4133        }
4134        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4135            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4136                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4137                    + Debug.getCallers(5));
4138        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4139                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4140            // If the caller wants all packages and has a restricted profile associated with it,
4141            // then match all users. This is to make sure that launchers that need to access work
4142            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4143            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4144            flags |= PackageManager.MATCH_ANY_USER;
4145        }
4146        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4147            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4148                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4149        }
4150        return updateFlags(flags, userId);
4151    }
4152
4153    /**
4154     * Update given flags when being used to request {@link ApplicationInfo}.
4155     */
4156    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4157        return updateFlagsForPackage(flags, userId, cookie);
4158    }
4159
4160    /**
4161     * Update given flags when being used to request {@link ComponentInfo}.
4162     */
4163    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4164        if (cookie instanceof Intent) {
4165            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4166                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4167            }
4168        }
4169
4170        boolean triaged = true;
4171        // Caller is asking for component details, so they'd better be
4172        // asking for specific encryption matching behavior, or be triaged
4173        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4174                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4175                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4176            triaged = false;
4177        }
4178        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4179            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4180                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4181        }
4182
4183        return updateFlags(flags, userId);
4184    }
4185
4186    /**
4187     * Update given intent when being used to request {@link ResolveInfo}.
4188     */
4189    private Intent updateIntentForResolve(Intent intent) {
4190        if (intent.getSelector() != null) {
4191            intent = intent.getSelector();
4192        }
4193        if (DEBUG_PREFERRED) {
4194            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4195        }
4196        return intent;
4197    }
4198
4199    /**
4200     * Update given flags when being used to request {@link ResolveInfo}.
4201     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4202     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4203     * flag set. However, this flag is only honoured in three circumstances:
4204     * <ul>
4205     * <li>when called from a system process</li>
4206     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4207     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4208     * action and a {@code android.intent.category.BROWSABLE} category</li>
4209     * </ul>
4210     */
4211    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4212        return updateFlagsForResolve(flags, userId, intent, callingUid,
4213                false /*includeInstantApps*/, false /*onlyExposedExplicitly*/);
4214    }
4215    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4216            boolean includeInstantApps) {
4217        return updateFlagsForResolve(flags, userId, intent, callingUid,
4218                includeInstantApps, false /*onlyExposedExplicitly*/);
4219    }
4220    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4221            boolean includeInstantApps, boolean onlyExposedExplicitly) {
4222        // Safe mode means we shouldn't match any third-party components
4223        if (mSafeMode) {
4224            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4225        }
4226        if (getInstantAppPackageName(callingUid) != null) {
4227            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4228            if (onlyExposedExplicitly) {
4229                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4230            }
4231            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4232            flags |= PackageManager.MATCH_INSTANT;
4233        } else {
4234            // Otherwise, prevent leaking ephemeral components
4235            final boolean isSpecialProcess =
4236                    callingUid == Process.SYSTEM_UID
4237                    || callingUid == Process.SHELL_UID
4238                    || callingUid == 0;
4239            final boolean allowMatchInstant =
4240                    (includeInstantApps
4241                            && Intent.ACTION_VIEW.equals(intent.getAction())
4242                            && hasWebURI(intent))
4243                    || isSpecialProcess
4244                    || mContext.checkCallingOrSelfPermission(
4245                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4246            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4247                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4248            if (!allowMatchInstant) {
4249                flags &= ~PackageManager.MATCH_INSTANT;
4250            }
4251        }
4252        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4253    }
4254
4255    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4256            int userId) {
4257        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4258        if (ret != null) {
4259            rebaseEnabledOverlays(ret.applicationInfo, userId);
4260        }
4261        return ret;
4262    }
4263
4264    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4265            PackageUserState state, int userId) {
4266        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4267        if (ai != null) {
4268            rebaseEnabledOverlays(ai.applicationInfo, userId);
4269        }
4270        return ai;
4271    }
4272
4273    @Override
4274    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4275        if (!sUserManager.exists(userId)) return null;
4276        flags = updateFlagsForComponent(flags, userId, component);
4277        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4278                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4279        synchronized (mPackages) {
4280            PackageParser.Activity a = mActivities.mActivities.get(component);
4281
4282            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4283            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4284                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4285                if (ps == null) return null;
4286                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4287            }
4288            if (mResolveComponentName.equals(component)) {
4289                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4290                        userId);
4291            }
4292        }
4293        return null;
4294    }
4295
4296    @Override
4297    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4298            String resolvedType) {
4299        synchronized (mPackages) {
4300            if (component.equals(mResolveComponentName)) {
4301                // The resolver supports EVERYTHING!
4302                return true;
4303            }
4304            PackageParser.Activity a = mActivities.mActivities.get(component);
4305            if (a == null) {
4306                return false;
4307            }
4308            for (int i=0; i<a.intents.size(); i++) {
4309                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4310                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4311                    return true;
4312                }
4313            }
4314            return false;
4315        }
4316    }
4317
4318    @Override
4319    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4320        if (!sUserManager.exists(userId)) return null;
4321        flags = updateFlagsForComponent(flags, userId, component);
4322        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4323                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4324        synchronized (mPackages) {
4325            PackageParser.Activity a = mReceivers.mActivities.get(component);
4326            if (DEBUG_PACKAGE_INFO) Log.v(
4327                TAG, "getReceiverInfo " + component + ": " + a);
4328            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4329                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4330                if (ps == null) return null;
4331                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4332            }
4333        }
4334        return null;
4335    }
4336
4337    @Override
4338    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4339            int flags, int userId) {
4340        if (!sUserManager.exists(userId)) return null;
4341        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4342
4343        flags = updateFlagsForPackage(flags, userId, null);
4344
4345        final boolean canSeeStaticLibraries =
4346                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4347                        == PERMISSION_GRANTED
4348                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4349                        == PERMISSION_GRANTED
4350                || canRequestPackageInstallsInternal(packageName,
4351                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4352                        false  /* throwIfPermNotDeclared*/)
4353                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4354                        == PERMISSION_GRANTED;
4355
4356        synchronized (mPackages) {
4357            List<SharedLibraryInfo> result = null;
4358
4359            final int libCount = mSharedLibraries.size();
4360            for (int i = 0; i < libCount; i++) {
4361                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4362                if (versionedLib == null) {
4363                    continue;
4364                }
4365
4366                final int versionCount = versionedLib.size();
4367                for (int j = 0; j < versionCount; j++) {
4368                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4369                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4370                        break;
4371                    }
4372                    final long identity = Binder.clearCallingIdentity();
4373                    try {
4374                        PackageInfo packageInfo = getPackageInfoVersioned(
4375                                libInfo.getDeclaringPackage(), flags
4376                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4377                        if (packageInfo == null) {
4378                            continue;
4379                        }
4380                    } finally {
4381                        Binder.restoreCallingIdentity(identity);
4382                    }
4383
4384                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4385                            libInfo.getVersion(), libInfo.getType(),
4386                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4387                            flags, userId));
4388
4389                    if (result == null) {
4390                        result = new ArrayList<>();
4391                    }
4392                    result.add(resLibInfo);
4393                }
4394            }
4395
4396            return result != null ? new ParceledListSlice<>(result) : null;
4397        }
4398    }
4399
4400    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4401            SharedLibraryInfo libInfo, int flags, int userId) {
4402        List<VersionedPackage> versionedPackages = null;
4403        final int packageCount = mSettings.mPackages.size();
4404        for (int i = 0; i < packageCount; i++) {
4405            PackageSetting ps = mSettings.mPackages.valueAt(i);
4406
4407            if (ps == null) {
4408                continue;
4409            }
4410
4411            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4412                continue;
4413            }
4414
4415            final String libName = libInfo.getName();
4416            if (libInfo.isStatic()) {
4417                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4418                if (libIdx < 0) {
4419                    continue;
4420                }
4421                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4422                    continue;
4423                }
4424                if (versionedPackages == null) {
4425                    versionedPackages = new ArrayList<>();
4426                }
4427                // If the dependent is a static shared lib, use the public package name
4428                String dependentPackageName = ps.name;
4429                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4430                    dependentPackageName = ps.pkg.manifestPackageName;
4431                }
4432                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4433            } else if (ps.pkg != null) {
4434                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4435                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4436                    if (versionedPackages == null) {
4437                        versionedPackages = new ArrayList<>();
4438                    }
4439                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4440                }
4441            }
4442        }
4443
4444        return versionedPackages;
4445    }
4446
4447    @Override
4448    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4449        if (!sUserManager.exists(userId)) return null;
4450        flags = updateFlagsForComponent(flags, userId, component);
4451        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4452                false /* requireFullPermission */, false /* checkShell */, "get service info");
4453        synchronized (mPackages) {
4454            PackageParser.Service s = mServices.mServices.get(component);
4455            if (DEBUG_PACKAGE_INFO) Log.v(
4456                TAG, "getServiceInfo " + component + ": " + s);
4457            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4458                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4459                if (ps == null) return null;
4460                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4461                        ps.readUserState(userId), userId);
4462                if (si != null) {
4463                    rebaseEnabledOverlays(si.applicationInfo, userId);
4464                }
4465                return si;
4466            }
4467        }
4468        return null;
4469    }
4470
4471    @Override
4472    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4473        if (!sUserManager.exists(userId)) return null;
4474        flags = updateFlagsForComponent(flags, userId, component);
4475        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4476                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4477        synchronized (mPackages) {
4478            PackageParser.Provider p = mProviders.mProviders.get(component);
4479            if (DEBUG_PACKAGE_INFO) Log.v(
4480                TAG, "getProviderInfo " + component + ": " + p);
4481            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4482                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4483                if (ps == null) return null;
4484                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4485                        ps.readUserState(userId), userId);
4486                if (pi != null) {
4487                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4488                }
4489                return pi;
4490            }
4491        }
4492        return null;
4493    }
4494
4495    @Override
4496    public String[] getSystemSharedLibraryNames() {
4497        synchronized (mPackages) {
4498            Set<String> libs = null;
4499            final int libCount = mSharedLibraries.size();
4500            for (int i = 0; i < libCount; i++) {
4501                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4502                if (versionedLib == null) {
4503                    continue;
4504                }
4505                final int versionCount = versionedLib.size();
4506                for (int j = 0; j < versionCount; j++) {
4507                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4508                    if (!libEntry.info.isStatic()) {
4509                        if (libs == null) {
4510                            libs = new ArraySet<>();
4511                        }
4512                        libs.add(libEntry.info.getName());
4513                        break;
4514                    }
4515                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4516                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4517                            UserHandle.getUserId(Binder.getCallingUid()),
4518                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4519                        if (libs == null) {
4520                            libs = new ArraySet<>();
4521                        }
4522                        libs.add(libEntry.info.getName());
4523                        break;
4524                    }
4525                }
4526            }
4527
4528            if (libs != null) {
4529                String[] libsArray = new String[libs.size()];
4530                libs.toArray(libsArray);
4531                return libsArray;
4532            }
4533
4534            return null;
4535        }
4536    }
4537
4538    @Override
4539    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4540        synchronized (mPackages) {
4541            return mServicesSystemSharedLibraryPackageName;
4542        }
4543    }
4544
4545    @Override
4546    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4547        synchronized (mPackages) {
4548            return mSharedSystemSharedLibraryPackageName;
4549        }
4550    }
4551
4552    private void updateSequenceNumberLP(String packageName, int[] userList) {
4553        for (int i = userList.length - 1; i >= 0; --i) {
4554            final int userId = userList[i];
4555            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4556            if (changedPackages == null) {
4557                changedPackages = new SparseArray<>();
4558                mChangedPackages.put(userId, changedPackages);
4559            }
4560            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4561            if (sequenceNumbers == null) {
4562                sequenceNumbers = new HashMap<>();
4563                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4564            }
4565            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4566            if (sequenceNumber != null) {
4567                changedPackages.remove(sequenceNumber);
4568            }
4569            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4570            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4571        }
4572        mChangedPackagesSequenceNumber++;
4573    }
4574
4575    @Override
4576    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4577        synchronized (mPackages) {
4578            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4579                return null;
4580            }
4581            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4582            if (changedPackages == null) {
4583                return null;
4584            }
4585            final List<String> packageNames =
4586                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4587            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4588                final String packageName = changedPackages.get(i);
4589                if (packageName != null) {
4590                    packageNames.add(packageName);
4591                }
4592            }
4593            return packageNames.isEmpty()
4594                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4595        }
4596    }
4597
4598    @Override
4599    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4600        ArrayList<FeatureInfo> res;
4601        synchronized (mAvailableFeatures) {
4602            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4603            res.addAll(mAvailableFeatures.values());
4604        }
4605        final FeatureInfo fi = new FeatureInfo();
4606        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4607                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4608        res.add(fi);
4609
4610        return new ParceledListSlice<>(res);
4611    }
4612
4613    @Override
4614    public boolean hasSystemFeature(String name, int version) {
4615        synchronized (mAvailableFeatures) {
4616            final FeatureInfo feat = mAvailableFeatures.get(name);
4617            if (feat == null) {
4618                return false;
4619            } else {
4620                return feat.version >= version;
4621            }
4622        }
4623    }
4624
4625    @Override
4626    public int checkPermission(String permName, String pkgName, int userId) {
4627        if (!sUserManager.exists(userId)) {
4628            return PackageManager.PERMISSION_DENIED;
4629        }
4630
4631        synchronized (mPackages) {
4632            final PackageParser.Package p = mPackages.get(pkgName);
4633            if (p != null && p.mExtras != null) {
4634                final PackageSetting ps = (PackageSetting) p.mExtras;
4635                final PermissionsState permissionsState = ps.getPermissionsState();
4636                if (permissionsState.hasPermission(permName, userId)) {
4637                    return PackageManager.PERMISSION_GRANTED;
4638                }
4639                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4640                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4641                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4642                    return PackageManager.PERMISSION_GRANTED;
4643                }
4644            }
4645        }
4646
4647        return PackageManager.PERMISSION_DENIED;
4648    }
4649
4650    @Override
4651    public int checkUidPermission(String permName, int uid) {
4652        final int userId = UserHandle.getUserId(uid);
4653
4654        if (!sUserManager.exists(userId)) {
4655            return PackageManager.PERMISSION_DENIED;
4656        }
4657
4658        synchronized (mPackages) {
4659            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4660            if (obj != null) {
4661                final SettingBase ps = (SettingBase) obj;
4662                final PermissionsState permissionsState = ps.getPermissionsState();
4663                if (permissionsState.hasPermission(permName, userId)) {
4664                    return PackageManager.PERMISSION_GRANTED;
4665                }
4666                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4667                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4668                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4669                    return PackageManager.PERMISSION_GRANTED;
4670                }
4671            } else {
4672                ArraySet<String> perms = mSystemPermissions.get(uid);
4673                if (perms != null) {
4674                    if (perms.contains(permName)) {
4675                        return PackageManager.PERMISSION_GRANTED;
4676                    }
4677                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4678                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4679                        return PackageManager.PERMISSION_GRANTED;
4680                    }
4681                }
4682            }
4683        }
4684
4685        return PackageManager.PERMISSION_DENIED;
4686    }
4687
4688    @Override
4689    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4690        if (UserHandle.getCallingUserId() != userId) {
4691            mContext.enforceCallingPermission(
4692                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4693                    "isPermissionRevokedByPolicy for user " + userId);
4694        }
4695
4696        if (checkPermission(permission, packageName, userId)
4697                == PackageManager.PERMISSION_GRANTED) {
4698            return false;
4699        }
4700
4701        final long identity = Binder.clearCallingIdentity();
4702        try {
4703            final int flags = getPermissionFlags(permission, packageName, userId);
4704            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4705        } finally {
4706            Binder.restoreCallingIdentity(identity);
4707        }
4708    }
4709
4710    @Override
4711    public String getPermissionControllerPackageName() {
4712        synchronized (mPackages) {
4713            return mRequiredInstallerPackage;
4714        }
4715    }
4716
4717    /**
4718     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4719     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4720     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4721     * @param message the message to log on security exception
4722     */
4723    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4724            boolean checkShell, String message) {
4725        if (userId < 0) {
4726            throw new IllegalArgumentException("Invalid userId " + userId);
4727        }
4728        if (checkShell) {
4729            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4730        }
4731        if (userId == UserHandle.getUserId(callingUid)) return;
4732        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4733            if (requireFullPermission) {
4734                mContext.enforceCallingOrSelfPermission(
4735                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4736            } else {
4737                try {
4738                    mContext.enforceCallingOrSelfPermission(
4739                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4740                } catch (SecurityException se) {
4741                    mContext.enforceCallingOrSelfPermission(
4742                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4743                }
4744            }
4745        }
4746    }
4747
4748    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4749        if (callingUid == Process.SHELL_UID) {
4750            if (userHandle >= 0
4751                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4752                throw new SecurityException("Shell does not have permission to access user "
4753                        + userHandle);
4754            } else if (userHandle < 0) {
4755                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4756                        + Debug.getCallers(3));
4757            }
4758        }
4759    }
4760
4761    private BasePermission findPermissionTreeLP(String permName) {
4762        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4763            if (permName.startsWith(bp.name) &&
4764                    permName.length() > bp.name.length() &&
4765                    permName.charAt(bp.name.length()) == '.') {
4766                return bp;
4767            }
4768        }
4769        return null;
4770    }
4771
4772    private BasePermission checkPermissionTreeLP(String permName) {
4773        if (permName != null) {
4774            BasePermission bp = findPermissionTreeLP(permName);
4775            if (bp != null) {
4776                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4777                    return bp;
4778                }
4779                throw new SecurityException("Calling uid "
4780                        + Binder.getCallingUid()
4781                        + " is not allowed to add to permission tree "
4782                        + bp.name + " owned by uid " + bp.uid);
4783            }
4784        }
4785        throw new SecurityException("No permission tree found for " + permName);
4786    }
4787
4788    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4789        if (s1 == null) {
4790            return s2 == null;
4791        }
4792        if (s2 == null) {
4793            return false;
4794        }
4795        if (s1.getClass() != s2.getClass()) {
4796            return false;
4797        }
4798        return s1.equals(s2);
4799    }
4800
4801    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4802        if (pi1.icon != pi2.icon) return false;
4803        if (pi1.logo != pi2.logo) return false;
4804        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4805        if (!compareStrings(pi1.name, pi2.name)) return false;
4806        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4807        // We'll take care of setting this one.
4808        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4809        // These are not currently stored in settings.
4810        //if (!compareStrings(pi1.group, pi2.group)) return false;
4811        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4812        //if (pi1.labelRes != pi2.labelRes) return false;
4813        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4814        return true;
4815    }
4816
4817    int permissionInfoFootprint(PermissionInfo info) {
4818        int size = info.name.length();
4819        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4820        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4821        return size;
4822    }
4823
4824    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4825        int size = 0;
4826        for (BasePermission perm : mSettings.mPermissions.values()) {
4827            if (perm.uid == tree.uid) {
4828                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4829            }
4830        }
4831        return size;
4832    }
4833
4834    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4835        // We calculate the max size of permissions defined by this uid and throw
4836        // if that plus the size of 'info' would exceed our stated maximum.
4837        if (tree.uid != Process.SYSTEM_UID) {
4838            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4839            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4840                throw new SecurityException("Permission tree size cap exceeded");
4841            }
4842        }
4843    }
4844
4845    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4846        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4847            throw new SecurityException("Label must be specified in permission");
4848        }
4849        BasePermission tree = checkPermissionTreeLP(info.name);
4850        BasePermission bp = mSettings.mPermissions.get(info.name);
4851        boolean added = bp == null;
4852        boolean changed = true;
4853        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4854        if (added) {
4855            enforcePermissionCapLocked(info, tree);
4856            bp = new BasePermission(info.name, tree.sourcePackage,
4857                    BasePermission.TYPE_DYNAMIC);
4858        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4859            throw new SecurityException(
4860                    "Not allowed to modify non-dynamic permission "
4861                    + info.name);
4862        } else {
4863            if (bp.protectionLevel == fixedLevel
4864                    && bp.perm.owner.equals(tree.perm.owner)
4865                    && bp.uid == tree.uid
4866                    && comparePermissionInfos(bp.perm.info, info)) {
4867                changed = false;
4868            }
4869        }
4870        bp.protectionLevel = fixedLevel;
4871        info = new PermissionInfo(info);
4872        info.protectionLevel = fixedLevel;
4873        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4874        bp.perm.info.packageName = tree.perm.info.packageName;
4875        bp.uid = tree.uid;
4876        if (added) {
4877            mSettings.mPermissions.put(info.name, bp);
4878        }
4879        if (changed) {
4880            if (!async) {
4881                mSettings.writeLPr();
4882            } else {
4883                scheduleWriteSettingsLocked();
4884            }
4885        }
4886        return added;
4887    }
4888
4889    @Override
4890    public boolean addPermission(PermissionInfo info) {
4891        synchronized (mPackages) {
4892            return addPermissionLocked(info, false);
4893        }
4894    }
4895
4896    @Override
4897    public boolean addPermissionAsync(PermissionInfo info) {
4898        synchronized (mPackages) {
4899            return addPermissionLocked(info, true);
4900        }
4901    }
4902
4903    @Override
4904    public void removePermission(String name) {
4905        synchronized (mPackages) {
4906            checkPermissionTreeLP(name);
4907            BasePermission bp = mSettings.mPermissions.get(name);
4908            if (bp != null) {
4909                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4910                    throw new SecurityException(
4911                            "Not allowed to modify non-dynamic permission "
4912                            + name);
4913                }
4914                mSettings.mPermissions.remove(name);
4915                mSettings.writeLPr();
4916            }
4917        }
4918    }
4919
4920    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4921            BasePermission bp) {
4922        int index = pkg.requestedPermissions.indexOf(bp.name);
4923        if (index == -1) {
4924            throw new SecurityException("Package " + pkg.packageName
4925                    + " has not requested permission " + bp.name);
4926        }
4927        if (!bp.isRuntime() && !bp.isDevelopment()) {
4928            throw new SecurityException("Permission " + bp.name
4929                    + " is not a changeable permission type");
4930        }
4931    }
4932
4933    @Override
4934    public void grantRuntimePermission(String packageName, String name, final int userId) {
4935        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4936    }
4937
4938    private void grantRuntimePermission(String packageName, String name, final int userId,
4939            boolean overridePolicy) {
4940        if (!sUserManager.exists(userId)) {
4941            Log.e(TAG, "No such user:" + userId);
4942            return;
4943        }
4944
4945        mContext.enforceCallingOrSelfPermission(
4946                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4947                "grantRuntimePermission");
4948
4949        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4950                true /* requireFullPermission */, true /* checkShell */,
4951                "grantRuntimePermission");
4952
4953        final int uid;
4954        final SettingBase sb;
4955
4956        synchronized (mPackages) {
4957            final PackageParser.Package pkg = mPackages.get(packageName);
4958            if (pkg == null) {
4959                throw new IllegalArgumentException("Unknown package: " + packageName);
4960            }
4961
4962            final BasePermission bp = mSettings.mPermissions.get(name);
4963            if (bp == null) {
4964                throw new IllegalArgumentException("Unknown permission: " + name);
4965            }
4966
4967            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4968
4969            // If a permission review is required for legacy apps we represent
4970            // their permissions as always granted runtime ones since we need
4971            // to keep the review required permission flag per user while an
4972            // install permission's state is shared across all users.
4973            if (mPermissionReviewRequired
4974                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4975                    && bp.isRuntime()) {
4976                return;
4977            }
4978
4979            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4980            sb = (SettingBase) pkg.mExtras;
4981            if (sb == null) {
4982                throw new IllegalArgumentException("Unknown package: " + packageName);
4983            }
4984
4985            final PermissionsState permissionsState = sb.getPermissionsState();
4986
4987            final int flags = permissionsState.getPermissionFlags(name, userId);
4988            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4989                throw new SecurityException("Cannot grant system fixed permission "
4990                        + name + " for package " + packageName);
4991            }
4992            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4993                throw new SecurityException("Cannot grant policy fixed permission "
4994                        + name + " for package " + packageName);
4995            }
4996
4997            if (bp.isDevelopment()) {
4998                // Development permissions must be handled specially, since they are not
4999                // normal runtime permissions.  For now they apply to all users.
5000                if (permissionsState.grantInstallPermission(bp) !=
5001                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5002                    scheduleWriteSettingsLocked();
5003                }
5004                return;
5005            }
5006
5007            final PackageSetting ps = mSettings.mPackages.get(packageName);
5008            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5009                throw new SecurityException("Cannot grant non-ephemeral permission"
5010                        + name + " for package " + packageName);
5011            }
5012
5013            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5014                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5015                return;
5016            }
5017
5018            final int result = permissionsState.grantRuntimePermission(bp, userId);
5019            switch (result) {
5020                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5021                    return;
5022                }
5023
5024                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5025                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5026                    mHandler.post(new Runnable() {
5027                        @Override
5028                        public void run() {
5029                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5030                        }
5031                    });
5032                }
5033                break;
5034            }
5035
5036            if (bp.isRuntime()) {
5037                logPermissionGranted(mContext, name, packageName);
5038            }
5039
5040            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5041
5042            // Not critical if that is lost - app has to request again.
5043            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5044        }
5045
5046        // Only need to do this if user is initialized. Otherwise it's a new user
5047        // and there are no processes running as the user yet and there's no need
5048        // to make an expensive call to remount processes for the changed permissions.
5049        if (READ_EXTERNAL_STORAGE.equals(name)
5050                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5051            final long token = Binder.clearCallingIdentity();
5052            try {
5053                if (sUserManager.isInitialized(userId)) {
5054                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5055                            StorageManagerInternal.class);
5056                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5057                }
5058            } finally {
5059                Binder.restoreCallingIdentity(token);
5060            }
5061        }
5062    }
5063
5064    @Override
5065    public void revokeRuntimePermission(String packageName, String name, int userId) {
5066        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5067    }
5068
5069    private void revokeRuntimePermission(String packageName, String name, int userId,
5070            boolean overridePolicy) {
5071        if (!sUserManager.exists(userId)) {
5072            Log.e(TAG, "No such user:" + userId);
5073            return;
5074        }
5075
5076        mContext.enforceCallingOrSelfPermission(
5077                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5078                "revokeRuntimePermission");
5079
5080        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5081                true /* requireFullPermission */, true /* checkShell */,
5082                "revokeRuntimePermission");
5083
5084        final int appId;
5085
5086        synchronized (mPackages) {
5087            final PackageParser.Package pkg = mPackages.get(packageName);
5088            if (pkg == null) {
5089                throw new IllegalArgumentException("Unknown package: " + packageName);
5090            }
5091
5092            final BasePermission bp = mSettings.mPermissions.get(name);
5093            if (bp == null) {
5094                throw new IllegalArgumentException("Unknown permission: " + name);
5095            }
5096
5097            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5098
5099            // If a permission review is required for legacy apps we represent
5100            // their permissions as always granted runtime ones since we need
5101            // to keep the review required permission flag per user while an
5102            // install permission's state is shared across all users.
5103            if (mPermissionReviewRequired
5104                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5105                    && bp.isRuntime()) {
5106                return;
5107            }
5108
5109            SettingBase sb = (SettingBase) pkg.mExtras;
5110            if (sb == null) {
5111                throw new IllegalArgumentException("Unknown package: " + packageName);
5112            }
5113
5114            final PermissionsState permissionsState = sb.getPermissionsState();
5115
5116            final int flags = permissionsState.getPermissionFlags(name, userId);
5117            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5118                throw new SecurityException("Cannot revoke system fixed permission "
5119                        + name + " for package " + packageName);
5120            }
5121            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5122                throw new SecurityException("Cannot revoke policy fixed permission "
5123                        + name + " for package " + packageName);
5124            }
5125
5126            if (bp.isDevelopment()) {
5127                // Development permissions must be handled specially, since they are not
5128                // normal runtime permissions.  For now they apply to all users.
5129                if (permissionsState.revokeInstallPermission(bp) !=
5130                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5131                    scheduleWriteSettingsLocked();
5132                }
5133                return;
5134            }
5135
5136            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5137                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5138                return;
5139            }
5140
5141            if (bp.isRuntime()) {
5142                logPermissionRevoked(mContext, name, packageName);
5143            }
5144
5145            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5146
5147            // Critical, after this call app should never have the permission.
5148            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5149
5150            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5151        }
5152
5153        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5154    }
5155
5156    /**
5157     * Get the first event id for the permission.
5158     *
5159     * <p>There are four events for each permission: <ul>
5160     *     <li>Request permission: first id + 0</li>
5161     *     <li>Grant permission: first id + 1</li>
5162     *     <li>Request for permission denied: first id + 2</li>
5163     *     <li>Revoke permission: first id + 3</li>
5164     * </ul></p>
5165     *
5166     * @param name name of the permission
5167     *
5168     * @return The first event id for the permission
5169     */
5170    private static int getBaseEventId(@NonNull String name) {
5171        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5172
5173        if (eventIdIndex == -1) {
5174            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5175                    || "user".equals(Build.TYPE)) {
5176                Log.i(TAG, "Unknown permission " + name);
5177
5178                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5179            } else {
5180                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5181                //
5182                // Also update
5183                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5184                // - metrics_constants.proto
5185                throw new IllegalStateException("Unknown permission " + name);
5186            }
5187        }
5188
5189        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5190    }
5191
5192    /**
5193     * Log that a permission was revoked.
5194     *
5195     * @param context Context of the caller
5196     * @param name name of the permission
5197     * @param packageName package permission if for
5198     */
5199    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5200            @NonNull String packageName) {
5201        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5202    }
5203
5204    /**
5205     * Log that a permission request was granted.
5206     *
5207     * @param context Context of the caller
5208     * @param name name of the permission
5209     * @param packageName package permission if for
5210     */
5211    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5212            @NonNull String packageName) {
5213        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5214    }
5215
5216    @Override
5217    public void resetRuntimePermissions() {
5218        mContext.enforceCallingOrSelfPermission(
5219                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5220                "revokeRuntimePermission");
5221
5222        int callingUid = Binder.getCallingUid();
5223        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5224            mContext.enforceCallingOrSelfPermission(
5225                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5226                    "resetRuntimePermissions");
5227        }
5228
5229        synchronized (mPackages) {
5230            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5231            for (int userId : UserManagerService.getInstance().getUserIds()) {
5232                final int packageCount = mPackages.size();
5233                for (int i = 0; i < packageCount; i++) {
5234                    PackageParser.Package pkg = mPackages.valueAt(i);
5235                    if (!(pkg.mExtras instanceof PackageSetting)) {
5236                        continue;
5237                    }
5238                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5239                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5240                }
5241            }
5242        }
5243    }
5244
5245    @Override
5246    public int getPermissionFlags(String name, String packageName, int userId) {
5247        if (!sUserManager.exists(userId)) {
5248            return 0;
5249        }
5250
5251        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5252
5253        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5254                true /* requireFullPermission */, false /* checkShell */,
5255                "getPermissionFlags");
5256
5257        synchronized (mPackages) {
5258            final PackageParser.Package pkg = mPackages.get(packageName);
5259            if (pkg == null) {
5260                return 0;
5261            }
5262
5263            final BasePermission bp = mSettings.mPermissions.get(name);
5264            if (bp == null) {
5265                return 0;
5266            }
5267
5268            SettingBase sb = (SettingBase) pkg.mExtras;
5269            if (sb == null) {
5270                return 0;
5271            }
5272
5273            PermissionsState permissionsState = sb.getPermissionsState();
5274            return permissionsState.getPermissionFlags(name, userId);
5275        }
5276    }
5277
5278    @Override
5279    public void updatePermissionFlags(String name, String packageName, int flagMask,
5280            int flagValues, int userId) {
5281        if (!sUserManager.exists(userId)) {
5282            return;
5283        }
5284
5285        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5286
5287        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5288                true /* requireFullPermission */, true /* checkShell */,
5289                "updatePermissionFlags");
5290
5291        // Only the system can change these flags and nothing else.
5292        if (getCallingUid() != Process.SYSTEM_UID) {
5293            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5294            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5295            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5296            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5297            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5298        }
5299
5300        synchronized (mPackages) {
5301            final PackageParser.Package pkg = mPackages.get(packageName);
5302            if (pkg == null) {
5303                throw new IllegalArgumentException("Unknown package: " + packageName);
5304            }
5305
5306            final BasePermission bp = mSettings.mPermissions.get(name);
5307            if (bp == null) {
5308                throw new IllegalArgumentException("Unknown permission: " + name);
5309            }
5310
5311            SettingBase sb = (SettingBase) pkg.mExtras;
5312            if (sb == null) {
5313                throw new IllegalArgumentException("Unknown package: " + packageName);
5314            }
5315
5316            PermissionsState permissionsState = sb.getPermissionsState();
5317
5318            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5319
5320            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5321                // Install and runtime permissions are stored in different places,
5322                // so figure out what permission changed and persist the change.
5323                if (permissionsState.getInstallPermissionState(name) != null) {
5324                    scheduleWriteSettingsLocked();
5325                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5326                        || hadState) {
5327                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5328                }
5329            }
5330        }
5331    }
5332
5333    /**
5334     * Update the permission flags for all packages and runtime permissions of a user in order
5335     * to allow device or profile owner to remove POLICY_FIXED.
5336     */
5337    @Override
5338    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5339        if (!sUserManager.exists(userId)) {
5340            return;
5341        }
5342
5343        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5344
5345        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5346                true /* requireFullPermission */, true /* checkShell */,
5347                "updatePermissionFlagsForAllApps");
5348
5349        // Only the system can change system fixed flags.
5350        if (getCallingUid() != Process.SYSTEM_UID) {
5351            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5352            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5353        }
5354
5355        synchronized (mPackages) {
5356            boolean changed = false;
5357            final int packageCount = mPackages.size();
5358            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5359                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5360                SettingBase sb = (SettingBase) pkg.mExtras;
5361                if (sb == null) {
5362                    continue;
5363                }
5364                PermissionsState permissionsState = sb.getPermissionsState();
5365                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5366                        userId, flagMask, flagValues);
5367            }
5368            if (changed) {
5369                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5370            }
5371        }
5372    }
5373
5374    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5375        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5376                != PackageManager.PERMISSION_GRANTED
5377            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5378                != PackageManager.PERMISSION_GRANTED) {
5379            throw new SecurityException(message + " requires "
5380                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5381                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5382        }
5383    }
5384
5385    @Override
5386    public boolean shouldShowRequestPermissionRationale(String permissionName,
5387            String packageName, int userId) {
5388        if (UserHandle.getCallingUserId() != userId) {
5389            mContext.enforceCallingPermission(
5390                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5391                    "canShowRequestPermissionRationale for user " + userId);
5392        }
5393
5394        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5395        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5396            return false;
5397        }
5398
5399        if (checkPermission(permissionName, packageName, userId)
5400                == PackageManager.PERMISSION_GRANTED) {
5401            return false;
5402        }
5403
5404        final int flags;
5405
5406        final long identity = Binder.clearCallingIdentity();
5407        try {
5408            flags = getPermissionFlags(permissionName,
5409                    packageName, userId);
5410        } finally {
5411            Binder.restoreCallingIdentity(identity);
5412        }
5413
5414        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5415                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5416                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5417
5418        if ((flags & fixedFlags) != 0) {
5419            return false;
5420        }
5421
5422        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5423    }
5424
5425    @Override
5426    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5427        mContext.enforceCallingOrSelfPermission(
5428                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5429                "addOnPermissionsChangeListener");
5430
5431        synchronized (mPackages) {
5432            mOnPermissionChangeListeners.addListenerLocked(listener);
5433        }
5434    }
5435
5436    @Override
5437    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5438        synchronized (mPackages) {
5439            mOnPermissionChangeListeners.removeListenerLocked(listener);
5440        }
5441    }
5442
5443    @Override
5444    public boolean isProtectedBroadcast(String actionName) {
5445        synchronized (mPackages) {
5446            if (mProtectedBroadcasts.contains(actionName)) {
5447                return true;
5448            } else if (actionName != null) {
5449                // TODO: remove these terrible hacks
5450                if (actionName.startsWith("android.net.netmon.lingerExpired")
5451                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5452                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5453                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5454                    return true;
5455                }
5456            }
5457        }
5458        return false;
5459    }
5460
5461    @Override
5462    public int checkSignatures(String pkg1, String pkg2) {
5463        synchronized (mPackages) {
5464            final PackageParser.Package p1 = mPackages.get(pkg1);
5465            final PackageParser.Package p2 = mPackages.get(pkg2);
5466            if (p1 == null || p1.mExtras == null
5467                    || p2 == null || p2.mExtras == null) {
5468                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5469            }
5470            return compareSignatures(p1.mSignatures, p2.mSignatures);
5471        }
5472    }
5473
5474    @Override
5475    public int checkUidSignatures(int uid1, int uid2) {
5476        // Map to base uids.
5477        uid1 = UserHandle.getAppId(uid1);
5478        uid2 = UserHandle.getAppId(uid2);
5479        // reader
5480        synchronized (mPackages) {
5481            Signature[] s1;
5482            Signature[] s2;
5483            Object obj = mSettings.getUserIdLPr(uid1);
5484            if (obj != null) {
5485                if (obj instanceof SharedUserSetting) {
5486                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5487                } else if (obj instanceof PackageSetting) {
5488                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5489                } else {
5490                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5491                }
5492            } else {
5493                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5494            }
5495            obj = mSettings.getUserIdLPr(uid2);
5496            if (obj != null) {
5497                if (obj instanceof SharedUserSetting) {
5498                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5499                } else if (obj instanceof PackageSetting) {
5500                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5501                } else {
5502                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5503                }
5504            } else {
5505                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5506            }
5507            return compareSignatures(s1, s2);
5508        }
5509    }
5510
5511    /**
5512     * This method should typically only be used when granting or revoking
5513     * permissions, since the app may immediately restart after this call.
5514     * <p>
5515     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5516     * guard your work against the app being relaunched.
5517     */
5518    private void killUid(int appId, int userId, String reason) {
5519        final long identity = Binder.clearCallingIdentity();
5520        try {
5521            IActivityManager am = ActivityManager.getService();
5522            if (am != null) {
5523                try {
5524                    am.killUid(appId, userId, reason);
5525                } catch (RemoteException e) {
5526                    /* ignore - same process */
5527                }
5528            }
5529        } finally {
5530            Binder.restoreCallingIdentity(identity);
5531        }
5532    }
5533
5534    /**
5535     * Compares two sets of signatures. Returns:
5536     * <br />
5537     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5538     * <br />
5539     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5540     * <br />
5541     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5542     * <br />
5543     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5544     * <br />
5545     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5546     */
5547    static int compareSignatures(Signature[] s1, Signature[] s2) {
5548        if (s1 == null) {
5549            return s2 == null
5550                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5551                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5552        }
5553
5554        if (s2 == null) {
5555            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5556        }
5557
5558        if (s1.length != s2.length) {
5559            return PackageManager.SIGNATURE_NO_MATCH;
5560        }
5561
5562        // Since both signature sets are of size 1, we can compare without HashSets.
5563        if (s1.length == 1) {
5564            return s1[0].equals(s2[0]) ?
5565                    PackageManager.SIGNATURE_MATCH :
5566                    PackageManager.SIGNATURE_NO_MATCH;
5567        }
5568
5569        ArraySet<Signature> set1 = new ArraySet<Signature>();
5570        for (Signature sig : s1) {
5571            set1.add(sig);
5572        }
5573        ArraySet<Signature> set2 = new ArraySet<Signature>();
5574        for (Signature sig : s2) {
5575            set2.add(sig);
5576        }
5577        // Make sure s2 contains all signatures in s1.
5578        if (set1.equals(set2)) {
5579            return PackageManager.SIGNATURE_MATCH;
5580        }
5581        return PackageManager.SIGNATURE_NO_MATCH;
5582    }
5583
5584    /**
5585     * If the database version for this type of package (internal storage or
5586     * external storage) is less than the version where package signatures
5587     * were updated, return true.
5588     */
5589    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5590        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5591        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5592    }
5593
5594    /**
5595     * Used for backward compatibility to make sure any packages with
5596     * certificate chains get upgraded to the new style. {@code existingSigs}
5597     * will be in the old format (since they were stored on disk from before the
5598     * system upgrade) and {@code scannedSigs} will be in the newer format.
5599     */
5600    private int compareSignaturesCompat(PackageSignatures existingSigs,
5601            PackageParser.Package scannedPkg) {
5602        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5603            return PackageManager.SIGNATURE_NO_MATCH;
5604        }
5605
5606        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5607        for (Signature sig : existingSigs.mSignatures) {
5608            existingSet.add(sig);
5609        }
5610        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5611        for (Signature sig : scannedPkg.mSignatures) {
5612            try {
5613                Signature[] chainSignatures = sig.getChainSignatures();
5614                for (Signature chainSig : chainSignatures) {
5615                    scannedCompatSet.add(chainSig);
5616                }
5617            } catch (CertificateEncodingException e) {
5618                scannedCompatSet.add(sig);
5619            }
5620        }
5621        /*
5622         * Make sure the expanded scanned set contains all signatures in the
5623         * existing one.
5624         */
5625        if (scannedCompatSet.equals(existingSet)) {
5626            // Migrate the old signatures to the new scheme.
5627            existingSigs.assignSignatures(scannedPkg.mSignatures);
5628            // The new KeySets will be re-added later in the scanning process.
5629            synchronized (mPackages) {
5630                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5631            }
5632            return PackageManager.SIGNATURE_MATCH;
5633        }
5634        return PackageManager.SIGNATURE_NO_MATCH;
5635    }
5636
5637    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5638        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5639        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5640    }
5641
5642    private int compareSignaturesRecover(PackageSignatures existingSigs,
5643            PackageParser.Package scannedPkg) {
5644        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5645            return PackageManager.SIGNATURE_NO_MATCH;
5646        }
5647
5648        String msg = null;
5649        try {
5650            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5651                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5652                        + scannedPkg.packageName);
5653                return PackageManager.SIGNATURE_MATCH;
5654            }
5655        } catch (CertificateException e) {
5656            msg = e.getMessage();
5657        }
5658
5659        logCriticalInfo(Log.INFO,
5660                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5661        return PackageManager.SIGNATURE_NO_MATCH;
5662    }
5663
5664    @Override
5665    public List<String> getAllPackages() {
5666        synchronized (mPackages) {
5667            return new ArrayList<String>(mPackages.keySet());
5668        }
5669    }
5670
5671    @Override
5672    public String[] getPackagesForUid(int uid) {
5673        final int userId = UserHandle.getUserId(uid);
5674        uid = UserHandle.getAppId(uid);
5675        // reader
5676        synchronized (mPackages) {
5677            Object obj = mSettings.getUserIdLPr(uid);
5678            if (obj instanceof SharedUserSetting) {
5679                final SharedUserSetting sus = (SharedUserSetting) obj;
5680                final int N = sus.packages.size();
5681                String[] res = new String[N];
5682                final Iterator<PackageSetting> it = sus.packages.iterator();
5683                int i = 0;
5684                while (it.hasNext()) {
5685                    PackageSetting ps = it.next();
5686                    if (ps.getInstalled(userId)) {
5687                        res[i++] = ps.name;
5688                    } else {
5689                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5690                    }
5691                }
5692                return res;
5693            } else if (obj instanceof PackageSetting) {
5694                final PackageSetting ps = (PackageSetting) obj;
5695                if (ps.getInstalled(userId)) {
5696                    return new String[]{ps.name};
5697                }
5698            }
5699        }
5700        return null;
5701    }
5702
5703    @Override
5704    public String getNameForUid(int uid) {
5705        // reader
5706        synchronized (mPackages) {
5707            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5708            if (obj instanceof SharedUserSetting) {
5709                final SharedUserSetting sus = (SharedUserSetting) obj;
5710                return sus.name + ":" + sus.userId;
5711            } else if (obj instanceof PackageSetting) {
5712                final PackageSetting ps = (PackageSetting) obj;
5713                return ps.name;
5714            }
5715        }
5716        return null;
5717    }
5718
5719    @Override
5720    public int getUidForSharedUser(String sharedUserName) {
5721        if(sharedUserName == null) {
5722            return -1;
5723        }
5724        // reader
5725        synchronized (mPackages) {
5726            SharedUserSetting suid;
5727            try {
5728                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5729                if (suid != null) {
5730                    return suid.userId;
5731                }
5732            } catch (PackageManagerException ignore) {
5733                // can't happen, but, still need to catch it
5734            }
5735            return -1;
5736        }
5737    }
5738
5739    @Override
5740    public int getFlagsForUid(int uid) {
5741        synchronized (mPackages) {
5742            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5743            if (obj instanceof SharedUserSetting) {
5744                final SharedUserSetting sus = (SharedUserSetting) obj;
5745                return sus.pkgFlags;
5746            } else if (obj instanceof PackageSetting) {
5747                final PackageSetting ps = (PackageSetting) obj;
5748                return ps.pkgFlags;
5749            }
5750        }
5751        return 0;
5752    }
5753
5754    @Override
5755    public int getPrivateFlagsForUid(int uid) {
5756        synchronized (mPackages) {
5757            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5758            if (obj instanceof SharedUserSetting) {
5759                final SharedUserSetting sus = (SharedUserSetting) obj;
5760                return sus.pkgPrivateFlags;
5761            } else if (obj instanceof PackageSetting) {
5762                final PackageSetting ps = (PackageSetting) obj;
5763                return ps.pkgPrivateFlags;
5764            }
5765        }
5766        return 0;
5767    }
5768
5769    @Override
5770    public boolean isUidPrivileged(int uid) {
5771        uid = UserHandle.getAppId(uid);
5772        // reader
5773        synchronized (mPackages) {
5774            Object obj = mSettings.getUserIdLPr(uid);
5775            if (obj instanceof SharedUserSetting) {
5776                final SharedUserSetting sus = (SharedUserSetting) obj;
5777                final Iterator<PackageSetting> it = sus.packages.iterator();
5778                while (it.hasNext()) {
5779                    if (it.next().isPrivileged()) {
5780                        return true;
5781                    }
5782                }
5783            } else if (obj instanceof PackageSetting) {
5784                final PackageSetting ps = (PackageSetting) obj;
5785                return ps.isPrivileged();
5786            }
5787        }
5788        return false;
5789    }
5790
5791    @Override
5792    public String[] getAppOpPermissionPackages(String permissionName) {
5793        synchronized (mPackages) {
5794            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5795            if (pkgs == null) {
5796                return null;
5797            }
5798            return pkgs.toArray(new String[pkgs.size()]);
5799        }
5800    }
5801
5802    @Override
5803    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5804            int flags, int userId) {
5805        return resolveIntentInternal(
5806                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5807    }
5808
5809    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5810            int flags, int userId, boolean resolveForStart) {
5811        try {
5812            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5813
5814            if (!sUserManager.exists(userId)) return null;
5815            final int callingUid = Binder.getCallingUid();
5816            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5817            enforceCrossUserPermission(callingUid, userId,
5818                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5819
5820            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5821            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5822                    flags, userId, resolveForStart);
5823            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5824
5825            final ResolveInfo bestChoice =
5826                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5827            return bestChoice;
5828        } finally {
5829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5830        }
5831    }
5832
5833    @Override
5834    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5835        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5836            throw new SecurityException(
5837                    "findPersistentPreferredActivity can only be run by the system");
5838        }
5839        if (!sUserManager.exists(userId)) {
5840            return null;
5841        }
5842        final int callingUid = Binder.getCallingUid();
5843        intent = updateIntentForResolve(intent);
5844        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5845        final int flags = updateFlagsForResolve(
5846                0, userId, intent, callingUid, false /*includeInstantApps*/);
5847        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5848                userId);
5849        synchronized (mPackages) {
5850            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5851                    userId);
5852        }
5853    }
5854
5855    @Override
5856    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5857            IntentFilter filter, int match, ComponentName activity) {
5858        final int userId = UserHandle.getCallingUserId();
5859        if (DEBUG_PREFERRED) {
5860            Log.v(TAG, "setLastChosenActivity intent=" + intent
5861                + " resolvedType=" + resolvedType
5862                + " flags=" + flags
5863                + " filter=" + filter
5864                + " match=" + match
5865                + " activity=" + activity);
5866            filter.dump(new PrintStreamPrinter(System.out), "    ");
5867        }
5868        intent.setComponent(null);
5869        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5870                userId);
5871        // Find any earlier preferred or last chosen entries and nuke them
5872        findPreferredActivity(intent, resolvedType,
5873                flags, query, 0, false, true, false, userId);
5874        // Add the new activity as the last chosen for this filter
5875        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5876                "Setting last chosen");
5877    }
5878
5879    @Override
5880    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5881        final int userId = UserHandle.getCallingUserId();
5882        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5883        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5884                userId);
5885        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5886                false, false, false, userId);
5887    }
5888
5889    /**
5890     * Returns whether or not instant apps have been disabled remotely.
5891     */
5892    private boolean isEphemeralDisabled() {
5893        return mEphemeralAppsDisabled;
5894    }
5895
5896    private boolean isInstantAppAllowed(
5897            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5898            boolean skipPackageCheck) {
5899        if (mInstantAppResolverConnection == null) {
5900            return false;
5901        }
5902        if (mInstantAppInstallerActivity == null) {
5903            return false;
5904        }
5905        if (intent.getComponent() != null) {
5906            return false;
5907        }
5908        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5909            return false;
5910        }
5911        if (!skipPackageCheck && intent.getPackage() != null) {
5912            return false;
5913        }
5914        final boolean isWebUri = hasWebURI(intent);
5915        if (!isWebUri || intent.getData().getHost() == null) {
5916            return false;
5917        }
5918        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5919        // Or if there's already an ephemeral app installed that handles the action
5920        synchronized (mPackages) {
5921            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5922            for (int n = 0; n < count; n++) {
5923                final ResolveInfo info = resolvedActivities.get(n);
5924                final String packageName = info.activityInfo.packageName;
5925                final PackageSetting ps = mSettings.mPackages.get(packageName);
5926                if (ps != null) {
5927                    // only check domain verification status if the app is not a browser
5928                    if (!info.handleAllWebDataURI) {
5929                        // Try to get the status from User settings first
5930                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5931                        final int status = (int) (packedStatus >> 32);
5932                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5933                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5934                            if (DEBUG_EPHEMERAL) {
5935                                Slog.v(TAG, "DENY instant app;"
5936                                    + " pkg: " + packageName + ", status: " + status);
5937                            }
5938                            return false;
5939                        }
5940                    }
5941                    if (ps.getInstantApp(userId)) {
5942                        if (DEBUG_EPHEMERAL) {
5943                            Slog.v(TAG, "DENY instant app installed;"
5944                                    + " pkg: " + packageName);
5945                        }
5946                        return false;
5947                    }
5948                }
5949            }
5950        }
5951        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5952        return true;
5953    }
5954
5955    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5956            Intent origIntent, String resolvedType, String callingPackage,
5957            Bundle verificationBundle, int userId) {
5958        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5959                new InstantAppRequest(responseObj, origIntent, resolvedType,
5960                        callingPackage, userId, verificationBundle));
5961        mHandler.sendMessage(msg);
5962    }
5963
5964    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5965            int flags, List<ResolveInfo> query, int userId) {
5966        if (query != null) {
5967            final int N = query.size();
5968            if (N == 1) {
5969                return query.get(0);
5970            } else if (N > 1) {
5971                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5972                // If there is more than one activity with the same priority,
5973                // then let the user decide between them.
5974                ResolveInfo r0 = query.get(0);
5975                ResolveInfo r1 = query.get(1);
5976                if (DEBUG_INTENT_MATCHING || debug) {
5977                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5978                            + r1.activityInfo.name + "=" + r1.priority);
5979                }
5980                // If the first activity has a higher priority, or a different
5981                // default, then it is always desirable to pick it.
5982                if (r0.priority != r1.priority
5983                        || r0.preferredOrder != r1.preferredOrder
5984                        || r0.isDefault != r1.isDefault) {
5985                    return query.get(0);
5986                }
5987                // If we have saved a preference for a preferred activity for
5988                // this Intent, use that.
5989                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5990                        flags, query, r0.priority, true, false, debug, userId);
5991                if (ri != null) {
5992                    return ri;
5993                }
5994                // If we have an ephemeral app, use it
5995                for (int i = 0; i < N; i++) {
5996                    ri = query.get(i);
5997                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5998                        final String packageName = ri.activityInfo.packageName;
5999                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6000                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6001                        final int status = (int)(packedStatus >> 32);
6002                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6003                            return ri;
6004                        }
6005                    }
6006                }
6007                ri = new ResolveInfo(mResolveInfo);
6008                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6009                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6010                // If all of the options come from the same package, show the application's
6011                // label and icon instead of the generic resolver's.
6012                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6013                // and then throw away the ResolveInfo itself, meaning that the caller loses
6014                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6015                // a fallback for this case; we only set the target package's resources on
6016                // the ResolveInfo, not the ActivityInfo.
6017                final String intentPackage = intent.getPackage();
6018                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6019                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6020                    ri.resolvePackageName = intentPackage;
6021                    if (userNeedsBadging(userId)) {
6022                        ri.noResourceId = true;
6023                    } else {
6024                        ri.icon = appi.icon;
6025                    }
6026                    ri.iconResourceId = appi.icon;
6027                    ri.labelRes = appi.labelRes;
6028                }
6029                ri.activityInfo.applicationInfo = new ApplicationInfo(
6030                        ri.activityInfo.applicationInfo);
6031                if (userId != 0) {
6032                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6033                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6034                }
6035                // Make sure that the resolver is displayable in car mode
6036                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6037                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6038                return ri;
6039            }
6040        }
6041        return null;
6042    }
6043
6044    /**
6045     * Return true if the given list is not empty and all of its contents have
6046     * an activityInfo with the given package name.
6047     */
6048    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6049        if (ArrayUtils.isEmpty(list)) {
6050            return false;
6051        }
6052        for (int i = 0, N = list.size(); i < N; i++) {
6053            final ResolveInfo ri = list.get(i);
6054            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6055            if (ai == null || !packageName.equals(ai.packageName)) {
6056                return false;
6057            }
6058        }
6059        return true;
6060    }
6061
6062    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6063            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6064        final int N = query.size();
6065        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6066                .get(userId);
6067        // Get the list of persistent preferred activities that handle the intent
6068        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6069        List<PersistentPreferredActivity> pprefs = ppir != null
6070                ? ppir.queryIntent(intent, resolvedType,
6071                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6072                        userId)
6073                : null;
6074        if (pprefs != null && pprefs.size() > 0) {
6075            final int M = pprefs.size();
6076            for (int i=0; i<M; i++) {
6077                final PersistentPreferredActivity ppa = pprefs.get(i);
6078                if (DEBUG_PREFERRED || debug) {
6079                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6080                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6081                            + "\n  component=" + ppa.mComponent);
6082                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6083                }
6084                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6085                        flags | MATCH_DISABLED_COMPONENTS, userId);
6086                if (DEBUG_PREFERRED || debug) {
6087                    Slog.v(TAG, "Found persistent preferred activity:");
6088                    if (ai != null) {
6089                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6090                    } else {
6091                        Slog.v(TAG, "  null");
6092                    }
6093                }
6094                if (ai == null) {
6095                    // This previously registered persistent preferred activity
6096                    // component is no longer known. Ignore it and do NOT remove it.
6097                    continue;
6098                }
6099                for (int j=0; j<N; j++) {
6100                    final ResolveInfo ri = query.get(j);
6101                    if (!ri.activityInfo.applicationInfo.packageName
6102                            .equals(ai.applicationInfo.packageName)) {
6103                        continue;
6104                    }
6105                    if (!ri.activityInfo.name.equals(ai.name)) {
6106                        continue;
6107                    }
6108                    //  Found a persistent preference that can handle the intent.
6109                    if (DEBUG_PREFERRED || debug) {
6110                        Slog.v(TAG, "Returning persistent preferred activity: " +
6111                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6112                    }
6113                    return ri;
6114                }
6115            }
6116        }
6117        return null;
6118    }
6119
6120    // TODO: handle preferred activities missing while user has amnesia
6121    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6122            List<ResolveInfo> query, int priority, boolean always,
6123            boolean removeMatches, boolean debug, int userId) {
6124        if (!sUserManager.exists(userId)) return null;
6125        final int callingUid = Binder.getCallingUid();
6126        flags = updateFlagsForResolve(
6127                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6128        intent = updateIntentForResolve(intent);
6129        // writer
6130        synchronized (mPackages) {
6131            // Try to find a matching persistent preferred activity.
6132            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6133                    debug, userId);
6134
6135            // If a persistent preferred activity matched, use it.
6136            if (pri != null) {
6137                return pri;
6138            }
6139
6140            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6141            // Get the list of preferred activities that handle the intent
6142            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6143            List<PreferredActivity> prefs = pir != null
6144                    ? pir.queryIntent(intent, resolvedType,
6145                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6146                            userId)
6147                    : null;
6148            if (prefs != null && prefs.size() > 0) {
6149                boolean changed = false;
6150                try {
6151                    // First figure out how good the original match set is.
6152                    // We will only allow preferred activities that came
6153                    // from the same match quality.
6154                    int match = 0;
6155
6156                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6157
6158                    final int N = query.size();
6159                    for (int j=0; j<N; j++) {
6160                        final ResolveInfo ri = query.get(j);
6161                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6162                                + ": 0x" + Integer.toHexString(match));
6163                        if (ri.match > match) {
6164                            match = ri.match;
6165                        }
6166                    }
6167
6168                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6169                            + Integer.toHexString(match));
6170
6171                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6172                    final int M = prefs.size();
6173                    for (int i=0; i<M; i++) {
6174                        final PreferredActivity pa = prefs.get(i);
6175                        if (DEBUG_PREFERRED || debug) {
6176                            Slog.v(TAG, "Checking PreferredActivity ds="
6177                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6178                                    + "\n  component=" + pa.mPref.mComponent);
6179                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6180                        }
6181                        if (pa.mPref.mMatch != match) {
6182                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6183                                    + Integer.toHexString(pa.mPref.mMatch));
6184                            continue;
6185                        }
6186                        // If it's not an "always" type preferred activity and that's what we're
6187                        // looking for, skip it.
6188                        if (always && !pa.mPref.mAlways) {
6189                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6190                            continue;
6191                        }
6192                        final ActivityInfo ai = getActivityInfo(
6193                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6194                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6195                                userId);
6196                        if (DEBUG_PREFERRED || debug) {
6197                            Slog.v(TAG, "Found preferred activity:");
6198                            if (ai != null) {
6199                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6200                            } else {
6201                                Slog.v(TAG, "  null");
6202                            }
6203                        }
6204                        if (ai == null) {
6205                            // This previously registered preferred activity
6206                            // component is no longer known.  Most likely an update
6207                            // to the app was installed and in the new version this
6208                            // component no longer exists.  Clean it up by removing
6209                            // it from the preferred activities list, and skip it.
6210                            Slog.w(TAG, "Removing dangling preferred activity: "
6211                                    + pa.mPref.mComponent);
6212                            pir.removeFilter(pa);
6213                            changed = true;
6214                            continue;
6215                        }
6216                        for (int j=0; j<N; j++) {
6217                            final ResolveInfo ri = query.get(j);
6218                            if (!ri.activityInfo.applicationInfo.packageName
6219                                    .equals(ai.applicationInfo.packageName)) {
6220                                continue;
6221                            }
6222                            if (!ri.activityInfo.name.equals(ai.name)) {
6223                                continue;
6224                            }
6225
6226                            if (removeMatches) {
6227                                pir.removeFilter(pa);
6228                                changed = true;
6229                                if (DEBUG_PREFERRED) {
6230                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6231                                }
6232                                break;
6233                            }
6234
6235                            // Okay we found a previously set preferred or last chosen app.
6236                            // If the result set is different from when this
6237                            // was created, we need to clear it and re-ask the
6238                            // user their preference, if we're looking for an "always" type entry.
6239                            if (always && !pa.mPref.sameSet(query)) {
6240                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6241                                        + intent + " type " + resolvedType);
6242                                if (DEBUG_PREFERRED) {
6243                                    Slog.v(TAG, "Removing preferred activity since set changed "
6244                                            + pa.mPref.mComponent);
6245                                }
6246                                pir.removeFilter(pa);
6247                                // Re-add the filter as a "last chosen" entry (!always)
6248                                PreferredActivity lastChosen = new PreferredActivity(
6249                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6250                                pir.addFilter(lastChosen);
6251                                changed = true;
6252                                return null;
6253                            }
6254
6255                            // Yay! Either the set matched or we're looking for the last chosen
6256                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6257                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6258                            return ri;
6259                        }
6260                    }
6261                } finally {
6262                    if (changed) {
6263                        if (DEBUG_PREFERRED) {
6264                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6265                        }
6266                        scheduleWritePackageRestrictionsLocked(userId);
6267                    }
6268                }
6269            }
6270        }
6271        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6272        return null;
6273    }
6274
6275    /*
6276     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6277     */
6278    @Override
6279    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6280            int targetUserId) {
6281        mContext.enforceCallingOrSelfPermission(
6282                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6283        List<CrossProfileIntentFilter> matches =
6284                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6285        if (matches != null) {
6286            int size = matches.size();
6287            for (int i = 0; i < size; i++) {
6288                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6289            }
6290        }
6291        if (hasWebURI(intent)) {
6292            // cross-profile app linking works only towards the parent.
6293            final int callingUid = Binder.getCallingUid();
6294            final UserInfo parent = getProfileParent(sourceUserId);
6295            synchronized(mPackages) {
6296                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6297                        false /*includeInstantApps*/);
6298                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6299                        intent, resolvedType, flags, sourceUserId, parent.id);
6300                return xpDomainInfo != null;
6301            }
6302        }
6303        return false;
6304    }
6305
6306    private UserInfo getProfileParent(int userId) {
6307        final long identity = Binder.clearCallingIdentity();
6308        try {
6309            return sUserManager.getProfileParent(userId);
6310        } finally {
6311            Binder.restoreCallingIdentity(identity);
6312        }
6313    }
6314
6315    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6316            String resolvedType, int userId) {
6317        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6318        if (resolver != null) {
6319            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6320        }
6321        return null;
6322    }
6323
6324    @Override
6325    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6326            String resolvedType, int flags, int userId) {
6327        try {
6328            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6329
6330            return new ParceledListSlice<>(
6331                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6332        } finally {
6333            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6334        }
6335    }
6336
6337    /**
6338     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6339     * instant, returns {@code null}.
6340     */
6341    private String getInstantAppPackageName(int callingUid) {
6342        // If the caller is an isolated app use the owner's uid for the lookup.
6343        if (Process.isIsolated(callingUid)) {
6344            callingUid = mIsolatedOwners.get(callingUid);
6345        }
6346        final int appId = UserHandle.getAppId(callingUid);
6347        synchronized (mPackages) {
6348            final Object obj = mSettings.getUserIdLPr(appId);
6349            if (obj instanceof PackageSetting) {
6350                final PackageSetting ps = (PackageSetting) obj;
6351                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6352                return isInstantApp ? ps.pkg.packageName : null;
6353            }
6354        }
6355        return null;
6356    }
6357
6358    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6359            String resolvedType, int flags, int userId) {
6360        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6361    }
6362
6363    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6364            String resolvedType, int flags, int userId, boolean resolveForStart) {
6365        if (!sUserManager.exists(userId)) return Collections.emptyList();
6366        final int callingUid = Binder.getCallingUid();
6367        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6368        enforceCrossUserPermission(callingUid, userId,
6369                false /* requireFullPermission */, false /* checkShell */,
6370                "query intent activities");
6371        final String pkgName = intent.getPackage();
6372        ComponentName comp = intent.getComponent();
6373        if (comp == null) {
6374            if (intent.getSelector() != null) {
6375                intent = intent.getSelector();
6376                comp = intent.getComponent();
6377            }
6378        }
6379
6380        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6381                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6382        if (comp != null) {
6383            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6384            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6385            if (ai != null) {
6386                // When specifying an explicit component, we prevent the activity from being
6387                // used when either 1) the calling package is normal and the activity is within
6388                // an ephemeral application or 2) the calling package is ephemeral and the
6389                // activity is not visible to ephemeral applications.
6390                final boolean matchInstantApp =
6391                        (flags & PackageManager.MATCH_INSTANT) != 0;
6392                final boolean matchVisibleToInstantAppOnly =
6393                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6394                final boolean matchExplicitlyVisibleOnly =
6395                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6396                final boolean isCallerInstantApp =
6397                        instantAppPkgName != null;
6398                final boolean isTargetSameInstantApp =
6399                        comp.getPackageName().equals(instantAppPkgName);
6400                final boolean isTargetInstantApp =
6401                        (ai.applicationInfo.privateFlags
6402                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6403                final boolean isTargetVisibleToInstantApp =
6404                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6405                final boolean isTargetExplicitlyVisibleToInstantApp =
6406                        isTargetVisibleToInstantApp
6407                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6408                final boolean isTargetHiddenFromInstantApp =
6409                        !isTargetVisibleToInstantApp
6410                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6411                final boolean blockResolution =
6412                        !isTargetSameInstantApp
6413                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6414                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6415                                        && isTargetHiddenFromInstantApp));
6416                if (!blockResolution) {
6417                    final ResolveInfo ri = new ResolveInfo();
6418                    ri.activityInfo = ai;
6419                    list.add(ri);
6420                }
6421            }
6422            return applyPostResolutionFilter(list, instantAppPkgName);
6423        }
6424
6425        // reader
6426        boolean sortResult = false;
6427        boolean addEphemeral = false;
6428        List<ResolveInfo> result;
6429        final boolean ephemeralDisabled = isEphemeralDisabled();
6430        synchronized (mPackages) {
6431            if (pkgName == null) {
6432                List<CrossProfileIntentFilter> matchingFilters =
6433                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6434                // Check for results that need to skip the current profile.
6435                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6436                        resolvedType, flags, userId);
6437                if (xpResolveInfo != null) {
6438                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6439                    xpResult.add(xpResolveInfo);
6440                    return applyPostResolutionFilter(
6441                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6442                }
6443
6444                // Check for results in the current profile.
6445                result = filterIfNotSystemUser(mActivities.queryIntent(
6446                        intent, resolvedType, flags, userId), userId);
6447                addEphemeral = !ephemeralDisabled
6448                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6449                // Check for cross profile results.
6450                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6451                xpResolveInfo = queryCrossProfileIntents(
6452                        matchingFilters, intent, resolvedType, flags, userId,
6453                        hasNonNegativePriorityResult);
6454                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6455                    boolean isVisibleToUser = filterIfNotSystemUser(
6456                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6457                    if (isVisibleToUser) {
6458                        result.add(xpResolveInfo);
6459                        sortResult = true;
6460                    }
6461                }
6462                if (hasWebURI(intent)) {
6463                    CrossProfileDomainInfo xpDomainInfo = null;
6464                    final UserInfo parent = getProfileParent(userId);
6465                    if (parent != null) {
6466                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6467                                flags, userId, parent.id);
6468                    }
6469                    if (xpDomainInfo != null) {
6470                        if (xpResolveInfo != null) {
6471                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6472                            // in the result.
6473                            result.remove(xpResolveInfo);
6474                        }
6475                        if (result.size() == 0 && !addEphemeral) {
6476                            // No result in current profile, but found candidate in parent user.
6477                            // And we are not going to add emphemeral app, so we can return the
6478                            // result straight away.
6479                            result.add(xpDomainInfo.resolveInfo);
6480                            return applyPostResolutionFilter(result, instantAppPkgName);
6481                        }
6482                    } else if (result.size() <= 1 && !addEphemeral) {
6483                        // No result in parent user and <= 1 result in current profile, and we
6484                        // are not going to add emphemeral app, so we can return the result without
6485                        // further processing.
6486                        return applyPostResolutionFilter(result, instantAppPkgName);
6487                    }
6488                    // We have more than one candidate (combining results from current and parent
6489                    // profile), so we need filtering and sorting.
6490                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6491                            intent, flags, result, xpDomainInfo, userId);
6492                    sortResult = true;
6493                }
6494            } else {
6495                final PackageParser.Package pkg = mPackages.get(pkgName);
6496                if (pkg != null) {
6497                    return applyPostResolutionFilter(filterIfNotSystemUser(
6498                            mActivities.queryIntentForPackage(
6499                                    intent, resolvedType, flags, pkg.activities, userId),
6500                            userId), instantAppPkgName);
6501                } else {
6502                    // the caller wants to resolve for a particular package; however, there
6503                    // were no installed results, so, try to find an ephemeral result
6504                    addEphemeral = !ephemeralDisabled
6505                            && isInstantAppAllowed(
6506                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6507                    result = new ArrayList<ResolveInfo>();
6508                }
6509            }
6510        }
6511        if (addEphemeral) {
6512            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6513        }
6514        if (sortResult) {
6515            Collections.sort(result, mResolvePrioritySorter);
6516        }
6517        return applyPostResolutionFilter(result, instantAppPkgName);
6518    }
6519
6520    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6521            String resolvedType, int flags, int userId) {
6522        // first, check to see if we've got an instant app already installed
6523        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6524        ResolveInfo localInstantApp = null;
6525        boolean blockResolution = false;
6526        if (!alreadyResolvedLocally) {
6527            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6528                    flags
6529                        | PackageManager.GET_RESOLVED_FILTER
6530                        | PackageManager.MATCH_INSTANT
6531                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6532                    userId);
6533            for (int i = instantApps.size() - 1; i >= 0; --i) {
6534                final ResolveInfo info = instantApps.get(i);
6535                final String packageName = info.activityInfo.packageName;
6536                final PackageSetting ps = mSettings.mPackages.get(packageName);
6537                if (ps.getInstantApp(userId)) {
6538                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6539                    final int status = (int)(packedStatus >> 32);
6540                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6541                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6542                        // there's a local instant application installed, but, the user has
6543                        // chosen to never use it; skip resolution and don't acknowledge
6544                        // an instant application is even available
6545                        if (DEBUG_EPHEMERAL) {
6546                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6547                        }
6548                        blockResolution = true;
6549                        break;
6550                    } else {
6551                        // we have a locally installed instant application; skip resolution
6552                        // but acknowledge there's an instant application available
6553                        if (DEBUG_EPHEMERAL) {
6554                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6555                        }
6556                        localInstantApp = info;
6557                        break;
6558                    }
6559                }
6560            }
6561        }
6562        // no app installed, let's see if one's available
6563        AuxiliaryResolveInfo auxiliaryResponse = null;
6564        if (!blockResolution) {
6565            if (localInstantApp == null) {
6566                // we don't have an instant app locally, resolve externally
6567                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6568                final InstantAppRequest requestObject = new InstantAppRequest(
6569                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6570                        null /*callingPackage*/, userId, null /*verificationBundle*/);
6571                auxiliaryResponse =
6572                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6573                                mContext, mInstantAppResolverConnection, requestObject);
6574                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6575            } else {
6576                // we have an instant application locally, but, we can't admit that since
6577                // callers shouldn't be able to determine prior browsing. create a dummy
6578                // auxiliary response so the downstream code behaves as if there's an
6579                // instant application available externally. when it comes time to start
6580                // the instant application, we'll do the right thing.
6581                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6582                auxiliaryResponse = new AuxiliaryResolveInfo(
6583                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
6584            }
6585        }
6586        if (auxiliaryResponse != null) {
6587            if (DEBUG_EPHEMERAL) {
6588                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6589            }
6590            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6591            final PackageSetting ps =
6592                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6593            if (ps != null) {
6594                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6595                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6596                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6597                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6598                // make sure this resolver is the default
6599                ephemeralInstaller.isDefault = true;
6600                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6601                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6602                // add a non-generic filter
6603                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6604                ephemeralInstaller.filter.addDataPath(
6605                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6606                ephemeralInstaller.isInstantAppAvailable = true;
6607                result.add(ephemeralInstaller);
6608            }
6609        }
6610        return result;
6611    }
6612
6613    private static class CrossProfileDomainInfo {
6614        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6615        ResolveInfo resolveInfo;
6616        /* Best domain verification status of the activities found in the other profile */
6617        int bestDomainVerificationStatus;
6618    }
6619
6620    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6621            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6622        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6623                sourceUserId)) {
6624            return null;
6625        }
6626        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6627                resolvedType, flags, parentUserId);
6628
6629        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6630            return null;
6631        }
6632        CrossProfileDomainInfo result = null;
6633        int size = resultTargetUser.size();
6634        for (int i = 0; i < size; i++) {
6635            ResolveInfo riTargetUser = resultTargetUser.get(i);
6636            // Intent filter verification is only for filters that specify a host. So don't return
6637            // those that handle all web uris.
6638            if (riTargetUser.handleAllWebDataURI) {
6639                continue;
6640            }
6641            String packageName = riTargetUser.activityInfo.packageName;
6642            PackageSetting ps = mSettings.mPackages.get(packageName);
6643            if (ps == null) {
6644                continue;
6645            }
6646            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6647            int status = (int)(verificationState >> 32);
6648            if (result == null) {
6649                result = new CrossProfileDomainInfo();
6650                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6651                        sourceUserId, parentUserId);
6652                result.bestDomainVerificationStatus = status;
6653            } else {
6654                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6655                        result.bestDomainVerificationStatus);
6656            }
6657        }
6658        // Don't consider matches with status NEVER across profiles.
6659        if (result != null && result.bestDomainVerificationStatus
6660                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6661            return null;
6662        }
6663        return result;
6664    }
6665
6666    /**
6667     * Verification statuses are ordered from the worse to the best, except for
6668     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6669     */
6670    private int bestDomainVerificationStatus(int status1, int status2) {
6671        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6672            return status2;
6673        }
6674        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6675            return status1;
6676        }
6677        return (int) MathUtils.max(status1, status2);
6678    }
6679
6680    private boolean isUserEnabled(int userId) {
6681        long callingId = Binder.clearCallingIdentity();
6682        try {
6683            UserInfo userInfo = sUserManager.getUserInfo(userId);
6684            return userInfo != null && userInfo.isEnabled();
6685        } finally {
6686            Binder.restoreCallingIdentity(callingId);
6687        }
6688    }
6689
6690    /**
6691     * Filter out activities with systemUserOnly flag set, when current user is not System.
6692     *
6693     * @return filtered list
6694     */
6695    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6696        if (userId == UserHandle.USER_SYSTEM) {
6697            return resolveInfos;
6698        }
6699        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6700            ResolveInfo info = resolveInfos.get(i);
6701            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6702                resolveInfos.remove(i);
6703            }
6704        }
6705        return resolveInfos;
6706    }
6707
6708    /**
6709     * Filters out ephemeral activities.
6710     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6711     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6712     *
6713     * @param resolveInfos The pre-filtered list of resolved activities
6714     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6715     *          is performed.
6716     * @return A filtered list of resolved activities.
6717     */
6718    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6719            String ephemeralPkgName) {
6720        // TODO: When adding on-demand split support for non-instant apps, remove this check
6721        // and always apply post filtering
6722        if (ephemeralPkgName == null) {
6723            return resolveInfos;
6724        }
6725        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6726            final ResolveInfo info = resolveInfos.get(i);
6727            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6728            // allow activities that are defined in the provided package
6729            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6730                if (info.activityInfo.splitName != null
6731                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6732                                info.activityInfo.splitName)) {
6733                    // requested activity is defined in a split that hasn't been installed yet.
6734                    // add the installer to the resolve list
6735                    if (DEBUG_EPHEMERAL) {
6736                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6737                    }
6738                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6739                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6740                            info.activityInfo.packageName, info.activityInfo.splitName,
6741                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
6742                    // make sure this resolver is the default
6743                    installerInfo.isDefault = true;
6744                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6745                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6746                    // add a non-generic filter
6747                    installerInfo.filter = new IntentFilter();
6748                    // load resources from the correct package
6749                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6750                    resolveInfos.set(i, installerInfo);
6751                }
6752                continue;
6753            }
6754            // allow activities that have been explicitly exposed to ephemeral apps
6755            if (!isEphemeralApp
6756                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6757                continue;
6758            }
6759            resolveInfos.remove(i);
6760        }
6761        return resolveInfos;
6762    }
6763
6764    /**
6765     * @param resolveInfos list of resolve infos in descending priority order
6766     * @return if the list contains a resolve info with non-negative priority
6767     */
6768    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6769        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6770    }
6771
6772    private static boolean hasWebURI(Intent intent) {
6773        if (intent.getData() == null) {
6774            return false;
6775        }
6776        final String scheme = intent.getScheme();
6777        if (TextUtils.isEmpty(scheme)) {
6778            return false;
6779        }
6780        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6781    }
6782
6783    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6784            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6785            int userId) {
6786        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6787
6788        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6789            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6790                    candidates.size());
6791        }
6792
6793        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6794        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6795        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6796        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6797        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6798        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6799
6800        synchronized (mPackages) {
6801            final int count = candidates.size();
6802            // First, try to use linked apps. Partition the candidates into four lists:
6803            // one for the final results, one for the "do not use ever", one for "undefined status"
6804            // and finally one for "browser app type".
6805            for (int n=0; n<count; n++) {
6806                ResolveInfo info = candidates.get(n);
6807                String packageName = info.activityInfo.packageName;
6808                PackageSetting ps = mSettings.mPackages.get(packageName);
6809                if (ps != null) {
6810                    // Add to the special match all list (Browser use case)
6811                    if (info.handleAllWebDataURI) {
6812                        matchAllList.add(info);
6813                        continue;
6814                    }
6815                    // Try to get the status from User settings first
6816                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6817                    int status = (int)(packedStatus >> 32);
6818                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6819                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6820                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6821                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6822                                    + " : linkgen=" + linkGeneration);
6823                        }
6824                        // Use link-enabled generation as preferredOrder, i.e.
6825                        // prefer newly-enabled over earlier-enabled.
6826                        info.preferredOrder = linkGeneration;
6827                        alwaysList.add(info);
6828                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6829                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6830                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6831                        }
6832                        neverList.add(info);
6833                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6834                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6835                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6836                        }
6837                        alwaysAskList.add(info);
6838                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6839                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6840                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6841                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6842                        }
6843                        undefinedList.add(info);
6844                    }
6845                }
6846            }
6847
6848            // We'll want to include browser possibilities in a few cases
6849            boolean includeBrowser = false;
6850
6851            // First try to add the "always" resolution(s) for the current user, if any
6852            if (alwaysList.size() > 0) {
6853                result.addAll(alwaysList);
6854            } else {
6855                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6856                result.addAll(undefinedList);
6857                // Maybe add one for the other profile.
6858                if (xpDomainInfo != null && (
6859                        xpDomainInfo.bestDomainVerificationStatus
6860                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6861                    result.add(xpDomainInfo.resolveInfo);
6862                }
6863                includeBrowser = true;
6864            }
6865
6866            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6867            // If there were 'always' entries their preferred order has been set, so we also
6868            // back that off to make the alternatives equivalent
6869            if (alwaysAskList.size() > 0) {
6870                for (ResolveInfo i : result) {
6871                    i.preferredOrder = 0;
6872                }
6873                result.addAll(alwaysAskList);
6874                includeBrowser = true;
6875            }
6876
6877            if (includeBrowser) {
6878                // Also add browsers (all of them or only the default one)
6879                if (DEBUG_DOMAIN_VERIFICATION) {
6880                    Slog.v(TAG, "   ...including browsers in candidate set");
6881                }
6882                if ((matchFlags & MATCH_ALL) != 0) {
6883                    result.addAll(matchAllList);
6884                } else {
6885                    // Browser/generic handling case.  If there's a default browser, go straight
6886                    // to that (but only if there is no other higher-priority match).
6887                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6888                    int maxMatchPrio = 0;
6889                    ResolveInfo defaultBrowserMatch = null;
6890                    final int numCandidates = matchAllList.size();
6891                    for (int n = 0; n < numCandidates; n++) {
6892                        ResolveInfo info = matchAllList.get(n);
6893                        // track the highest overall match priority...
6894                        if (info.priority > maxMatchPrio) {
6895                            maxMatchPrio = info.priority;
6896                        }
6897                        // ...and the highest-priority default browser match
6898                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6899                            if (defaultBrowserMatch == null
6900                                    || (defaultBrowserMatch.priority < info.priority)) {
6901                                if (debug) {
6902                                    Slog.v(TAG, "Considering default browser match " + info);
6903                                }
6904                                defaultBrowserMatch = info;
6905                            }
6906                        }
6907                    }
6908                    if (defaultBrowserMatch != null
6909                            && defaultBrowserMatch.priority >= maxMatchPrio
6910                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6911                    {
6912                        if (debug) {
6913                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6914                        }
6915                        result.add(defaultBrowserMatch);
6916                    } else {
6917                        result.addAll(matchAllList);
6918                    }
6919                }
6920
6921                // If there is nothing selected, add all candidates and remove the ones that the user
6922                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6923                if (result.size() == 0) {
6924                    result.addAll(candidates);
6925                    result.removeAll(neverList);
6926                }
6927            }
6928        }
6929        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6930            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6931                    result.size());
6932            for (ResolveInfo info : result) {
6933                Slog.v(TAG, "  + " + info.activityInfo);
6934            }
6935        }
6936        return result;
6937    }
6938
6939    // Returns a packed value as a long:
6940    //
6941    // high 'int'-sized word: link status: undefined/ask/never/always.
6942    // low 'int'-sized word: relative priority among 'always' results.
6943    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6944        long result = ps.getDomainVerificationStatusForUser(userId);
6945        // if none available, get the master status
6946        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6947            if (ps.getIntentFilterVerificationInfo() != null) {
6948                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6949            }
6950        }
6951        return result;
6952    }
6953
6954    private ResolveInfo querySkipCurrentProfileIntents(
6955            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6956            int flags, int sourceUserId) {
6957        if (matchingFilters != null) {
6958            int size = matchingFilters.size();
6959            for (int i = 0; i < size; i ++) {
6960                CrossProfileIntentFilter filter = matchingFilters.get(i);
6961                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6962                    // Checking if there are activities in the target user that can handle the
6963                    // intent.
6964                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6965                            resolvedType, flags, sourceUserId);
6966                    if (resolveInfo != null) {
6967                        return resolveInfo;
6968                    }
6969                }
6970            }
6971        }
6972        return null;
6973    }
6974
6975    // Return matching ResolveInfo in target user if any.
6976    private ResolveInfo queryCrossProfileIntents(
6977            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6978            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6979        if (matchingFilters != null) {
6980            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6981            // match the same intent. For performance reasons, it is better not to
6982            // run queryIntent twice for the same userId
6983            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6984            int size = matchingFilters.size();
6985            for (int i = 0; i < size; i++) {
6986                CrossProfileIntentFilter filter = matchingFilters.get(i);
6987                int targetUserId = filter.getTargetUserId();
6988                boolean skipCurrentProfile =
6989                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6990                boolean skipCurrentProfileIfNoMatchFound =
6991                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6992                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6993                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6994                    // Checking if there are activities in the target user that can handle the
6995                    // intent.
6996                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6997                            resolvedType, flags, sourceUserId);
6998                    if (resolveInfo != null) return resolveInfo;
6999                    alreadyTriedUserIds.put(targetUserId, true);
7000                }
7001            }
7002        }
7003        return null;
7004    }
7005
7006    /**
7007     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7008     * will forward the intent to the filter's target user.
7009     * Otherwise, returns null.
7010     */
7011    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7012            String resolvedType, int flags, int sourceUserId) {
7013        int targetUserId = filter.getTargetUserId();
7014        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7015                resolvedType, flags, targetUserId);
7016        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7017            // If all the matches in the target profile are suspended, return null.
7018            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7019                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7020                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7021                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7022                            targetUserId);
7023                }
7024            }
7025        }
7026        return null;
7027    }
7028
7029    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7030            int sourceUserId, int targetUserId) {
7031        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7032        long ident = Binder.clearCallingIdentity();
7033        boolean targetIsProfile;
7034        try {
7035            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7036        } finally {
7037            Binder.restoreCallingIdentity(ident);
7038        }
7039        String className;
7040        if (targetIsProfile) {
7041            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7042        } else {
7043            className = FORWARD_INTENT_TO_PARENT;
7044        }
7045        ComponentName forwardingActivityComponentName = new ComponentName(
7046                mAndroidApplication.packageName, className);
7047        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7048                sourceUserId);
7049        if (!targetIsProfile) {
7050            forwardingActivityInfo.showUserIcon = targetUserId;
7051            forwardingResolveInfo.noResourceId = true;
7052        }
7053        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7054        forwardingResolveInfo.priority = 0;
7055        forwardingResolveInfo.preferredOrder = 0;
7056        forwardingResolveInfo.match = 0;
7057        forwardingResolveInfo.isDefault = true;
7058        forwardingResolveInfo.filter = filter;
7059        forwardingResolveInfo.targetUserId = targetUserId;
7060        return forwardingResolveInfo;
7061    }
7062
7063    @Override
7064    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7065            Intent[] specifics, String[] specificTypes, Intent intent,
7066            String resolvedType, int flags, int userId) {
7067        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7068                specificTypes, intent, resolvedType, flags, userId));
7069    }
7070
7071    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7072            Intent[] specifics, String[] specificTypes, Intent intent,
7073            String resolvedType, int flags, int userId) {
7074        if (!sUserManager.exists(userId)) return Collections.emptyList();
7075        final int callingUid = Binder.getCallingUid();
7076        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7077                false /*includeInstantApps*/);
7078        enforceCrossUserPermission(callingUid, userId,
7079                false /*requireFullPermission*/, false /*checkShell*/,
7080                "query intent activity options");
7081        final String resultsAction = intent.getAction();
7082
7083        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7084                | PackageManager.GET_RESOLVED_FILTER, userId);
7085
7086        if (DEBUG_INTENT_MATCHING) {
7087            Log.v(TAG, "Query " + intent + ": " + results);
7088        }
7089
7090        int specificsPos = 0;
7091        int N;
7092
7093        // todo: note that the algorithm used here is O(N^2).  This
7094        // isn't a problem in our current environment, but if we start running
7095        // into situations where we have more than 5 or 10 matches then this
7096        // should probably be changed to something smarter...
7097
7098        // First we go through and resolve each of the specific items
7099        // that were supplied, taking care of removing any corresponding
7100        // duplicate items in the generic resolve list.
7101        if (specifics != null) {
7102            for (int i=0; i<specifics.length; i++) {
7103                final Intent sintent = specifics[i];
7104                if (sintent == null) {
7105                    continue;
7106                }
7107
7108                if (DEBUG_INTENT_MATCHING) {
7109                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7110                }
7111
7112                String action = sintent.getAction();
7113                if (resultsAction != null && resultsAction.equals(action)) {
7114                    // If this action was explicitly requested, then don't
7115                    // remove things that have it.
7116                    action = null;
7117                }
7118
7119                ResolveInfo ri = null;
7120                ActivityInfo ai = null;
7121
7122                ComponentName comp = sintent.getComponent();
7123                if (comp == null) {
7124                    ri = resolveIntent(
7125                        sintent,
7126                        specificTypes != null ? specificTypes[i] : null,
7127                            flags, userId);
7128                    if (ri == null) {
7129                        continue;
7130                    }
7131                    if (ri == mResolveInfo) {
7132                        // ACK!  Must do something better with this.
7133                    }
7134                    ai = ri.activityInfo;
7135                    comp = new ComponentName(ai.applicationInfo.packageName,
7136                            ai.name);
7137                } else {
7138                    ai = getActivityInfo(comp, flags, userId);
7139                    if (ai == null) {
7140                        continue;
7141                    }
7142                }
7143
7144                // Look for any generic query activities that are duplicates
7145                // of this specific one, and remove them from the results.
7146                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7147                N = results.size();
7148                int j;
7149                for (j=specificsPos; j<N; j++) {
7150                    ResolveInfo sri = results.get(j);
7151                    if ((sri.activityInfo.name.equals(comp.getClassName())
7152                            && sri.activityInfo.applicationInfo.packageName.equals(
7153                                    comp.getPackageName()))
7154                        || (action != null && sri.filter.matchAction(action))) {
7155                        results.remove(j);
7156                        if (DEBUG_INTENT_MATCHING) Log.v(
7157                            TAG, "Removing duplicate item from " + j
7158                            + " due to specific " + specificsPos);
7159                        if (ri == null) {
7160                            ri = sri;
7161                        }
7162                        j--;
7163                        N--;
7164                    }
7165                }
7166
7167                // Add this specific item to its proper place.
7168                if (ri == null) {
7169                    ri = new ResolveInfo();
7170                    ri.activityInfo = ai;
7171                }
7172                results.add(specificsPos, ri);
7173                ri.specificIndex = i;
7174                specificsPos++;
7175            }
7176        }
7177
7178        // Now we go through the remaining generic results and remove any
7179        // duplicate actions that are found here.
7180        N = results.size();
7181        for (int i=specificsPos; i<N-1; i++) {
7182            final ResolveInfo rii = results.get(i);
7183            if (rii.filter == null) {
7184                continue;
7185            }
7186
7187            // Iterate over all of the actions of this result's intent
7188            // filter...  typically this should be just one.
7189            final Iterator<String> it = rii.filter.actionsIterator();
7190            if (it == null) {
7191                continue;
7192            }
7193            while (it.hasNext()) {
7194                final String action = it.next();
7195                if (resultsAction != null && resultsAction.equals(action)) {
7196                    // If this action was explicitly requested, then don't
7197                    // remove things that have it.
7198                    continue;
7199                }
7200                for (int j=i+1; j<N; j++) {
7201                    final ResolveInfo rij = results.get(j);
7202                    if (rij.filter != null && rij.filter.hasAction(action)) {
7203                        results.remove(j);
7204                        if (DEBUG_INTENT_MATCHING) Log.v(
7205                            TAG, "Removing duplicate item from " + j
7206                            + " due to action " + action + " at " + i);
7207                        j--;
7208                        N--;
7209                    }
7210                }
7211            }
7212
7213            // If the caller didn't request filter information, drop it now
7214            // so we don't have to marshall/unmarshall it.
7215            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7216                rii.filter = null;
7217            }
7218        }
7219
7220        // Filter out the caller activity if so requested.
7221        if (caller != null) {
7222            N = results.size();
7223            for (int i=0; i<N; i++) {
7224                ActivityInfo ainfo = results.get(i).activityInfo;
7225                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7226                        && caller.getClassName().equals(ainfo.name)) {
7227                    results.remove(i);
7228                    break;
7229                }
7230            }
7231        }
7232
7233        // If the caller didn't request filter information,
7234        // drop them now so we don't have to
7235        // marshall/unmarshall it.
7236        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7237            N = results.size();
7238            for (int i=0; i<N; i++) {
7239                results.get(i).filter = null;
7240            }
7241        }
7242
7243        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7244        return results;
7245    }
7246
7247    @Override
7248    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7249            String resolvedType, int flags, int userId) {
7250        return new ParceledListSlice<>(
7251                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7252    }
7253
7254    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7255            String resolvedType, int flags, int userId) {
7256        if (!sUserManager.exists(userId)) return Collections.emptyList();
7257        final int callingUid = Binder.getCallingUid();
7258        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7259                false /*includeInstantApps*/);
7260        ComponentName comp = intent.getComponent();
7261        if (comp == null) {
7262            if (intent.getSelector() != null) {
7263                intent = intent.getSelector();
7264                comp = intent.getComponent();
7265            }
7266        }
7267        if (comp != null) {
7268            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7269            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7270            if (ai != null) {
7271                ResolveInfo ri = new ResolveInfo();
7272                ri.activityInfo = ai;
7273                list.add(ri);
7274            }
7275            return list;
7276        }
7277
7278        // reader
7279        synchronized (mPackages) {
7280            String pkgName = intent.getPackage();
7281            if (pkgName == null) {
7282                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7283            }
7284            final PackageParser.Package pkg = mPackages.get(pkgName);
7285            if (pkg != null) {
7286                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7287                        userId);
7288            }
7289            return Collections.emptyList();
7290        }
7291    }
7292
7293    @Override
7294    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7295        final int callingUid = Binder.getCallingUid();
7296        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7297    }
7298
7299    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7300            int userId, int callingUid) {
7301        if (!sUserManager.exists(userId)) return null;
7302        flags = updateFlagsForResolve(
7303                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7304        List<ResolveInfo> query = queryIntentServicesInternal(
7305                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7306        if (query != null) {
7307            if (query.size() >= 1) {
7308                // If there is more than one service with the same priority,
7309                // just arbitrarily pick the first one.
7310                return query.get(0);
7311            }
7312        }
7313        return null;
7314    }
7315
7316    @Override
7317    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7318            String resolvedType, int flags, int userId) {
7319        final int callingUid = Binder.getCallingUid();
7320        return new ParceledListSlice<>(queryIntentServicesInternal(
7321                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7322    }
7323
7324    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7325            String resolvedType, int flags, int userId, int callingUid,
7326            boolean includeInstantApps) {
7327        if (!sUserManager.exists(userId)) return Collections.emptyList();
7328        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7329        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7330        ComponentName comp = intent.getComponent();
7331        if (comp == null) {
7332            if (intent.getSelector() != null) {
7333                intent = intent.getSelector();
7334                comp = intent.getComponent();
7335            }
7336        }
7337        if (comp != null) {
7338            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7339            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7340            if (si != null) {
7341                // When specifying an explicit component, we prevent the service from being
7342                // used when either 1) the service is in an instant application and the
7343                // caller is not the same instant application or 2) the calling package is
7344                // ephemeral and the activity is not visible to ephemeral applications.
7345                final boolean matchInstantApp =
7346                        (flags & PackageManager.MATCH_INSTANT) != 0;
7347                final boolean matchVisibleToInstantAppOnly =
7348                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7349                final boolean isCallerInstantApp =
7350                        instantAppPkgName != null;
7351                final boolean isTargetSameInstantApp =
7352                        comp.getPackageName().equals(instantAppPkgName);
7353                final boolean isTargetInstantApp =
7354                        (si.applicationInfo.privateFlags
7355                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7356                final boolean isTargetHiddenFromInstantApp =
7357                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7358                final boolean blockResolution =
7359                        !isTargetSameInstantApp
7360                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7361                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7362                                        && isTargetHiddenFromInstantApp));
7363                if (!blockResolution) {
7364                    final ResolveInfo ri = new ResolveInfo();
7365                    ri.serviceInfo = si;
7366                    list.add(ri);
7367                }
7368            }
7369            return list;
7370        }
7371
7372        // reader
7373        synchronized (mPackages) {
7374            String pkgName = intent.getPackage();
7375            if (pkgName == null) {
7376                return applyPostServiceResolutionFilter(
7377                        mServices.queryIntent(intent, resolvedType, flags, userId),
7378                        instantAppPkgName);
7379            }
7380            final PackageParser.Package pkg = mPackages.get(pkgName);
7381            if (pkg != null) {
7382                return applyPostServiceResolutionFilter(
7383                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7384                                userId),
7385                        instantAppPkgName);
7386            }
7387            return Collections.emptyList();
7388        }
7389    }
7390
7391    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7392            String instantAppPkgName) {
7393        // TODO: When adding on-demand split support for non-instant apps, remove this check
7394        // and always apply post filtering
7395        if (instantAppPkgName == null) {
7396            return resolveInfos;
7397        }
7398        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7399            final ResolveInfo info = resolveInfos.get(i);
7400            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7401            // allow services that are defined in the provided package
7402            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7403                if (info.serviceInfo.splitName != null
7404                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7405                                info.serviceInfo.splitName)) {
7406                    // requested service is defined in a split that hasn't been installed yet.
7407                    // add the installer to the resolve list
7408                    if (DEBUG_EPHEMERAL) {
7409                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7410                    }
7411                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7412                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7413                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7414                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7415                    // make sure this resolver is the default
7416                    installerInfo.isDefault = true;
7417                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7418                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7419                    // add a non-generic filter
7420                    installerInfo.filter = new IntentFilter();
7421                    // load resources from the correct package
7422                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7423                    resolveInfos.set(i, installerInfo);
7424                }
7425                continue;
7426            }
7427            // allow services that have been explicitly exposed to ephemeral apps
7428            if (!isEphemeralApp
7429                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7430                continue;
7431            }
7432            resolveInfos.remove(i);
7433        }
7434        return resolveInfos;
7435    }
7436
7437    @Override
7438    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7439            String resolvedType, int flags, int userId) {
7440        return new ParceledListSlice<>(
7441                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7442    }
7443
7444    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7445            Intent intent, String resolvedType, int flags, int userId) {
7446        if (!sUserManager.exists(userId)) return Collections.emptyList();
7447        final int callingUid = Binder.getCallingUid();
7448        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7449        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7450                false /*includeInstantApps*/);
7451        ComponentName comp = intent.getComponent();
7452        if (comp == null) {
7453            if (intent.getSelector() != null) {
7454                intent = intent.getSelector();
7455                comp = intent.getComponent();
7456            }
7457        }
7458        if (comp != null) {
7459            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7460            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7461            if (pi != null) {
7462                // When specifying an explicit component, we prevent the provider from being
7463                // used when either 1) the provider is in an instant application and the
7464                // caller is not the same instant application or 2) the calling package is an
7465                // instant application and the provider is not visible to instant applications.
7466                final boolean matchInstantApp =
7467                        (flags & PackageManager.MATCH_INSTANT) != 0;
7468                final boolean matchVisibleToInstantAppOnly =
7469                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7470                final boolean isCallerInstantApp =
7471                        instantAppPkgName != null;
7472                final boolean isTargetSameInstantApp =
7473                        comp.getPackageName().equals(instantAppPkgName);
7474                final boolean isTargetInstantApp =
7475                        (pi.applicationInfo.privateFlags
7476                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7477                final boolean isTargetHiddenFromInstantApp =
7478                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7479                final boolean blockResolution =
7480                        !isTargetSameInstantApp
7481                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7482                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7483                                        && isTargetHiddenFromInstantApp));
7484                if (!blockResolution) {
7485                    final ResolveInfo ri = new ResolveInfo();
7486                    ri.providerInfo = pi;
7487                    list.add(ri);
7488                }
7489            }
7490            return list;
7491        }
7492
7493        // reader
7494        synchronized (mPackages) {
7495            String pkgName = intent.getPackage();
7496            if (pkgName == null) {
7497                return applyPostContentProviderResolutionFilter(
7498                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7499                        instantAppPkgName);
7500            }
7501            final PackageParser.Package pkg = mPackages.get(pkgName);
7502            if (pkg != null) {
7503                return applyPostContentProviderResolutionFilter(
7504                        mProviders.queryIntentForPackage(
7505                        intent, resolvedType, flags, pkg.providers, userId),
7506                        instantAppPkgName);
7507            }
7508            return Collections.emptyList();
7509        }
7510    }
7511
7512    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7513            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7514        // TODO: When adding on-demand split support for non-instant applications, remove
7515        // this check and always apply post filtering
7516        if (instantAppPkgName == null) {
7517            return resolveInfos;
7518        }
7519        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7520            final ResolveInfo info = resolveInfos.get(i);
7521            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7522            // allow providers that are defined in the provided package
7523            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7524                if (info.providerInfo.splitName != null
7525                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7526                                info.providerInfo.splitName)) {
7527                    // requested provider is defined in a split that hasn't been installed yet.
7528                    // add the installer to the resolve list
7529                    if (DEBUG_EPHEMERAL) {
7530                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7531                    }
7532                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7533                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7534                            info.providerInfo.packageName, info.providerInfo.splitName,
7535                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7536                    // make sure this resolver is the default
7537                    installerInfo.isDefault = true;
7538                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7539                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7540                    // add a non-generic filter
7541                    installerInfo.filter = new IntentFilter();
7542                    // load resources from the correct package
7543                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7544                    resolveInfos.set(i, installerInfo);
7545                }
7546                continue;
7547            }
7548            // allow providers that have been explicitly exposed to instant applications
7549            if (!isEphemeralApp
7550                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7551                continue;
7552            }
7553            resolveInfos.remove(i);
7554        }
7555        return resolveInfos;
7556    }
7557
7558    @Override
7559    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7560        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7561        flags = updateFlagsForPackage(flags, userId, null);
7562        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7563        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7564                true /* requireFullPermission */, false /* checkShell */,
7565                "get installed packages");
7566
7567        // writer
7568        synchronized (mPackages) {
7569            ArrayList<PackageInfo> list;
7570            if (listUninstalled) {
7571                list = new ArrayList<>(mSettings.mPackages.size());
7572                for (PackageSetting ps : mSettings.mPackages.values()) {
7573                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7574                        continue;
7575                    }
7576                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7577                    if (pi != null) {
7578                        list.add(pi);
7579                    }
7580                }
7581            } else {
7582                list = new ArrayList<>(mPackages.size());
7583                for (PackageParser.Package p : mPackages.values()) {
7584                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7585                            Binder.getCallingUid(), userId, flags)) {
7586                        continue;
7587                    }
7588                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7589                            p.mExtras, flags, userId);
7590                    if (pi != null) {
7591                        list.add(pi);
7592                    }
7593                }
7594            }
7595
7596            return new ParceledListSlice<>(list);
7597        }
7598    }
7599
7600    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7601            String[] permissions, boolean[] tmp, int flags, int userId) {
7602        int numMatch = 0;
7603        final PermissionsState permissionsState = ps.getPermissionsState();
7604        for (int i=0; i<permissions.length; i++) {
7605            final String permission = permissions[i];
7606            if (permissionsState.hasPermission(permission, userId)) {
7607                tmp[i] = true;
7608                numMatch++;
7609            } else {
7610                tmp[i] = false;
7611            }
7612        }
7613        if (numMatch == 0) {
7614            return;
7615        }
7616        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7617
7618        // The above might return null in cases of uninstalled apps or install-state
7619        // skew across users/profiles.
7620        if (pi != null) {
7621            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7622                if (numMatch == permissions.length) {
7623                    pi.requestedPermissions = permissions;
7624                } else {
7625                    pi.requestedPermissions = new String[numMatch];
7626                    numMatch = 0;
7627                    for (int i=0; i<permissions.length; i++) {
7628                        if (tmp[i]) {
7629                            pi.requestedPermissions[numMatch] = permissions[i];
7630                            numMatch++;
7631                        }
7632                    }
7633                }
7634            }
7635            list.add(pi);
7636        }
7637    }
7638
7639    @Override
7640    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7641            String[] permissions, int flags, int userId) {
7642        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7643        flags = updateFlagsForPackage(flags, userId, permissions);
7644        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7645                true /* requireFullPermission */, false /* checkShell */,
7646                "get packages holding permissions");
7647        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7648
7649        // writer
7650        synchronized (mPackages) {
7651            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7652            boolean[] tmpBools = new boolean[permissions.length];
7653            if (listUninstalled) {
7654                for (PackageSetting ps : mSettings.mPackages.values()) {
7655                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7656                            userId);
7657                }
7658            } else {
7659                for (PackageParser.Package pkg : mPackages.values()) {
7660                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7661                    if (ps != null) {
7662                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7663                                userId);
7664                    }
7665                }
7666            }
7667
7668            return new ParceledListSlice<PackageInfo>(list);
7669        }
7670    }
7671
7672    @Override
7673    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7674        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7675        flags = updateFlagsForApplication(flags, userId, null);
7676        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7677
7678        // writer
7679        synchronized (mPackages) {
7680            ArrayList<ApplicationInfo> list;
7681            if (listUninstalled) {
7682                list = new ArrayList<>(mSettings.mPackages.size());
7683                for (PackageSetting ps : mSettings.mPackages.values()) {
7684                    ApplicationInfo ai;
7685                    int effectiveFlags = flags;
7686                    if (ps.isSystem()) {
7687                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7688                    }
7689                    if (ps.pkg != null) {
7690                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7691                            continue;
7692                        }
7693                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7694                                ps.readUserState(userId), userId);
7695                        if (ai != null) {
7696                            rebaseEnabledOverlays(ai, userId);
7697                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7698                        }
7699                    } else {
7700                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7701                        // and already converts to externally visible package name
7702                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7703                                Binder.getCallingUid(), effectiveFlags, userId);
7704                    }
7705                    if (ai != null) {
7706                        list.add(ai);
7707                    }
7708                }
7709            } else {
7710                list = new ArrayList<>(mPackages.size());
7711                for (PackageParser.Package p : mPackages.values()) {
7712                    if (p.mExtras != null) {
7713                        PackageSetting ps = (PackageSetting) p.mExtras;
7714                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7715                            continue;
7716                        }
7717                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7718                                ps.readUserState(userId), userId);
7719                        if (ai != null) {
7720                            rebaseEnabledOverlays(ai, userId);
7721                            ai.packageName = resolveExternalPackageNameLPr(p);
7722                            list.add(ai);
7723                        }
7724                    }
7725                }
7726            }
7727
7728            return new ParceledListSlice<>(list);
7729        }
7730    }
7731
7732    @Override
7733    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7734        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7735            return null;
7736        }
7737
7738        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7739                "getEphemeralApplications");
7740        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7741                true /* requireFullPermission */, false /* checkShell */,
7742                "getEphemeralApplications");
7743        synchronized (mPackages) {
7744            List<InstantAppInfo> instantApps = mInstantAppRegistry
7745                    .getInstantAppsLPr(userId);
7746            if (instantApps != null) {
7747                return new ParceledListSlice<>(instantApps);
7748            }
7749        }
7750        return null;
7751    }
7752
7753    @Override
7754    public boolean isInstantApp(String packageName, int userId) {
7755        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7756                true /* requireFullPermission */, false /* checkShell */,
7757                "isInstantApp");
7758        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7759            return false;
7760        }
7761        int uid = Binder.getCallingUid();
7762        if (Process.isIsolated(uid)) {
7763            uid = mIsolatedOwners.get(uid);
7764        }
7765
7766        synchronized (mPackages) {
7767            final PackageSetting ps = mSettings.mPackages.get(packageName);
7768            PackageParser.Package pkg = mPackages.get(packageName);
7769            final boolean returnAllowed =
7770                    ps != null
7771                    && (isCallerSameApp(packageName, uid)
7772                            || mContext.checkCallingOrSelfPermission(
7773                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7774                                            == PERMISSION_GRANTED
7775                            || mInstantAppRegistry.isInstantAccessGranted(
7776                                    userId, UserHandle.getAppId(uid), ps.appId));
7777            if (returnAllowed) {
7778                return ps.getInstantApp(userId);
7779            }
7780        }
7781        return false;
7782    }
7783
7784    @Override
7785    public byte[] getInstantAppCookie(String packageName, int userId) {
7786        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7787            return null;
7788        }
7789
7790        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7791                true /* requireFullPermission */, false /* checkShell */,
7792                "getInstantAppCookie");
7793        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7794            return null;
7795        }
7796        synchronized (mPackages) {
7797            return mInstantAppRegistry.getInstantAppCookieLPw(
7798                    packageName, userId);
7799        }
7800    }
7801
7802    @Override
7803    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7804        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7805            return true;
7806        }
7807
7808        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7809                true /* requireFullPermission */, true /* checkShell */,
7810                "setInstantAppCookie");
7811        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7812            return false;
7813        }
7814        synchronized (mPackages) {
7815            return mInstantAppRegistry.setInstantAppCookieLPw(
7816                    packageName, cookie, userId);
7817        }
7818    }
7819
7820    @Override
7821    public Bitmap getInstantAppIcon(String packageName, int userId) {
7822        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7823            return null;
7824        }
7825
7826        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7827                "getInstantAppIcon");
7828
7829        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7830                true /* requireFullPermission */, false /* checkShell */,
7831                "getInstantAppIcon");
7832
7833        synchronized (mPackages) {
7834            return mInstantAppRegistry.getInstantAppIconLPw(
7835                    packageName, userId);
7836        }
7837    }
7838
7839    private boolean isCallerSameApp(String packageName, int uid) {
7840        PackageParser.Package pkg = mPackages.get(packageName);
7841        return pkg != null
7842                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7843    }
7844
7845    @Override
7846    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7847        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7848    }
7849
7850    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7851        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7852
7853        // reader
7854        synchronized (mPackages) {
7855            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7856            final int userId = UserHandle.getCallingUserId();
7857            while (i.hasNext()) {
7858                final PackageParser.Package p = i.next();
7859                if (p.applicationInfo == null) continue;
7860
7861                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7862                        && !p.applicationInfo.isDirectBootAware();
7863                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7864                        && p.applicationInfo.isDirectBootAware();
7865
7866                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7867                        && (!mSafeMode || isSystemApp(p))
7868                        && (matchesUnaware || matchesAware)) {
7869                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7870                    if (ps != null) {
7871                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7872                                ps.readUserState(userId), userId);
7873                        if (ai != null) {
7874                            rebaseEnabledOverlays(ai, userId);
7875                            finalList.add(ai);
7876                        }
7877                    }
7878                }
7879            }
7880        }
7881
7882        return finalList;
7883    }
7884
7885    @Override
7886    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7887        if (!sUserManager.exists(userId)) return null;
7888        flags = updateFlagsForComponent(flags, userId, name);
7889        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7890        // reader
7891        synchronized (mPackages) {
7892            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7893            PackageSetting ps = provider != null
7894                    ? mSettings.mPackages.get(provider.owner.packageName)
7895                    : null;
7896            if (ps != null) {
7897                final boolean isInstantApp = ps.getInstantApp(userId);
7898                // normal application; filter out instant application provider
7899                if (instantAppPkgName == null && isInstantApp) {
7900                    return null;
7901                }
7902                // instant application; filter out other instant applications
7903                if (instantAppPkgName != null
7904                        && isInstantApp
7905                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7906                    return null;
7907                }
7908                // instant application; filter out non-exposed provider
7909                if (instantAppPkgName != null
7910                        && !isInstantApp
7911                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7912                    return null;
7913                }
7914                // provider not enabled
7915                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7916                    return null;
7917                }
7918                return PackageParser.generateProviderInfo(
7919                        provider, flags, ps.readUserState(userId), userId);
7920            }
7921            return null;
7922        }
7923    }
7924
7925    /**
7926     * @deprecated
7927     */
7928    @Deprecated
7929    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7930        // reader
7931        synchronized (mPackages) {
7932            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7933                    .entrySet().iterator();
7934            final int userId = UserHandle.getCallingUserId();
7935            while (i.hasNext()) {
7936                Map.Entry<String, PackageParser.Provider> entry = i.next();
7937                PackageParser.Provider p = entry.getValue();
7938                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7939
7940                if (ps != null && p.syncable
7941                        && (!mSafeMode || (p.info.applicationInfo.flags
7942                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7943                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7944                            ps.readUserState(userId), userId);
7945                    if (info != null) {
7946                        outNames.add(entry.getKey());
7947                        outInfo.add(info);
7948                    }
7949                }
7950            }
7951        }
7952    }
7953
7954    @Override
7955    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7956            int uid, int flags, String metaDataKey) {
7957        final int userId = processName != null ? UserHandle.getUserId(uid)
7958                : UserHandle.getCallingUserId();
7959        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7960        flags = updateFlagsForComponent(flags, userId, processName);
7961
7962        ArrayList<ProviderInfo> finalList = null;
7963        // reader
7964        synchronized (mPackages) {
7965            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7966            while (i.hasNext()) {
7967                final PackageParser.Provider p = i.next();
7968                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7969                if (ps != null && p.info.authority != null
7970                        && (processName == null
7971                                || (p.info.processName.equals(processName)
7972                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7973                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7974
7975                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7976                    // parameter.
7977                    if (metaDataKey != null
7978                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7979                        continue;
7980                    }
7981
7982                    if (finalList == null) {
7983                        finalList = new ArrayList<ProviderInfo>(3);
7984                    }
7985                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7986                            ps.readUserState(userId), userId);
7987                    if (info != null) {
7988                        finalList.add(info);
7989                    }
7990                }
7991            }
7992        }
7993
7994        if (finalList != null) {
7995            Collections.sort(finalList, mProviderInitOrderSorter);
7996            return new ParceledListSlice<ProviderInfo>(finalList);
7997        }
7998
7999        return ParceledListSlice.emptyList();
8000    }
8001
8002    @Override
8003    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
8004        // reader
8005        synchronized (mPackages) {
8006            final PackageParser.Instrumentation i = mInstrumentation.get(name);
8007            return PackageParser.generateInstrumentationInfo(i, flags);
8008        }
8009    }
8010
8011    @Override
8012    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8013            String targetPackage, int flags) {
8014        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8015    }
8016
8017    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8018            int flags) {
8019        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8020
8021        // reader
8022        synchronized (mPackages) {
8023            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8024            while (i.hasNext()) {
8025                final PackageParser.Instrumentation p = i.next();
8026                if (targetPackage == null
8027                        || targetPackage.equals(p.info.targetPackage)) {
8028                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8029                            flags);
8030                    if (ii != null) {
8031                        finalList.add(ii);
8032                    }
8033                }
8034            }
8035        }
8036
8037        return finalList;
8038    }
8039
8040    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8041        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8042        try {
8043            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8044        } finally {
8045            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8046        }
8047    }
8048
8049    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8050        final File[] files = dir.listFiles();
8051        if (ArrayUtils.isEmpty(files)) {
8052            Log.d(TAG, "No files in app dir " + dir);
8053            return;
8054        }
8055
8056        if (DEBUG_PACKAGE_SCANNING) {
8057            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8058                    + " flags=0x" + Integer.toHexString(parseFlags));
8059        }
8060        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8061                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8062                mParallelPackageParserCallback);
8063
8064        // Submit files for parsing in parallel
8065        int fileCount = 0;
8066        for (File file : files) {
8067            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8068                    && !PackageInstallerService.isStageName(file.getName());
8069            if (!isPackage) {
8070                // Ignore entries which are not packages
8071                continue;
8072            }
8073            parallelPackageParser.submit(file, parseFlags);
8074            fileCount++;
8075        }
8076
8077        // Process results one by one
8078        for (; fileCount > 0; fileCount--) {
8079            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8080            Throwable throwable = parseResult.throwable;
8081            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8082
8083            if (throwable == null) {
8084                // Static shared libraries have synthetic package names
8085                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8086                    renameStaticSharedLibraryPackage(parseResult.pkg);
8087                }
8088                try {
8089                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8090                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8091                                currentTime, null);
8092                    }
8093                } catch (PackageManagerException e) {
8094                    errorCode = e.error;
8095                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8096                }
8097            } else if (throwable instanceof PackageParser.PackageParserException) {
8098                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8099                        throwable;
8100                errorCode = e.error;
8101                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8102            } else {
8103                throw new IllegalStateException("Unexpected exception occurred while parsing "
8104                        + parseResult.scanFile, throwable);
8105            }
8106
8107            // Delete invalid userdata apps
8108            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8109                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8110                logCriticalInfo(Log.WARN,
8111                        "Deleting invalid package at " + parseResult.scanFile);
8112                removeCodePathLI(parseResult.scanFile);
8113            }
8114        }
8115        parallelPackageParser.close();
8116    }
8117
8118    private static File getSettingsProblemFile() {
8119        File dataDir = Environment.getDataDirectory();
8120        File systemDir = new File(dataDir, "system");
8121        File fname = new File(systemDir, "uiderrors.txt");
8122        return fname;
8123    }
8124
8125    static void reportSettingsProblem(int priority, String msg) {
8126        logCriticalInfo(priority, msg);
8127    }
8128
8129    public static void logCriticalInfo(int priority, String msg) {
8130        Slog.println(priority, TAG, msg);
8131        EventLogTags.writePmCriticalInfo(msg);
8132        try {
8133            File fname = getSettingsProblemFile();
8134            FileOutputStream out = new FileOutputStream(fname, true);
8135            PrintWriter pw = new FastPrintWriter(out);
8136            SimpleDateFormat formatter = new SimpleDateFormat();
8137            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8138            pw.println(dateString + ": " + msg);
8139            pw.close();
8140            FileUtils.setPermissions(
8141                    fname.toString(),
8142                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8143                    -1, -1);
8144        } catch (java.io.IOException e) {
8145        }
8146    }
8147
8148    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8149        if (srcFile.isDirectory()) {
8150            final File baseFile = new File(pkg.baseCodePath);
8151            long maxModifiedTime = baseFile.lastModified();
8152            if (pkg.splitCodePaths != null) {
8153                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8154                    final File splitFile = new File(pkg.splitCodePaths[i]);
8155                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8156                }
8157            }
8158            return maxModifiedTime;
8159        }
8160        return srcFile.lastModified();
8161    }
8162
8163    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8164            final int policyFlags) throws PackageManagerException {
8165        // When upgrading from pre-N MR1, verify the package time stamp using the package
8166        // directory and not the APK file.
8167        final long lastModifiedTime = mIsPreNMR1Upgrade
8168                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8169        if (ps != null
8170                && ps.codePath.equals(srcFile)
8171                && ps.timeStamp == lastModifiedTime
8172                && !isCompatSignatureUpdateNeeded(pkg)
8173                && !isRecoverSignatureUpdateNeeded(pkg)) {
8174            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8175            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8176            ArraySet<PublicKey> signingKs;
8177            synchronized (mPackages) {
8178                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8179            }
8180            if (ps.signatures.mSignatures != null
8181                    && ps.signatures.mSignatures.length != 0
8182                    && signingKs != null) {
8183                // Optimization: reuse the existing cached certificates
8184                // if the package appears to be unchanged.
8185                pkg.mSignatures = ps.signatures.mSignatures;
8186                pkg.mSigningKeys = signingKs;
8187                return;
8188            }
8189
8190            Slog.w(TAG, "PackageSetting for " + ps.name
8191                    + " is missing signatures.  Collecting certs again to recover them.");
8192        } else {
8193            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8194        }
8195
8196        try {
8197            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8198            PackageParser.collectCertificates(pkg, policyFlags);
8199        } catch (PackageParserException e) {
8200            throw PackageManagerException.from(e);
8201        } finally {
8202            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8203        }
8204    }
8205
8206    /**
8207     *  Traces a package scan.
8208     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8209     */
8210    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8211            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8212        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8213        try {
8214            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8215        } finally {
8216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8217        }
8218    }
8219
8220    /**
8221     *  Scans a package and returns the newly parsed package.
8222     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8223     */
8224    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8225            long currentTime, UserHandle user) throws PackageManagerException {
8226        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8227        PackageParser pp = new PackageParser();
8228        pp.setSeparateProcesses(mSeparateProcesses);
8229        pp.setOnlyCoreApps(mOnlyCore);
8230        pp.setDisplayMetrics(mMetrics);
8231        pp.setCallback(mPackageParserCallback);
8232
8233        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8234            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8235        }
8236
8237        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8238        final PackageParser.Package pkg;
8239        try {
8240            pkg = pp.parsePackage(scanFile, parseFlags);
8241        } catch (PackageParserException e) {
8242            throw PackageManagerException.from(e);
8243        } finally {
8244            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8245        }
8246
8247        // Static shared libraries have synthetic package names
8248        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8249            renameStaticSharedLibraryPackage(pkg);
8250        }
8251
8252        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8253    }
8254
8255    /**
8256     *  Scans a package and returns the newly parsed package.
8257     *  @throws PackageManagerException on a parse error.
8258     */
8259    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8260            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8261            throws PackageManagerException {
8262        // If the package has children and this is the first dive in the function
8263        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8264        // packages (parent and children) would be successfully scanned before the
8265        // actual scan since scanning mutates internal state and we want to atomically
8266        // install the package and its children.
8267        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8268            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8269                scanFlags |= SCAN_CHECK_ONLY;
8270            }
8271        } else {
8272            scanFlags &= ~SCAN_CHECK_ONLY;
8273        }
8274
8275        // Scan the parent
8276        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8277                scanFlags, currentTime, user);
8278
8279        // Scan the children
8280        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8281        for (int i = 0; i < childCount; i++) {
8282            PackageParser.Package childPackage = pkg.childPackages.get(i);
8283            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8284                    currentTime, user);
8285        }
8286
8287
8288        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8289            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8290        }
8291
8292        return scannedPkg;
8293    }
8294
8295    /**
8296     *  Scans a package and returns the newly parsed package.
8297     *  @throws PackageManagerException on a parse error.
8298     */
8299    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8300            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8301            throws PackageManagerException {
8302        PackageSetting ps = null;
8303        PackageSetting updatedPkg;
8304        // reader
8305        synchronized (mPackages) {
8306            // Look to see if we already know about this package.
8307            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8308            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8309                // This package has been renamed to its original name.  Let's
8310                // use that.
8311                ps = mSettings.getPackageLPr(oldName);
8312            }
8313            // If there was no original package, see one for the real package name.
8314            if (ps == null) {
8315                ps = mSettings.getPackageLPr(pkg.packageName);
8316            }
8317            // Check to see if this package could be hiding/updating a system
8318            // package.  Must look for it either under the original or real
8319            // package name depending on our state.
8320            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8321            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8322
8323            // If this is a package we don't know about on the system partition, we
8324            // may need to remove disabled child packages on the system partition
8325            // or may need to not add child packages if the parent apk is updated
8326            // on the data partition and no longer defines this child package.
8327            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8328                // If this is a parent package for an updated system app and this system
8329                // app got an OTA update which no longer defines some of the child packages
8330                // we have to prune them from the disabled system packages.
8331                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8332                if (disabledPs != null) {
8333                    final int scannedChildCount = (pkg.childPackages != null)
8334                            ? pkg.childPackages.size() : 0;
8335                    final int disabledChildCount = disabledPs.childPackageNames != null
8336                            ? disabledPs.childPackageNames.size() : 0;
8337                    for (int i = 0; i < disabledChildCount; i++) {
8338                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8339                        boolean disabledPackageAvailable = false;
8340                        for (int j = 0; j < scannedChildCount; j++) {
8341                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8342                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8343                                disabledPackageAvailable = true;
8344                                break;
8345                            }
8346                         }
8347                         if (!disabledPackageAvailable) {
8348                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8349                         }
8350                    }
8351                }
8352            }
8353        }
8354
8355        boolean updatedPkgBetter = false;
8356        // First check if this is a system package that may involve an update
8357        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8358            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8359            // it needs to drop FLAG_PRIVILEGED.
8360            if (locationIsPrivileged(scanFile)) {
8361                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8362            } else {
8363                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8364            }
8365
8366            if (ps != null && !ps.codePath.equals(scanFile)) {
8367                // The path has changed from what was last scanned...  check the
8368                // version of the new path against what we have stored to determine
8369                // what to do.
8370                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8371                if (pkg.mVersionCode <= ps.versionCode) {
8372                    // The system package has been updated and the code path does not match
8373                    // Ignore entry. Skip it.
8374                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8375                            + " ignored: updated version " + ps.versionCode
8376                            + " better than this " + pkg.mVersionCode);
8377                    if (!updatedPkg.codePath.equals(scanFile)) {
8378                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8379                                + ps.name + " changing from " + updatedPkg.codePathString
8380                                + " to " + scanFile);
8381                        updatedPkg.codePath = scanFile;
8382                        updatedPkg.codePathString = scanFile.toString();
8383                        updatedPkg.resourcePath = scanFile;
8384                        updatedPkg.resourcePathString = scanFile.toString();
8385                    }
8386                    updatedPkg.pkg = pkg;
8387                    updatedPkg.versionCode = pkg.mVersionCode;
8388
8389                    // Update the disabled system child packages to point to the package too.
8390                    final int childCount = updatedPkg.childPackageNames != null
8391                            ? updatedPkg.childPackageNames.size() : 0;
8392                    for (int i = 0; i < childCount; i++) {
8393                        String childPackageName = updatedPkg.childPackageNames.get(i);
8394                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8395                                childPackageName);
8396                        if (updatedChildPkg != null) {
8397                            updatedChildPkg.pkg = pkg;
8398                            updatedChildPkg.versionCode = pkg.mVersionCode;
8399                        }
8400                    }
8401
8402                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8403                            + scanFile + " ignored: updated version " + ps.versionCode
8404                            + " better than this " + pkg.mVersionCode);
8405                } else {
8406                    // The current app on the system partition is better than
8407                    // what we have updated to on the data partition; switch
8408                    // back to the system partition version.
8409                    // At this point, its safely assumed that package installation for
8410                    // apps in system partition will go through. If not there won't be a working
8411                    // version of the app
8412                    // writer
8413                    synchronized (mPackages) {
8414                        // Just remove the loaded entries from package lists.
8415                        mPackages.remove(ps.name);
8416                    }
8417
8418                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8419                            + " reverting from " + ps.codePathString
8420                            + ": new version " + pkg.mVersionCode
8421                            + " better than installed " + ps.versionCode);
8422
8423                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8424                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8425                    synchronized (mInstallLock) {
8426                        args.cleanUpResourcesLI();
8427                    }
8428                    synchronized (mPackages) {
8429                        mSettings.enableSystemPackageLPw(ps.name);
8430                    }
8431                    updatedPkgBetter = true;
8432                }
8433            }
8434        }
8435
8436        if (updatedPkg != null) {
8437            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8438            // initially
8439            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8440
8441            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8442            // flag set initially
8443            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8444                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8445            }
8446        }
8447
8448        // Verify certificates against what was last scanned
8449        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8450
8451        /*
8452         * A new system app appeared, but we already had a non-system one of the
8453         * same name installed earlier.
8454         */
8455        boolean shouldHideSystemApp = false;
8456        if (updatedPkg == null && ps != null
8457                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8458            /*
8459             * Check to make sure the signatures match first. If they don't,
8460             * wipe the installed application and its data.
8461             */
8462            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8463                    != PackageManager.SIGNATURE_MATCH) {
8464                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8465                        + " signatures don't match existing userdata copy; removing");
8466                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8467                        "scanPackageInternalLI")) {
8468                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8469                }
8470                ps = null;
8471            } else {
8472                /*
8473                 * If the newly-added system app is an older version than the
8474                 * already installed version, hide it. It will be scanned later
8475                 * and re-added like an update.
8476                 */
8477                if (pkg.mVersionCode <= ps.versionCode) {
8478                    shouldHideSystemApp = true;
8479                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8480                            + " but new version " + pkg.mVersionCode + " better than installed "
8481                            + ps.versionCode + "; hiding system");
8482                } else {
8483                    /*
8484                     * The newly found system app is a newer version that the
8485                     * one previously installed. Simply remove the
8486                     * already-installed application and replace it with our own
8487                     * while keeping the application data.
8488                     */
8489                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8490                            + " reverting from " + ps.codePathString + ": new version "
8491                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8492                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8493                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8494                    synchronized (mInstallLock) {
8495                        args.cleanUpResourcesLI();
8496                    }
8497                }
8498            }
8499        }
8500
8501        // The apk is forward locked (not public) if its code and resources
8502        // are kept in different files. (except for app in either system or
8503        // vendor path).
8504        // TODO grab this value from PackageSettings
8505        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8506            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8507                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8508            }
8509        }
8510
8511        // TODO: extend to support forward-locked splits
8512        String resourcePath = null;
8513        String baseResourcePath = null;
8514        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8515            if (ps != null && ps.resourcePathString != null) {
8516                resourcePath = ps.resourcePathString;
8517                baseResourcePath = ps.resourcePathString;
8518            } else {
8519                // Should not happen at all. Just log an error.
8520                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8521            }
8522        } else {
8523            resourcePath = pkg.codePath;
8524            baseResourcePath = pkg.baseCodePath;
8525        }
8526
8527        // Set application objects path explicitly.
8528        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8529        pkg.setApplicationInfoCodePath(pkg.codePath);
8530        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8531        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8532        pkg.setApplicationInfoResourcePath(resourcePath);
8533        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8534        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8535
8536        final int userId = ((user == null) ? 0 : user.getIdentifier());
8537        if (ps != null && ps.getInstantApp(userId)) {
8538            scanFlags |= SCAN_AS_INSTANT_APP;
8539        }
8540
8541        // Note that we invoke the following method only if we are about to unpack an application
8542        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8543                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8544
8545        /*
8546         * If the system app should be overridden by a previously installed
8547         * data, hide the system app now and let the /data/app scan pick it up
8548         * again.
8549         */
8550        if (shouldHideSystemApp) {
8551            synchronized (mPackages) {
8552                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8553            }
8554        }
8555
8556        return scannedPkg;
8557    }
8558
8559    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8560        // Derive the new package synthetic package name
8561        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8562                + pkg.staticSharedLibVersion);
8563    }
8564
8565    private static String fixProcessName(String defProcessName,
8566            String processName) {
8567        if (processName == null) {
8568            return defProcessName;
8569        }
8570        return processName;
8571    }
8572
8573    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8574            throws PackageManagerException {
8575        if (pkgSetting.signatures.mSignatures != null) {
8576            // Already existing package. Make sure signatures match
8577            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8578                    == PackageManager.SIGNATURE_MATCH;
8579            if (!match) {
8580                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8581                        == PackageManager.SIGNATURE_MATCH;
8582            }
8583            if (!match) {
8584                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8585                        == PackageManager.SIGNATURE_MATCH;
8586            }
8587            if (!match) {
8588                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8589                        + pkg.packageName + " signatures do not match the "
8590                        + "previously installed version; ignoring!");
8591            }
8592        }
8593
8594        // Check for shared user signatures
8595        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8596            // Already existing package. Make sure signatures match
8597            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8598                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8599            if (!match) {
8600                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8601                        == PackageManager.SIGNATURE_MATCH;
8602            }
8603            if (!match) {
8604                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8605                        == PackageManager.SIGNATURE_MATCH;
8606            }
8607            if (!match) {
8608                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8609                        "Package " + pkg.packageName
8610                        + " has no signatures that match those in shared user "
8611                        + pkgSetting.sharedUser.name + "; ignoring!");
8612            }
8613        }
8614    }
8615
8616    /**
8617     * Enforces that only the system UID or root's UID can call a method exposed
8618     * via Binder.
8619     *
8620     * @param message used as message if SecurityException is thrown
8621     * @throws SecurityException if the caller is not system or root
8622     */
8623    private static final void enforceSystemOrRoot(String message) {
8624        final int uid = Binder.getCallingUid();
8625        if (uid != Process.SYSTEM_UID && uid != 0) {
8626            throw new SecurityException(message);
8627        }
8628    }
8629
8630    @Override
8631    public void performFstrimIfNeeded() {
8632        enforceSystemOrRoot("Only the system can request fstrim");
8633
8634        // Before everything else, see whether we need to fstrim.
8635        try {
8636            IStorageManager sm = PackageHelper.getStorageManager();
8637            if (sm != null) {
8638                boolean doTrim = false;
8639                final long interval = android.provider.Settings.Global.getLong(
8640                        mContext.getContentResolver(),
8641                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8642                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8643                if (interval > 0) {
8644                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8645                    if (timeSinceLast > interval) {
8646                        doTrim = true;
8647                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8648                                + "; running immediately");
8649                    }
8650                }
8651                if (doTrim) {
8652                    final boolean dexOptDialogShown;
8653                    synchronized (mPackages) {
8654                        dexOptDialogShown = mDexOptDialogShown;
8655                    }
8656                    if (!isFirstBoot() && dexOptDialogShown) {
8657                        try {
8658                            ActivityManager.getService().showBootMessage(
8659                                    mContext.getResources().getString(
8660                                            R.string.android_upgrading_fstrim), true);
8661                        } catch (RemoteException e) {
8662                        }
8663                    }
8664                    sm.runMaintenance();
8665                }
8666            } else {
8667                Slog.e(TAG, "storageManager service unavailable!");
8668            }
8669        } catch (RemoteException e) {
8670            // Can't happen; StorageManagerService is local
8671        }
8672    }
8673
8674    @Override
8675    public void updatePackagesIfNeeded() {
8676        enforceSystemOrRoot("Only the system can request package update");
8677
8678        // We need to re-extract after an OTA.
8679        boolean causeUpgrade = isUpgrade();
8680
8681        // First boot or factory reset.
8682        // Note: we also handle devices that are upgrading to N right now as if it is their
8683        //       first boot, as they do not have profile data.
8684        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8685
8686        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8687        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8688
8689        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8690            return;
8691        }
8692
8693        List<PackageParser.Package> pkgs;
8694        synchronized (mPackages) {
8695            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8696        }
8697
8698        final long startTime = System.nanoTime();
8699        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8700                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8701
8702        final int elapsedTimeSeconds =
8703                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8704
8705        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8706        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8707        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8708        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8709        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8710    }
8711
8712    /**
8713     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8714     * containing statistics about the invocation. The array consists of three elements,
8715     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8716     * and {@code numberOfPackagesFailed}.
8717     */
8718    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8719            String compilerFilter) {
8720
8721        int numberOfPackagesVisited = 0;
8722        int numberOfPackagesOptimized = 0;
8723        int numberOfPackagesSkipped = 0;
8724        int numberOfPackagesFailed = 0;
8725        final int numberOfPackagesToDexopt = pkgs.size();
8726
8727        for (PackageParser.Package pkg : pkgs) {
8728            numberOfPackagesVisited++;
8729
8730            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8731                if (DEBUG_DEXOPT) {
8732                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8733                }
8734                numberOfPackagesSkipped++;
8735                continue;
8736            }
8737
8738            if (DEBUG_DEXOPT) {
8739                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8740                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8741            }
8742
8743            if (showDialog) {
8744                try {
8745                    ActivityManager.getService().showBootMessage(
8746                            mContext.getResources().getString(R.string.android_upgrading_apk,
8747                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8748                } catch (RemoteException e) {
8749                }
8750                synchronized (mPackages) {
8751                    mDexOptDialogShown = true;
8752                }
8753            }
8754
8755            // If the OTA updates a system app which was previously preopted to a non-preopted state
8756            // the app might end up being verified at runtime. That's because by default the apps
8757            // are verify-profile but for preopted apps there's no profile.
8758            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8759            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8760            // filter (by default 'quicken').
8761            // Note that at this stage unused apps are already filtered.
8762            if (isSystemApp(pkg) &&
8763                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8764                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8765                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8766            }
8767
8768            // checkProfiles is false to avoid merging profiles during boot which
8769            // might interfere with background compilation (b/28612421).
8770            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8771            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8772            // trade-off worth doing to save boot time work.
8773            int dexOptStatus = performDexOptTraced(pkg.packageName,
8774                    false /* checkProfiles */,
8775                    compilerFilter,
8776                    false /* force */);
8777            switch (dexOptStatus) {
8778                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8779                    numberOfPackagesOptimized++;
8780                    break;
8781                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8782                    numberOfPackagesSkipped++;
8783                    break;
8784                case PackageDexOptimizer.DEX_OPT_FAILED:
8785                    numberOfPackagesFailed++;
8786                    break;
8787                default:
8788                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8789                    break;
8790            }
8791        }
8792
8793        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8794                numberOfPackagesFailed };
8795    }
8796
8797    @Override
8798    public void notifyPackageUse(String packageName, int reason) {
8799        synchronized (mPackages) {
8800            PackageParser.Package p = mPackages.get(packageName);
8801            if (p == null) {
8802                return;
8803            }
8804            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8805        }
8806    }
8807
8808    @Override
8809    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8810        int userId = UserHandle.getCallingUserId();
8811        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8812        if (ai == null) {
8813            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8814                + loadingPackageName + ", user=" + userId);
8815            return;
8816        }
8817        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8818    }
8819
8820    @Override
8821    public boolean performDexOpt(String packageName,
8822            boolean checkProfiles, int compileReason, boolean force) {
8823        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8824                getCompilerFilterForReason(compileReason), force);
8825        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8826    }
8827
8828    @Override
8829    public boolean performDexOptMode(String packageName,
8830            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8831        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8832                targetCompilerFilter, force);
8833        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8834    }
8835
8836    private int performDexOptTraced(String packageName,
8837                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8838        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8839        try {
8840            return performDexOptInternal(packageName, checkProfiles,
8841                    targetCompilerFilter, force);
8842        } finally {
8843            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8844        }
8845    }
8846
8847    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8848    // if the package can now be considered up to date for the given filter.
8849    private int performDexOptInternal(String packageName,
8850                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8851        PackageParser.Package p;
8852        synchronized (mPackages) {
8853            p = mPackages.get(packageName);
8854            if (p == null) {
8855                // Package could not be found. Report failure.
8856                return PackageDexOptimizer.DEX_OPT_FAILED;
8857            }
8858            mPackageUsage.maybeWriteAsync(mPackages);
8859            mCompilerStats.maybeWriteAsync();
8860        }
8861        long callingId = Binder.clearCallingIdentity();
8862        try {
8863            synchronized (mInstallLock) {
8864                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8865                        targetCompilerFilter, force);
8866            }
8867        } finally {
8868            Binder.restoreCallingIdentity(callingId);
8869        }
8870    }
8871
8872    public ArraySet<String> getOptimizablePackages() {
8873        ArraySet<String> pkgs = new ArraySet<String>();
8874        synchronized (mPackages) {
8875            for (PackageParser.Package p : mPackages.values()) {
8876                if (PackageDexOptimizer.canOptimizePackage(p)) {
8877                    pkgs.add(p.packageName);
8878                }
8879            }
8880        }
8881        return pkgs;
8882    }
8883
8884    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8885            boolean checkProfiles, String targetCompilerFilter,
8886            boolean force) {
8887        // Select the dex optimizer based on the force parameter.
8888        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8889        //       allocate an object here.
8890        PackageDexOptimizer pdo = force
8891                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8892                : mPackageDexOptimizer;
8893
8894        // Dexopt all dependencies first. Note: we ignore the return value and march on
8895        // on errors.
8896        // Note that we are going to call performDexOpt on those libraries as many times as
8897        // they are referenced in packages. When we do a batch of performDexOpt (for example
8898        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8899        // and the first package that uses the library will dexopt it. The
8900        // others will see that the compiled code for the library is up to date.
8901        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8902        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8903        if (!deps.isEmpty()) {
8904            for (PackageParser.Package depPackage : deps) {
8905                // TODO: Analyze and investigate if we (should) profile libraries.
8906                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8907                        false /* checkProfiles */,
8908                        targetCompilerFilter,
8909                        getOrCreateCompilerPackageStats(depPackage),
8910                        true /* isUsedByOtherApps */);
8911            }
8912        }
8913        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8914                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8915                mDexManager.isUsedByOtherApps(p.packageName));
8916    }
8917
8918    // Performs dexopt on the used secondary dex files belonging to the given package.
8919    // Returns true if all dex files were process successfully (which could mean either dexopt or
8920    // skip). Returns false if any of the files caused errors.
8921    @Override
8922    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8923            boolean force) {
8924        mDexManager.reconcileSecondaryDexFiles(packageName);
8925        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8926    }
8927
8928    public boolean performDexOptSecondary(String packageName, int compileReason,
8929            boolean force) {
8930        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8931    }
8932
8933    /**
8934     * Reconcile the information we have about the secondary dex files belonging to
8935     * {@code packagName} and the actual dex files. For all dex files that were
8936     * deleted, update the internal records and delete the generated oat files.
8937     */
8938    @Override
8939    public void reconcileSecondaryDexFiles(String packageName) {
8940        mDexManager.reconcileSecondaryDexFiles(packageName);
8941    }
8942
8943    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8944    // a reference there.
8945    /*package*/ DexManager getDexManager() {
8946        return mDexManager;
8947    }
8948
8949    /**
8950     * Execute the background dexopt job immediately.
8951     */
8952    @Override
8953    public boolean runBackgroundDexoptJob() {
8954        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8955    }
8956
8957    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8958        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8959                || p.usesStaticLibraries != null) {
8960            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8961            Set<String> collectedNames = new HashSet<>();
8962            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8963
8964            retValue.remove(p);
8965
8966            return retValue;
8967        } else {
8968            return Collections.emptyList();
8969        }
8970    }
8971
8972    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8973            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8974        if (!collectedNames.contains(p.packageName)) {
8975            collectedNames.add(p.packageName);
8976            collected.add(p);
8977
8978            if (p.usesLibraries != null) {
8979                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8980                        null, collected, collectedNames);
8981            }
8982            if (p.usesOptionalLibraries != null) {
8983                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8984                        null, collected, collectedNames);
8985            }
8986            if (p.usesStaticLibraries != null) {
8987                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8988                        p.usesStaticLibrariesVersions, collected, collectedNames);
8989            }
8990        }
8991    }
8992
8993    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8994            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8995        final int libNameCount = libs.size();
8996        for (int i = 0; i < libNameCount; i++) {
8997            String libName = libs.get(i);
8998            int version = (versions != null && versions.length == libNameCount)
8999                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9000            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9001            if (libPkg != null) {
9002                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9003            }
9004        }
9005    }
9006
9007    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9008        synchronized (mPackages) {
9009            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9010            if (libEntry != null) {
9011                return mPackages.get(libEntry.apk);
9012            }
9013            return null;
9014        }
9015    }
9016
9017    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9018        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9019        if (versionedLib == null) {
9020            return null;
9021        }
9022        return versionedLib.get(version);
9023    }
9024
9025    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9026        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9027                pkg.staticSharedLibName);
9028        if (versionedLib == null) {
9029            return null;
9030        }
9031        int previousLibVersion = -1;
9032        final int versionCount = versionedLib.size();
9033        for (int i = 0; i < versionCount; i++) {
9034            final int libVersion = versionedLib.keyAt(i);
9035            if (libVersion < pkg.staticSharedLibVersion) {
9036                previousLibVersion = Math.max(previousLibVersion, libVersion);
9037            }
9038        }
9039        if (previousLibVersion >= 0) {
9040            return versionedLib.get(previousLibVersion);
9041        }
9042        return null;
9043    }
9044
9045    public void shutdown() {
9046        mPackageUsage.writeNow(mPackages);
9047        mCompilerStats.writeNow();
9048    }
9049
9050    @Override
9051    public void dumpProfiles(String packageName) {
9052        PackageParser.Package pkg;
9053        synchronized (mPackages) {
9054            pkg = mPackages.get(packageName);
9055            if (pkg == null) {
9056                throw new IllegalArgumentException("Unknown package: " + packageName);
9057            }
9058        }
9059        /* Only the shell, root, or the app user should be able to dump profiles. */
9060        int callingUid = Binder.getCallingUid();
9061        if (callingUid != Process.SHELL_UID &&
9062            callingUid != Process.ROOT_UID &&
9063            callingUid != pkg.applicationInfo.uid) {
9064            throw new SecurityException("dumpProfiles");
9065        }
9066
9067        synchronized (mInstallLock) {
9068            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9069            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9070            try {
9071                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9072                String codePaths = TextUtils.join(";", allCodePaths);
9073                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9074            } catch (InstallerException e) {
9075                Slog.w(TAG, "Failed to dump profiles", e);
9076            }
9077            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9078        }
9079    }
9080
9081    @Override
9082    public void forceDexOpt(String packageName) {
9083        enforceSystemOrRoot("forceDexOpt");
9084
9085        PackageParser.Package pkg;
9086        synchronized (mPackages) {
9087            pkg = mPackages.get(packageName);
9088            if (pkg == null) {
9089                throw new IllegalArgumentException("Unknown package: " + packageName);
9090            }
9091        }
9092
9093        synchronized (mInstallLock) {
9094            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9095
9096            // Whoever is calling forceDexOpt wants a compiled package.
9097            // Don't use profiles since that may cause compilation to be skipped.
9098            final int res = performDexOptInternalWithDependenciesLI(pkg,
9099                    false /* checkProfiles */, getDefaultCompilerFilter(),
9100                    true /* force */);
9101
9102            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9103            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9104                throw new IllegalStateException("Failed to dexopt: " + res);
9105            }
9106        }
9107    }
9108
9109    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9110        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9111            Slog.w(TAG, "Unable to update from " + oldPkg.name
9112                    + " to " + newPkg.packageName
9113                    + ": old package not in system partition");
9114            return false;
9115        } else if (mPackages.get(oldPkg.name) != null) {
9116            Slog.w(TAG, "Unable to update from " + oldPkg.name
9117                    + " to " + newPkg.packageName
9118                    + ": old package still exists");
9119            return false;
9120        }
9121        return true;
9122    }
9123
9124    void removeCodePathLI(File codePath) {
9125        if (codePath.isDirectory()) {
9126            try {
9127                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9128            } catch (InstallerException e) {
9129                Slog.w(TAG, "Failed to remove code path", e);
9130            }
9131        } else {
9132            codePath.delete();
9133        }
9134    }
9135
9136    private int[] resolveUserIds(int userId) {
9137        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9138    }
9139
9140    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9141        if (pkg == null) {
9142            Slog.wtf(TAG, "Package was null!", new Throwable());
9143            return;
9144        }
9145        clearAppDataLeafLIF(pkg, userId, flags);
9146        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9147        for (int i = 0; i < childCount; i++) {
9148            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9149        }
9150    }
9151
9152    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9153        final PackageSetting ps;
9154        synchronized (mPackages) {
9155            ps = mSettings.mPackages.get(pkg.packageName);
9156        }
9157        for (int realUserId : resolveUserIds(userId)) {
9158            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9159            try {
9160                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9161                        ceDataInode);
9162            } catch (InstallerException e) {
9163                Slog.w(TAG, String.valueOf(e));
9164            }
9165        }
9166    }
9167
9168    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9169        if (pkg == null) {
9170            Slog.wtf(TAG, "Package was null!", new Throwable());
9171            return;
9172        }
9173        destroyAppDataLeafLIF(pkg, userId, flags);
9174        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9175        for (int i = 0; i < childCount; i++) {
9176            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9177        }
9178    }
9179
9180    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9181        final PackageSetting ps;
9182        synchronized (mPackages) {
9183            ps = mSettings.mPackages.get(pkg.packageName);
9184        }
9185        for (int realUserId : resolveUserIds(userId)) {
9186            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9187            try {
9188                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9189                        ceDataInode);
9190            } catch (InstallerException e) {
9191                Slog.w(TAG, String.valueOf(e));
9192            }
9193            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9194        }
9195    }
9196
9197    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9198        if (pkg == null) {
9199            Slog.wtf(TAG, "Package was null!", new Throwable());
9200            return;
9201        }
9202        destroyAppProfilesLeafLIF(pkg);
9203        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9204        for (int i = 0; i < childCount; i++) {
9205            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9206        }
9207    }
9208
9209    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9210        try {
9211            mInstaller.destroyAppProfiles(pkg.packageName);
9212        } catch (InstallerException e) {
9213            Slog.w(TAG, String.valueOf(e));
9214        }
9215    }
9216
9217    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9218        if (pkg == null) {
9219            Slog.wtf(TAG, "Package was null!", new Throwable());
9220            return;
9221        }
9222        clearAppProfilesLeafLIF(pkg);
9223        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9224        for (int i = 0; i < childCount; i++) {
9225            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9226        }
9227    }
9228
9229    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9230        try {
9231            mInstaller.clearAppProfiles(pkg.packageName);
9232        } catch (InstallerException e) {
9233            Slog.w(TAG, String.valueOf(e));
9234        }
9235    }
9236
9237    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9238            long lastUpdateTime) {
9239        // Set parent install/update time
9240        PackageSetting ps = (PackageSetting) pkg.mExtras;
9241        if (ps != null) {
9242            ps.firstInstallTime = firstInstallTime;
9243            ps.lastUpdateTime = lastUpdateTime;
9244        }
9245        // Set children install/update time
9246        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9247        for (int i = 0; i < childCount; i++) {
9248            PackageParser.Package childPkg = pkg.childPackages.get(i);
9249            ps = (PackageSetting) childPkg.mExtras;
9250            if (ps != null) {
9251                ps.firstInstallTime = firstInstallTime;
9252                ps.lastUpdateTime = lastUpdateTime;
9253            }
9254        }
9255    }
9256
9257    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9258            PackageParser.Package changingLib) {
9259        if (file.path != null) {
9260            usesLibraryFiles.add(file.path);
9261            return;
9262        }
9263        PackageParser.Package p = mPackages.get(file.apk);
9264        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9265            // If we are doing this while in the middle of updating a library apk,
9266            // then we need to make sure to use that new apk for determining the
9267            // dependencies here.  (We haven't yet finished committing the new apk
9268            // to the package manager state.)
9269            if (p == null || p.packageName.equals(changingLib.packageName)) {
9270                p = changingLib;
9271            }
9272        }
9273        if (p != null) {
9274            usesLibraryFiles.addAll(p.getAllCodePaths());
9275            if (p.usesLibraryFiles != null) {
9276                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9277            }
9278        }
9279    }
9280
9281    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9282            PackageParser.Package changingLib) throws PackageManagerException {
9283        if (pkg == null) {
9284            return;
9285        }
9286        ArraySet<String> usesLibraryFiles = null;
9287        if (pkg.usesLibraries != null) {
9288            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9289                    null, null, pkg.packageName, changingLib, true, null);
9290        }
9291        if (pkg.usesStaticLibraries != null) {
9292            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9293                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9294                    pkg.packageName, changingLib, true, usesLibraryFiles);
9295        }
9296        if (pkg.usesOptionalLibraries != null) {
9297            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9298                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9299        }
9300        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9301            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9302        } else {
9303            pkg.usesLibraryFiles = null;
9304        }
9305    }
9306
9307    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9308            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9309            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9310            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9311            throws PackageManagerException {
9312        final int libCount = requestedLibraries.size();
9313        for (int i = 0; i < libCount; i++) {
9314            final String libName = requestedLibraries.get(i);
9315            final int libVersion = requiredVersions != null ? requiredVersions[i]
9316                    : SharedLibraryInfo.VERSION_UNDEFINED;
9317            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9318            if (libEntry == null) {
9319                if (required) {
9320                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9321                            "Package " + packageName + " requires unavailable shared library "
9322                                    + libName + "; failing!");
9323                } else if (DEBUG_SHARED_LIBRARIES) {
9324                    Slog.i(TAG, "Package " + packageName
9325                            + " desires unavailable shared library "
9326                            + libName + "; ignoring!");
9327                }
9328            } else {
9329                if (requiredVersions != null && requiredCertDigests != null) {
9330                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9331                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9332                            "Package " + packageName + " requires unavailable static shared"
9333                                    + " library " + libName + " version "
9334                                    + libEntry.info.getVersion() + "; failing!");
9335                    }
9336
9337                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9338                    if (libPkg == null) {
9339                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9340                                "Package " + packageName + " requires unavailable static shared"
9341                                        + " library; failing!");
9342                    }
9343
9344                    String expectedCertDigest = requiredCertDigests[i];
9345                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9346                                libPkg.mSignatures[0]);
9347                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9348                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9349                                "Package " + packageName + " requires differently signed" +
9350                                        " static shared library; failing!");
9351                    }
9352                }
9353
9354                if (outUsedLibraries == null) {
9355                    outUsedLibraries = new ArraySet<>();
9356                }
9357                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9358            }
9359        }
9360        return outUsedLibraries;
9361    }
9362
9363    private static boolean hasString(List<String> list, List<String> which) {
9364        if (list == null) {
9365            return false;
9366        }
9367        for (int i=list.size()-1; i>=0; i--) {
9368            for (int j=which.size()-1; j>=0; j--) {
9369                if (which.get(j).equals(list.get(i))) {
9370                    return true;
9371                }
9372            }
9373        }
9374        return false;
9375    }
9376
9377    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9378            PackageParser.Package changingPkg) {
9379        ArrayList<PackageParser.Package> res = null;
9380        for (PackageParser.Package pkg : mPackages.values()) {
9381            if (changingPkg != null
9382                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9383                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9384                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9385                            changingPkg.staticSharedLibName)) {
9386                return null;
9387            }
9388            if (res == null) {
9389                res = new ArrayList<>();
9390            }
9391            res.add(pkg);
9392            try {
9393                updateSharedLibrariesLPr(pkg, changingPkg);
9394            } catch (PackageManagerException e) {
9395                // If a system app update or an app and a required lib missing we
9396                // delete the package and for updated system apps keep the data as
9397                // it is better for the user to reinstall than to be in an limbo
9398                // state. Also libs disappearing under an app should never happen
9399                // - just in case.
9400                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9401                    final int flags = pkg.isUpdatedSystemApp()
9402                            ? PackageManager.DELETE_KEEP_DATA : 0;
9403                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9404                            flags , null, true, null);
9405                }
9406                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9407            }
9408        }
9409        return res;
9410    }
9411
9412    /**
9413     * Derive the value of the {@code cpuAbiOverride} based on the provided
9414     * value and an optional stored value from the package settings.
9415     */
9416    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9417        String cpuAbiOverride = null;
9418
9419        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9420            cpuAbiOverride = null;
9421        } else if (abiOverride != null) {
9422            cpuAbiOverride = abiOverride;
9423        } else if (settings != null) {
9424            cpuAbiOverride = settings.cpuAbiOverrideString;
9425        }
9426
9427        return cpuAbiOverride;
9428    }
9429
9430    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9431            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9432                    throws PackageManagerException {
9433        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9434        // If the package has children and this is the first dive in the function
9435        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9436        // whether all packages (parent and children) would be successfully scanned
9437        // before the actual scan since scanning mutates internal state and we want
9438        // to atomically install the package and its children.
9439        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9440            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9441                scanFlags |= SCAN_CHECK_ONLY;
9442            }
9443        } else {
9444            scanFlags &= ~SCAN_CHECK_ONLY;
9445        }
9446
9447        final PackageParser.Package scannedPkg;
9448        try {
9449            // Scan the parent
9450            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9451            // Scan the children
9452            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9453            for (int i = 0; i < childCount; i++) {
9454                PackageParser.Package childPkg = pkg.childPackages.get(i);
9455                scanPackageLI(childPkg, policyFlags,
9456                        scanFlags, currentTime, user);
9457            }
9458        } finally {
9459            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9460        }
9461
9462        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9463            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9464        }
9465
9466        return scannedPkg;
9467    }
9468
9469    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9470            int scanFlags, long currentTime, @Nullable UserHandle user)
9471                    throws PackageManagerException {
9472        boolean success = false;
9473        try {
9474            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9475                    currentTime, user);
9476            success = true;
9477            return res;
9478        } finally {
9479            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9480                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9481                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9482                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9483                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9484            }
9485        }
9486    }
9487
9488    /**
9489     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9490     */
9491    private static boolean apkHasCode(String fileName) {
9492        StrictJarFile jarFile = null;
9493        try {
9494            jarFile = new StrictJarFile(fileName,
9495                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9496            return jarFile.findEntry("classes.dex") != null;
9497        } catch (IOException ignore) {
9498        } finally {
9499            try {
9500                if (jarFile != null) {
9501                    jarFile.close();
9502                }
9503            } catch (IOException ignore) {}
9504        }
9505        return false;
9506    }
9507
9508    /**
9509     * Enforces code policy for the package. This ensures that if an APK has
9510     * declared hasCode="true" in its manifest that the APK actually contains
9511     * code.
9512     *
9513     * @throws PackageManagerException If bytecode could not be found when it should exist
9514     */
9515    private static void assertCodePolicy(PackageParser.Package pkg)
9516            throws PackageManagerException {
9517        final boolean shouldHaveCode =
9518                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9519        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9520            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9521                    "Package " + pkg.baseCodePath + " code is missing");
9522        }
9523
9524        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9525            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9526                final boolean splitShouldHaveCode =
9527                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9528                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9529                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9530                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9531                }
9532            }
9533        }
9534    }
9535
9536    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9537            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9538                    throws PackageManagerException {
9539        if (DEBUG_PACKAGE_SCANNING) {
9540            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9541                Log.d(TAG, "Scanning package " + pkg.packageName);
9542        }
9543
9544        applyPolicy(pkg, policyFlags);
9545
9546        assertPackageIsValid(pkg, policyFlags, scanFlags);
9547
9548        // Initialize package source and resource directories
9549        final File scanFile = new File(pkg.codePath);
9550        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9551        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9552
9553        SharedUserSetting suid = null;
9554        PackageSetting pkgSetting = null;
9555
9556        // Getting the package setting may have a side-effect, so if we
9557        // are only checking if scan would succeed, stash a copy of the
9558        // old setting to restore at the end.
9559        PackageSetting nonMutatedPs = null;
9560
9561        // We keep references to the derived CPU Abis from settings in oder to reuse
9562        // them in the case where we're not upgrading or booting for the first time.
9563        String primaryCpuAbiFromSettings = null;
9564        String secondaryCpuAbiFromSettings = null;
9565
9566        // writer
9567        synchronized (mPackages) {
9568            if (pkg.mSharedUserId != null) {
9569                // SIDE EFFECTS; may potentially allocate a new shared user
9570                suid = mSettings.getSharedUserLPw(
9571                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9572                if (DEBUG_PACKAGE_SCANNING) {
9573                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9574                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9575                                + "): packages=" + suid.packages);
9576                }
9577            }
9578
9579            // Check if we are renaming from an original package name.
9580            PackageSetting origPackage = null;
9581            String realName = null;
9582            if (pkg.mOriginalPackages != null) {
9583                // This package may need to be renamed to a previously
9584                // installed name.  Let's check on that...
9585                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9586                if (pkg.mOriginalPackages.contains(renamed)) {
9587                    // This package had originally been installed as the
9588                    // original name, and we have already taken care of
9589                    // transitioning to the new one.  Just update the new
9590                    // one to continue using the old name.
9591                    realName = pkg.mRealPackage;
9592                    if (!pkg.packageName.equals(renamed)) {
9593                        // Callers into this function may have already taken
9594                        // care of renaming the package; only do it here if
9595                        // it is not already done.
9596                        pkg.setPackageName(renamed);
9597                    }
9598                } else {
9599                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9600                        if ((origPackage = mSettings.getPackageLPr(
9601                                pkg.mOriginalPackages.get(i))) != null) {
9602                            // We do have the package already installed under its
9603                            // original name...  should we use it?
9604                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9605                                // New package is not compatible with original.
9606                                origPackage = null;
9607                                continue;
9608                            } else if (origPackage.sharedUser != null) {
9609                                // Make sure uid is compatible between packages.
9610                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9611                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9612                                            + " to " + pkg.packageName + ": old uid "
9613                                            + origPackage.sharedUser.name
9614                                            + " differs from " + pkg.mSharedUserId);
9615                                    origPackage = null;
9616                                    continue;
9617                                }
9618                                // TODO: Add case when shared user id is added [b/28144775]
9619                            } else {
9620                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9621                                        + pkg.packageName + " to old name " + origPackage.name);
9622                            }
9623                            break;
9624                        }
9625                    }
9626                }
9627            }
9628
9629            if (mTransferedPackages.contains(pkg.packageName)) {
9630                Slog.w(TAG, "Package " + pkg.packageName
9631                        + " was transferred to another, but its .apk remains");
9632            }
9633
9634            // See comments in nonMutatedPs declaration
9635            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9636                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9637                if (foundPs != null) {
9638                    nonMutatedPs = new PackageSetting(foundPs);
9639                }
9640            }
9641
9642            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9643                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9644                if (foundPs != null) {
9645                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9646                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9647                }
9648            }
9649
9650            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9651            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9652                PackageManagerService.reportSettingsProblem(Log.WARN,
9653                        "Package " + pkg.packageName + " shared user changed from "
9654                                + (pkgSetting.sharedUser != null
9655                                        ? pkgSetting.sharedUser.name : "<nothing>")
9656                                + " to "
9657                                + (suid != null ? suid.name : "<nothing>")
9658                                + "; replacing with new");
9659                pkgSetting = null;
9660            }
9661            final PackageSetting oldPkgSetting =
9662                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9663            final PackageSetting disabledPkgSetting =
9664                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9665
9666            String[] usesStaticLibraries = null;
9667            if (pkg.usesStaticLibraries != null) {
9668                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9669                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9670            }
9671
9672            if (pkgSetting == null) {
9673                final String parentPackageName = (pkg.parentPackage != null)
9674                        ? pkg.parentPackage.packageName : null;
9675                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9676                // REMOVE SharedUserSetting from method; update in a separate call
9677                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9678                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9679                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9680                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9681                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9682                        true /*allowInstall*/, instantApp, parentPackageName,
9683                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9684                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9685                // SIDE EFFECTS; updates system state; move elsewhere
9686                if (origPackage != null) {
9687                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9688                }
9689                mSettings.addUserToSettingLPw(pkgSetting);
9690            } else {
9691                // REMOVE SharedUserSetting from method; update in a separate call.
9692                //
9693                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9694                // secondaryCpuAbi are not known at this point so we always update them
9695                // to null here, only to reset them at a later point.
9696                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9697                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9698                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9699                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9700                        UserManagerService.getInstance(), usesStaticLibraries,
9701                        pkg.usesStaticLibrariesVersions);
9702            }
9703            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9704            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9705
9706            // SIDE EFFECTS; modifies system state; move elsewhere
9707            if (pkgSetting.origPackage != null) {
9708                // If we are first transitioning from an original package,
9709                // fix up the new package's name now.  We need to do this after
9710                // looking up the package under its new name, so getPackageLP
9711                // can take care of fiddling things correctly.
9712                pkg.setPackageName(origPackage.name);
9713
9714                // File a report about this.
9715                String msg = "New package " + pkgSetting.realName
9716                        + " renamed to replace old package " + pkgSetting.name;
9717                reportSettingsProblem(Log.WARN, msg);
9718
9719                // Make a note of it.
9720                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9721                    mTransferedPackages.add(origPackage.name);
9722                }
9723
9724                // No longer need to retain this.
9725                pkgSetting.origPackage = null;
9726            }
9727
9728            // SIDE EFFECTS; modifies system state; move elsewhere
9729            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9730                // Make a note of it.
9731                mTransferedPackages.add(pkg.packageName);
9732            }
9733
9734            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9735                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9736            }
9737
9738            if ((scanFlags & SCAN_BOOTING) == 0
9739                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9740                // Check all shared libraries and map to their actual file path.
9741                // We only do this here for apps not on a system dir, because those
9742                // are the only ones that can fail an install due to this.  We
9743                // will take care of the system apps by updating all of their
9744                // library paths after the scan is done. Also during the initial
9745                // scan don't update any libs as we do this wholesale after all
9746                // apps are scanned to avoid dependency based scanning.
9747                updateSharedLibrariesLPr(pkg, null);
9748            }
9749
9750            if (mFoundPolicyFile) {
9751                SELinuxMMAC.assignSeInfoValue(pkg);
9752            }
9753            pkg.applicationInfo.uid = pkgSetting.appId;
9754            pkg.mExtras = pkgSetting;
9755
9756
9757            // Static shared libs have same package with different versions where
9758            // we internally use a synthetic package name to allow multiple versions
9759            // of the same package, therefore we need to compare signatures against
9760            // the package setting for the latest library version.
9761            PackageSetting signatureCheckPs = pkgSetting;
9762            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9763                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9764                if (libraryEntry != null) {
9765                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9766                }
9767            }
9768
9769            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9770                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9771                    // We just determined the app is signed correctly, so bring
9772                    // over the latest parsed certs.
9773                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9774                } else {
9775                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9776                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9777                                "Package " + pkg.packageName + " upgrade keys do not match the "
9778                                + "previously installed version");
9779                    } else {
9780                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9781                        String msg = "System package " + pkg.packageName
9782                                + " signature changed; retaining data.";
9783                        reportSettingsProblem(Log.WARN, msg);
9784                    }
9785                }
9786            } else {
9787                try {
9788                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9789                    verifySignaturesLP(signatureCheckPs, pkg);
9790                    // We just determined the app is signed correctly, so bring
9791                    // over the latest parsed certs.
9792                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9793                } catch (PackageManagerException e) {
9794                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9795                        throw e;
9796                    }
9797                    // The signature has changed, but this package is in the system
9798                    // image...  let's recover!
9799                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9800                    // However...  if this package is part of a shared user, but it
9801                    // doesn't match the signature of the shared user, let's fail.
9802                    // What this means is that you can't change the signatures
9803                    // associated with an overall shared user, which doesn't seem all
9804                    // that unreasonable.
9805                    if (signatureCheckPs.sharedUser != null) {
9806                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9807                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9808                            throw new PackageManagerException(
9809                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9810                                    "Signature mismatch for shared user: "
9811                                            + pkgSetting.sharedUser);
9812                        }
9813                    }
9814                    // File a report about this.
9815                    String msg = "System package " + pkg.packageName
9816                            + " signature changed; retaining data.";
9817                    reportSettingsProblem(Log.WARN, msg);
9818                }
9819            }
9820
9821            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9822                // This package wants to adopt ownership of permissions from
9823                // another package.
9824                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9825                    final String origName = pkg.mAdoptPermissions.get(i);
9826                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9827                    if (orig != null) {
9828                        if (verifyPackageUpdateLPr(orig, pkg)) {
9829                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9830                                    + pkg.packageName);
9831                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9832                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9833                        }
9834                    }
9835                }
9836            }
9837        }
9838
9839        pkg.applicationInfo.processName = fixProcessName(
9840                pkg.applicationInfo.packageName,
9841                pkg.applicationInfo.processName);
9842
9843        if (pkg != mPlatformPackage) {
9844            // Get all of our default paths setup
9845            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9846        }
9847
9848        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9849
9850        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9851            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9852                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9853                derivePackageAbi(
9854                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9855                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9856
9857                // Some system apps still use directory structure for native libraries
9858                // in which case we might end up not detecting abi solely based on apk
9859                // structure. Try to detect abi based on directory structure.
9860                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9861                        pkg.applicationInfo.primaryCpuAbi == null) {
9862                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9863                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9864                }
9865            } else {
9866                // This is not a first boot or an upgrade, don't bother deriving the
9867                // ABI during the scan. Instead, trust the value that was stored in the
9868                // package setting.
9869                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9870                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9871
9872                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9873
9874                if (DEBUG_ABI_SELECTION) {
9875                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9876                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9877                        pkg.applicationInfo.secondaryCpuAbi);
9878                }
9879            }
9880        } else {
9881            if ((scanFlags & SCAN_MOVE) != 0) {
9882                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9883                // but we already have this packages package info in the PackageSetting. We just
9884                // use that and derive the native library path based on the new codepath.
9885                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9886                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9887            }
9888
9889            // Set native library paths again. For moves, the path will be updated based on the
9890            // ABIs we've determined above. For non-moves, the path will be updated based on the
9891            // ABIs we determined during compilation, but the path will depend on the final
9892            // package path (after the rename away from the stage path).
9893            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9894        }
9895
9896        // This is a special case for the "system" package, where the ABI is
9897        // dictated by the zygote configuration (and init.rc). We should keep track
9898        // of this ABI so that we can deal with "normal" applications that run under
9899        // the same UID correctly.
9900        if (mPlatformPackage == pkg) {
9901            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9902                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9903        }
9904
9905        // If there's a mismatch between the abi-override in the package setting
9906        // and the abiOverride specified for the install. Warn about this because we
9907        // would've already compiled the app without taking the package setting into
9908        // account.
9909        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9910            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9911                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9912                        " for package " + pkg.packageName);
9913            }
9914        }
9915
9916        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9917        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9918        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9919
9920        // Copy the derived override back to the parsed package, so that we can
9921        // update the package settings accordingly.
9922        pkg.cpuAbiOverride = cpuAbiOverride;
9923
9924        if (DEBUG_ABI_SELECTION) {
9925            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9926                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9927                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9928        }
9929
9930        // Push the derived path down into PackageSettings so we know what to
9931        // clean up at uninstall time.
9932        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9933
9934        if (DEBUG_ABI_SELECTION) {
9935            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9936                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9937                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9938        }
9939
9940        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9941        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9942            // We don't do this here during boot because we can do it all
9943            // at once after scanning all existing packages.
9944            //
9945            // We also do this *before* we perform dexopt on this package, so that
9946            // we can avoid redundant dexopts, and also to make sure we've got the
9947            // code and package path correct.
9948            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9949        }
9950
9951        if (mFactoryTest && pkg.requestedPermissions.contains(
9952                android.Manifest.permission.FACTORY_TEST)) {
9953            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9954        }
9955
9956        if (isSystemApp(pkg)) {
9957            pkgSetting.isOrphaned = true;
9958        }
9959
9960        // Take care of first install / last update times.
9961        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9962        if (currentTime != 0) {
9963            if (pkgSetting.firstInstallTime == 0) {
9964                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9965            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9966                pkgSetting.lastUpdateTime = currentTime;
9967            }
9968        } else if (pkgSetting.firstInstallTime == 0) {
9969            // We need *something*.  Take time time stamp of the file.
9970            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9971        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9972            if (scanFileTime != pkgSetting.timeStamp) {
9973                // A package on the system image has changed; consider this
9974                // to be an update.
9975                pkgSetting.lastUpdateTime = scanFileTime;
9976            }
9977        }
9978        pkgSetting.setTimeStamp(scanFileTime);
9979
9980        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9981            if (nonMutatedPs != null) {
9982                synchronized (mPackages) {
9983                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9984                }
9985            }
9986        } else {
9987            final int userId = user == null ? 0 : user.getIdentifier();
9988            // Modify state for the given package setting
9989            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9990                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9991            if (pkgSetting.getInstantApp(userId)) {
9992                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9993            }
9994        }
9995        return pkg;
9996    }
9997
9998    /**
9999     * Applies policy to the parsed package based upon the given policy flags.
10000     * Ensures the package is in a good state.
10001     * <p>
10002     * Implementation detail: This method must NOT have any side effect. It would
10003     * ideally be static, but, it requires locks to read system state.
10004     */
10005    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10006        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10007            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10008            if (pkg.applicationInfo.isDirectBootAware()) {
10009                // we're direct boot aware; set for all components
10010                for (PackageParser.Service s : pkg.services) {
10011                    s.info.encryptionAware = s.info.directBootAware = true;
10012                }
10013                for (PackageParser.Provider p : pkg.providers) {
10014                    p.info.encryptionAware = p.info.directBootAware = true;
10015                }
10016                for (PackageParser.Activity a : pkg.activities) {
10017                    a.info.encryptionAware = a.info.directBootAware = true;
10018                }
10019                for (PackageParser.Activity r : pkg.receivers) {
10020                    r.info.encryptionAware = r.info.directBootAware = true;
10021                }
10022            }
10023        } else {
10024            // Only allow system apps to be flagged as core apps.
10025            pkg.coreApp = false;
10026            // clear flags not applicable to regular apps
10027            pkg.applicationInfo.privateFlags &=
10028                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10029            pkg.applicationInfo.privateFlags &=
10030                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10031        }
10032        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10033
10034        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10035            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10036        }
10037
10038        if (!isSystemApp(pkg)) {
10039            // Only system apps can use these features.
10040            pkg.mOriginalPackages = null;
10041            pkg.mRealPackage = null;
10042            pkg.mAdoptPermissions = null;
10043        }
10044    }
10045
10046    /**
10047     * Asserts the parsed package is valid according to the given policy. If the
10048     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10049     * <p>
10050     * Implementation detail: This method must NOT have any side effects. It would
10051     * ideally be static, but, it requires locks to read system state.
10052     *
10053     * @throws PackageManagerException If the package fails any of the validation checks
10054     */
10055    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10056            throws PackageManagerException {
10057        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10058            assertCodePolicy(pkg);
10059        }
10060
10061        if (pkg.applicationInfo.getCodePath() == null ||
10062                pkg.applicationInfo.getResourcePath() == null) {
10063            // Bail out. The resource and code paths haven't been set.
10064            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10065                    "Code and resource paths haven't been set correctly");
10066        }
10067
10068        // Make sure we're not adding any bogus keyset info
10069        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10070        ksms.assertScannedPackageValid(pkg);
10071
10072        synchronized (mPackages) {
10073            // The special "android" package can only be defined once
10074            if (pkg.packageName.equals("android")) {
10075                if (mAndroidApplication != null) {
10076                    Slog.w(TAG, "*************************************************");
10077                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10078                    Slog.w(TAG, " codePath=" + pkg.codePath);
10079                    Slog.w(TAG, "*************************************************");
10080                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10081                            "Core android package being redefined.  Skipping.");
10082                }
10083            }
10084
10085            // A package name must be unique; don't allow duplicates
10086            if (mPackages.containsKey(pkg.packageName)) {
10087                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10088                        "Application package " + pkg.packageName
10089                        + " already installed.  Skipping duplicate.");
10090            }
10091
10092            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10093                // Static libs have a synthetic package name containing the version
10094                // but we still want the base name to be unique.
10095                if (mPackages.containsKey(pkg.manifestPackageName)) {
10096                    throw new PackageManagerException(
10097                            "Duplicate static shared lib provider package");
10098                }
10099
10100                // Static shared libraries should have at least O target SDK
10101                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10102                    throw new PackageManagerException(
10103                            "Packages declaring static-shared libs must target O SDK or higher");
10104                }
10105
10106                // Package declaring static a shared lib cannot be instant apps
10107                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10108                    throw new PackageManagerException(
10109                            "Packages declaring static-shared libs cannot be instant apps");
10110                }
10111
10112                // Package declaring static a shared lib cannot be renamed since the package
10113                // name is synthetic and apps can't code around package manager internals.
10114                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10115                    throw new PackageManagerException(
10116                            "Packages declaring static-shared libs cannot be renamed");
10117                }
10118
10119                // Package declaring static a shared lib cannot declare child packages
10120                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10121                    throw new PackageManagerException(
10122                            "Packages declaring static-shared libs cannot have child packages");
10123                }
10124
10125                // Package declaring static a shared lib cannot declare dynamic libs
10126                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10127                    throw new PackageManagerException(
10128                            "Packages declaring static-shared libs cannot declare dynamic libs");
10129                }
10130
10131                // Package declaring static a shared lib cannot declare shared users
10132                if (pkg.mSharedUserId != null) {
10133                    throw new PackageManagerException(
10134                            "Packages declaring static-shared libs cannot declare shared users");
10135                }
10136
10137                // Static shared libs cannot declare activities
10138                if (!pkg.activities.isEmpty()) {
10139                    throw new PackageManagerException(
10140                            "Static shared libs cannot declare activities");
10141                }
10142
10143                // Static shared libs cannot declare services
10144                if (!pkg.services.isEmpty()) {
10145                    throw new PackageManagerException(
10146                            "Static shared libs cannot declare services");
10147                }
10148
10149                // Static shared libs cannot declare providers
10150                if (!pkg.providers.isEmpty()) {
10151                    throw new PackageManagerException(
10152                            "Static shared libs cannot declare content providers");
10153                }
10154
10155                // Static shared libs cannot declare receivers
10156                if (!pkg.receivers.isEmpty()) {
10157                    throw new PackageManagerException(
10158                            "Static shared libs cannot declare broadcast receivers");
10159                }
10160
10161                // Static shared libs cannot declare permission groups
10162                if (!pkg.permissionGroups.isEmpty()) {
10163                    throw new PackageManagerException(
10164                            "Static shared libs cannot declare permission groups");
10165                }
10166
10167                // Static shared libs cannot declare permissions
10168                if (!pkg.permissions.isEmpty()) {
10169                    throw new PackageManagerException(
10170                            "Static shared libs cannot declare permissions");
10171                }
10172
10173                // Static shared libs cannot declare protected broadcasts
10174                if (pkg.protectedBroadcasts != null) {
10175                    throw new PackageManagerException(
10176                            "Static shared libs cannot declare protected broadcasts");
10177                }
10178
10179                // Static shared libs cannot be overlay targets
10180                if (pkg.mOverlayTarget != null) {
10181                    throw new PackageManagerException(
10182                            "Static shared libs cannot be overlay targets");
10183                }
10184
10185                // The version codes must be ordered as lib versions
10186                int minVersionCode = Integer.MIN_VALUE;
10187                int maxVersionCode = Integer.MAX_VALUE;
10188
10189                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10190                        pkg.staticSharedLibName);
10191                if (versionedLib != null) {
10192                    final int versionCount = versionedLib.size();
10193                    for (int i = 0; i < versionCount; i++) {
10194                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10195                        // TODO: We will change version code to long, so in the new API it is long
10196                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10197                                .getVersionCode();
10198                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10199                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10200                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10201                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10202                        } else {
10203                            minVersionCode = maxVersionCode = libVersionCode;
10204                            break;
10205                        }
10206                    }
10207                }
10208                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10209                    throw new PackageManagerException("Static shared"
10210                            + " lib version codes must be ordered as lib versions");
10211                }
10212            }
10213
10214            // Only privileged apps and updated privileged apps can add child packages.
10215            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10216                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10217                    throw new PackageManagerException("Only privileged apps can add child "
10218                            + "packages. Ignoring package " + pkg.packageName);
10219                }
10220                final int childCount = pkg.childPackages.size();
10221                for (int i = 0; i < childCount; i++) {
10222                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10223                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10224                            childPkg.packageName)) {
10225                        throw new PackageManagerException("Can't override child of "
10226                                + "another disabled app. Ignoring package " + pkg.packageName);
10227                    }
10228                }
10229            }
10230
10231            // If we're only installing presumed-existing packages, require that the
10232            // scanned APK is both already known and at the path previously established
10233            // for it.  Previously unknown packages we pick up normally, but if we have an
10234            // a priori expectation about this package's install presence, enforce it.
10235            // With a singular exception for new system packages. When an OTA contains
10236            // a new system package, we allow the codepath to change from a system location
10237            // to the user-installed location. If we don't allow this change, any newer,
10238            // user-installed version of the application will be ignored.
10239            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10240                if (mExpectingBetter.containsKey(pkg.packageName)) {
10241                    logCriticalInfo(Log.WARN,
10242                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10243                } else {
10244                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10245                    if (known != null) {
10246                        if (DEBUG_PACKAGE_SCANNING) {
10247                            Log.d(TAG, "Examining " + pkg.codePath
10248                                    + " and requiring known paths " + known.codePathString
10249                                    + " & " + known.resourcePathString);
10250                        }
10251                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10252                                || !pkg.applicationInfo.getResourcePath().equals(
10253                                        known.resourcePathString)) {
10254                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10255                                    "Application package " + pkg.packageName
10256                                    + " found at " + pkg.applicationInfo.getCodePath()
10257                                    + " but expected at " + known.codePathString
10258                                    + "; ignoring.");
10259                        }
10260                    }
10261                }
10262            }
10263
10264            // Verify that this new package doesn't have any content providers
10265            // that conflict with existing packages.  Only do this if the
10266            // package isn't already installed, since we don't want to break
10267            // things that are installed.
10268            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10269                final int N = pkg.providers.size();
10270                int i;
10271                for (i=0; i<N; i++) {
10272                    PackageParser.Provider p = pkg.providers.get(i);
10273                    if (p.info.authority != null) {
10274                        String names[] = p.info.authority.split(";");
10275                        for (int j = 0; j < names.length; j++) {
10276                            if (mProvidersByAuthority.containsKey(names[j])) {
10277                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10278                                final String otherPackageName =
10279                                        ((other != null && other.getComponentName() != null) ?
10280                                                other.getComponentName().getPackageName() : "?");
10281                                throw new PackageManagerException(
10282                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10283                                        "Can't install because provider name " + names[j]
10284                                                + " (in package " + pkg.applicationInfo.packageName
10285                                                + ") is already used by " + otherPackageName);
10286                            }
10287                        }
10288                    }
10289                }
10290            }
10291        }
10292    }
10293
10294    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10295            int type, String declaringPackageName, int declaringVersionCode) {
10296        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10297        if (versionedLib == null) {
10298            versionedLib = new SparseArray<>();
10299            mSharedLibraries.put(name, versionedLib);
10300            if (type == SharedLibraryInfo.TYPE_STATIC) {
10301                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10302            }
10303        } else if (versionedLib.indexOfKey(version) >= 0) {
10304            return false;
10305        }
10306        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10307                version, type, declaringPackageName, declaringVersionCode);
10308        versionedLib.put(version, libEntry);
10309        return true;
10310    }
10311
10312    private boolean removeSharedLibraryLPw(String name, int version) {
10313        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10314        if (versionedLib == null) {
10315            return false;
10316        }
10317        final int libIdx = versionedLib.indexOfKey(version);
10318        if (libIdx < 0) {
10319            return false;
10320        }
10321        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10322        versionedLib.remove(version);
10323        if (versionedLib.size() <= 0) {
10324            mSharedLibraries.remove(name);
10325            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10326                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10327                        .getPackageName());
10328            }
10329        }
10330        return true;
10331    }
10332
10333    /**
10334     * Adds a scanned package to the system. When this method is finished, the package will
10335     * be available for query, resolution, etc...
10336     */
10337    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10338            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10339        final String pkgName = pkg.packageName;
10340        if (mCustomResolverComponentName != null &&
10341                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10342            setUpCustomResolverActivity(pkg);
10343        }
10344
10345        if (pkg.packageName.equals("android")) {
10346            synchronized (mPackages) {
10347                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10348                    // Set up information for our fall-back user intent resolution activity.
10349                    mPlatformPackage = pkg;
10350                    pkg.mVersionCode = mSdkVersion;
10351                    mAndroidApplication = pkg.applicationInfo;
10352                    if (!mResolverReplaced) {
10353                        mResolveActivity.applicationInfo = mAndroidApplication;
10354                        mResolveActivity.name = ResolverActivity.class.getName();
10355                        mResolveActivity.packageName = mAndroidApplication.packageName;
10356                        mResolveActivity.processName = "system:ui";
10357                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10358                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10359                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10360                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10361                        mResolveActivity.exported = true;
10362                        mResolveActivity.enabled = true;
10363                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10364                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10365                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10366                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10367                                | ActivityInfo.CONFIG_ORIENTATION
10368                                | ActivityInfo.CONFIG_KEYBOARD
10369                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10370                        mResolveInfo.activityInfo = mResolveActivity;
10371                        mResolveInfo.priority = 0;
10372                        mResolveInfo.preferredOrder = 0;
10373                        mResolveInfo.match = 0;
10374                        mResolveComponentName = new ComponentName(
10375                                mAndroidApplication.packageName, mResolveActivity.name);
10376                    }
10377                }
10378            }
10379        }
10380
10381        ArrayList<PackageParser.Package> clientLibPkgs = null;
10382        // writer
10383        synchronized (mPackages) {
10384            boolean hasStaticSharedLibs = false;
10385
10386            // Any app can add new static shared libraries
10387            if (pkg.staticSharedLibName != null) {
10388                // Static shared libs don't allow renaming as they have synthetic package
10389                // names to allow install of multiple versions, so use name from manifest.
10390                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10391                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10392                        pkg.manifestPackageName, pkg.mVersionCode)) {
10393                    hasStaticSharedLibs = true;
10394                } else {
10395                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10396                                + pkg.staticSharedLibName + " already exists; skipping");
10397                }
10398                // Static shared libs cannot be updated once installed since they
10399                // use synthetic package name which includes the version code, so
10400                // not need to update other packages's shared lib dependencies.
10401            }
10402
10403            if (!hasStaticSharedLibs
10404                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10405                // Only system apps can add new dynamic shared libraries.
10406                if (pkg.libraryNames != null) {
10407                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10408                        String name = pkg.libraryNames.get(i);
10409                        boolean allowed = false;
10410                        if (pkg.isUpdatedSystemApp()) {
10411                            // New library entries can only be added through the
10412                            // system image.  This is important to get rid of a lot
10413                            // of nasty edge cases: for example if we allowed a non-
10414                            // system update of the app to add a library, then uninstalling
10415                            // the update would make the library go away, and assumptions
10416                            // we made such as through app install filtering would now
10417                            // have allowed apps on the device which aren't compatible
10418                            // with it.  Better to just have the restriction here, be
10419                            // conservative, and create many fewer cases that can negatively
10420                            // impact the user experience.
10421                            final PackageSetting sysPs = mSettings
10422                                    .getDisabledSystemPkgLPr(pkg.packageName);
10423                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10424                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10425                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10426                                        allowed = true;
10427                                        break;
10428                                    }
10429                                }
10430                            }
10431                        } else {
10432                            allowed = true;
10433                        }
10434                        if (allowed) {
10435                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10436                                    SharedLibraryInfo.VERSION_UNDEFINED,
10437                                    SharedLibraryInfo.TYPE_DYNAMIC,
10438                                    pkg.packageName, pkg.mVersionCode)) {
10439                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10440                                        + name + " already exists; skipping");
10441                            }
10442                        } else {
10443                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10444                                    + name + " that is not declared on system image; skipping");
10445                        }
10446                    }
10447
10448                    if ((scanFlags & SCAN_BOOTING) == 0) {
10449                        // If we are not booting, we need to update any applications
10450                        // that are clients of our shared library.  If we are booting,
10451                        // this will all be done once the scan is complete.
10452                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10453                    }
10454                }
10455            }
10456        }
10457
10458        if ((scanFlags & SCAN_BOOTING) != 0) {
10459            // No apps can run during boot scan, so they don't need to be frozen
10460        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10461            // Caller asked to not kill app, so it's probably not frozen
10462        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10463            // Caller asked us to ignore frozen check for some reason; they
10464            // probably didn't know the package name
10465        } else {
10466            // We're doing major surgery on this package, so it better be frozen
10467            // right now to keep it from launching
10468            checkPackageFrozen(pkgName);
10469        }
10470
10471        // Also need to kill any apps that are dependent on the library.
10472        if (clientLibPkgs != null) {
10473            for (int i=0; i<clientLibPkgs.size(); i++) {
10474                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10475                killApplication(clientPkg.applicationInfo.packageName,
10476                        clientPkg.applicationInfo.uid, "update lib");
10477            }
10478        }
10479
10480        // writer
10481        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10482
10483        synchronized (mPackages) {
10484            // We don't expect installation to fail beyond this point
10485
10486            // Add the new setting to mSettings
10487            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10488            // Add the new setting to mPackages
10489            mPackages.put(pkg.applicationInfo.packageName, pkg);
10490            // Make sure we don't accidentally delete its data.
10491            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10492            while (iter.hasNext()) {
10493                PackageCleanItem item = iter.next();
10494                if (pkgName.equals(item.packageName)) {
10495                    iter.remove();
10496                }
10497            }
10498
10499            // Add the package's KeySets to the global KeySetManagerService
10500            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10501            ksms.addScannedPackageLPw(pkg);
10502
10503            int N = pkg.providers.size();
10504            StringBuilder r = null;
10505            int i;
10506            for (i=0; i<N; i++) {
10507                PackageParser.Provider p = pkg.providers.get(i);
10508                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10509                        p.info.processName);
10510                mProviders.addProvider(p);
10511                p.syncable = p.info.isSyncable;
10512                if (p.info.authority != null) {
10513                    String names[] = p.info.authority.split(";");
10514                    p.info.authority = null;
10515                    for (int j = 0; j < names.length; j++) {
10516                        if (j == 1 && p.syncable) {
10517                            // We only want the first authority for a provider to possibly be
10518                            // syncable, so if we already added this provider using a different
10519                            // authority clear the syncable flag. We copy the provider before
10520                            // changing it because the mProviders object contains a reference
10521                            // to a provider that we don't want to change.
10522                            // Only do this for the second authority since the resulting provider
10523                            // object can be the same for all future authorities for this provider.
10524                            p = new PackageParser.Provider(p);
10525                            p.syncable = false;
10526                        }
10527                        if (!mProvidersByAuthority.containsKey(names[j])) {
10528                            mProvidersByAuthority.put(names[j], p);
10529                            if (p.info.authority == null) {
10530                                p.info.authority = names[j];
10531                            } else {
10532                                p.info.authority = p.info.authority + ";" + names[j];
10533                            }
10534                            if (DEBUG_PACKAGE_SCANNING) {
10535                                if (chatty)
10536                                    Log.d(TAG, "Registered content provider: " + names[j]
10537                                            + ", className = " + p.info.name + ", isSyncable = "
10538                                            + p.info.isSyncable);
10539                            }
10540                        } else {
10541                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10542                            Slog.w(TAG, "Skipping provider name " + names[j] +
10543                                    " (in package " + pkg.applicationInfo.packageName +
10544                                    "): name already used by "
10545                                    + ((other != null && other.getComponentName() != null)
10546                                            ? other.getComponentName().getPackageName() : "?"));
10547                        }
10548                    }
10549                }
10550                if (chatty) {
10551                    if (r == null) {
10552                        r = new StringBuilder(256);
10553                    } else {
10554                        r.append(' ');
10555                    }
10556                    r.append(p.info.name);
10557                }
10558            }
10559            if (r != null) {
10560                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10561            }
10562
10563            N = pkg.services.size();
10564            r = null;
10565            for (i=0; i<N; i++) {
10566                PackageParser.Service s = pkg.services.get(i);
10567                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10568                        s.info.processName);
10569                mServices.addService(s);
10570                if (chatty) {
10571                    if (r == null) {
10572                        r = new StringBuilder(256);
10573                    } else {
10574                        r.append(' ');
10575                    }
10576                    r.append(s.info.name);
10577                }
10578            }
10579            if (r != null) {
10580                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10581            }
10582
10583            N = pkg.receivers.size();
10584            r = null;
10585            for (i=0; i<N; i++) {
10586                PackageParser.Activity a = pkg.receivers.get(i);
10587                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10588                        a.info.processName);
10589                mReceivers.addActivity(a, "receiver");
10590                if (chatty) {
10591                    if (r == null) {
10592                        r = new StringBuilder(256);
10593                    } else {
10594                        r.append(' ');
10595                    }
10596                    r.append(a.info.name);
10597                }
10598            }
10599            if (r != null) {
10600                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10601            }
10602
10603            N = pkg.activities.size();
10604            r = null;
10605            for (i=0; i<N; i++) {
10606                PackageParser.Activity a = pkg.activities.get(i);
10607                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10608                        a.info.processName);
10609                mActivities.addActivity(a, "activity");
10610                if (chatty) {
10611                    if (r == null) {
10612                        r = new StringBuilder(256);
10613                    } else {
10614                        r.append(' ');
10615                    }
10616                    r.append(a.info.name);
10617                }
10618            }
10619            if (r != null) {
10620                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10621            }
10622
10623            N = pkg.permissionGroups.size();
10624            r = null;
10625            for (i=0; i<N; i++) {
10626                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10627                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10628                final String curPackageName = cur == null ? null : cur.info.packageName;
10629                // Dont allow ephemeral apps to define new permission groups.
10630                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10631                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10632                            + pg.info.packageName
10633                            + " ignored: instant apps cannot define new permission groups.");
10634                    continue;
10635                }
10636                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10637                if (cur == null || isPackageUpdate) {
10638                    mPermissionGroups.put(pg.info.name, pg);
10639                    if (chatty) {
10640                        if (r == null) {
10641                            r = new StringBuilder(256);
10642                        } else {
10643                            r.append(' ');
10644                        }
10645                        if (isPackageUpdate) {
10646                            r.append("UPD:");
10647                        }
10648                        r.append(pg.info.name);
10649                    }
10650                } else {
10651                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10652                            + pg.info.packageName + " ignored: original from "
10653                            + cur.info.packageName);
10654                    if (chatty) {
10655                        if (r == null) {
10656                            r = new StringBuilder(256);
10657                        } else {
10658                            r.append(' ');
10659                        }
10660                        r.append("DUP:");
10661                        r.append(pg.info.name);
10662                    }
10663                }
10664            }
10665            if (r != null) {
10666                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10667            }
10668
10669            N = pkg.permissions.size();
10670            r = null;
10671            for (i=0; i<N; i++) {
10672                PackageParser.Permission p = pkg.permissions.get(i);
10673
10674                // Dont allow ephemeral apps to define new permissions.
10675                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10676                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10677                            + p.info.packageName
10678                            + " ignored: instant apps cannot define new permissions.");
10679                    continue;
10680                }
10681
10682                // Assume by default that we did not install this permission into the system.
10683                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10684
10685                // Now that permission groups have a special meaning, we ignore permission
10686                // groups for legacy apps to prevent unexpected behavior. In particular,
10687                // permissions for one app being granted to someone just because they happen
10688                // to be in a group defined by another app (before this had no implications).
10689                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10690                    p.group = mPermissionGroups.get(p.info.group);
10691                    // Warn for a permission in an unknown group.
10692                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
10693                        Slog.i(TAG, "Permission " + p.info.name + " from package "
10694                                + p.info.packageName + " in an unknown group " + p.info.group);
10695                    }
10696                }
10697
10698                ArrayMap<String, BasePermission> permissionMap =
10699                        p.tree ? mSettings.mPermissionTrees
10700                                : mSettings.mPermissions;
10701                BasePermission bp = permissionMap.get(p.info.name);
10702
10703                // Allow system apps to redefine non-system permissions
10704                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10705                    final boolean currentOwnerIsSystem = (bp.perm != null
10706                            && isSystemApp(bp.perm.owner));
10707                    if (isSystemApp(p.owner)) {
10708                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10709                            // It's a built-in permission and no owner, take ownership now
10710                            bp.packageSetting = pkgSetting;
10711                            bp.perm = p;
10712                            bp.uid = pkg.applicationInfo.uid;
10713                            bp.sourcePackage = p.info.packageName;
10714                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10715                        } else if (!currentOwnerIsSystem) {
10716                            String msg = "New decl " + p.owner + " of permission  "
10717                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10718                            reportSettingsProblem(Log.WARN, msg);
10719                            bp = null;
10720                        }
10721                    }
10722                }
10723
10724                if (bp == null) {
10725                    bp = new BasePermission(p.info.name, p.info.packageName,
10726                            BasePermission.TYPE_NORMAL);
10727                    permissionMap.put(p.info.name, bp);
10728                }
10729
10730                if (bp.perm == null) {
10731                    if (bp.sourcePackage == null
10732                            || bp.sourcePackage.equals(p.info.packageName)) {
10733                        BasePermission tree = findPermissionTreeLP(p.info.name);
10734                        if (tree == null
10735                                || tree.sourcePackage.equals(p.info.packageName)) {
10736                            bp.packageSetting = pkgSetting;
10737                            bp.perm = p;
10738                            bp.uid = pkg.applicationInfo.uid;
10739                            bp.sourcePackage = p.info.packageName;
10740                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10741                            if (chatty) {
10742                                if (r == null) {
10743                                    r = new StringBuilder(256);
10744                                } else {
10745                                    r.append(' ');
10746                                }
10747                                r.append(p.info.name);
10748                            }
10749                        } else {
10750                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10751                                    + p.info.packageName + " ignored: base tree "
10752                                    + tree.name + " is from package "
10753                                    + tree.sourcePackage);
10754                        }
10755                    } else {
10756                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10757                                + p.info.packageName + " ignored: original from "
10758                                + bp.sourcePackage);
10759                    }
10760                } else if (chatty) {
10761                    if (r == null) {
10762                        r = new StringBuilder(256);
10763                    } else {
10764                        r.append(' ');
10765                    }
10766                    r.append("DUP:");
10767                    r.append(p.info.name);
10768                }
10769                if (bp.perm == p) {
10770                    bp.protectionLevel = p.info.protectionLevel;
10771                }
10772            }
10773
10774            if (r != null) {
10775                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10776            }
10777
10778            N = pkg.instrumentation.size();
10779            r = null;
10780            for (i=0; i<N; i++) {
10781                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10782                a.info.packageName = pkg.applicationInfo.packageName;
10783                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10784                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10785                a.info.splitNames = pkg.splitNames;
10786                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10787                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10788                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10789                a.info.dataDir = pkg.applicationInfo.dataDir;
10790                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10791                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10792                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10793                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10794                mInstrumentation.put(a.getComponentName(), a);
10795                if (chatty) {
10796                    if (r == null) {
10797                        r = new StringBuilder(256);
10798                    } else {
10799                        r.append(' ');
10800                    }
10801                    r.append(a.info.name);
10802                }
10803            }
10804            if (r != null) {
10805                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10806            }
10807
10808            if (pkg.protectedBroadcasts != null) {
10809                N = pkg.protectedBroadcasts.size();
10810                for (i=0; i<N; i++) {
10811                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10812                }
10813            }
10814        }
10815
10816        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10817    }
10818
10819    /**
10820     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10821     * is derived purely on the basis of the contents of {@code scanFile} and
10822     * {@code cpuAbiOverride}.
10823     *
10824     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10825     */
10826    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10827                                 String cpuAbiOverride, boolean extractLibs,
10828                                 File appLib32InstallDir)
10829            throws PackageManagerException {
10830        // Give ourselves some initial paths; we'll come back for another
10831        // pass once we've determined ABI below.
10832        setNativeLibraryPaths(pkg, appLib32InstallDir);
10833
10834        // We would never need to extract libs for forward-locked and external packages,
10835        // since the container service will do it for us. We shouldn't attempt to
10836        // extract libs from system app when it was not updated.
10837        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10838                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10839            extractLibs = false;
10840        }
10841
10842        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10843        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10844
10845        NativeLibraryHelper.Handle handle = null;
10846        try {
10847            handle = NativeLibraryHelper.Handle.create(pkg);
10848            // TODO(multiArch): This can be null for apps that didn't go through the
10849            // usual installation process. We can calculate it again, like we
10850            // do during install time.
10851            //
10852            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10853            // unnecessary.
10854            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10855
10856            // Null out the abis so that they can be recalculated.
10857            pkg.applicationInfo.primaryCpuAbi = null;
10858            pkg.applicationInfo.secondaryCpuAbi = null;
10859            if (isMultiArch(pkg.applicationInfo)) {
10860                // Warn if we've set an abiOverride for multi-lib packages..
10861                // By definition, we need to copy both 32 and 64 bit libraries for
10862                // such packages.
10863                if (pkg.cpuAbiOverride != null
10864                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10865                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10866                }
10867
10868                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10869                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10870                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10871                    if (extractLibs) {
10872                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10873                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10874                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10875                                useIsaSpecificSubdirs);
10876                    } else {
10877                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10878                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10879                    }
10880                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10881                }
10882
10883                maybeThrowExceptionForMultiArchCopy(
10884                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10885
10886                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10887                    if (extractLibs) {
10888                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10889                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10890                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10891                                useIsaSpecificSubdirs);
10892                    } else {
10893                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10894                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10895                    }
10896                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10897                }
10898
10899                maybeThrowExceptionForMultiArchCopy(
10900                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10901
10902                if (abi64 >= 0) {
10903                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10904                }
10905
10906                if (abi32 >= 0) {
10907                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10908                    if (abi64 >= 0) {
10909                        if (pkg.use32bitAbi) {
10910                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10911                            pkg.applicationInfo.primaryCpuAbi = abi;
10912                        } else {
10913                            pkg.applicationInfo.secondaryCpuAbi = abi;
10914                        }
10915                    } else {
10916                        pkg.applicationInfo.primaryCpuAbi = abi;
10917                    }
10918                }
10919
10920            } else {
10921                String[] abiList = (cpuAbiOverride != null) ?
10922                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10923
10924                // Enable gross and lame hacks for apps that are built with old
10925                // SDK tools. We must scan their APKs for renderscript bitcode and
10926                // not launch them if it's present. Don't bother checking on devices
10927                // that don't have 64 bit support.
10928                boolean needsRenderScriptOverride = false;
10929                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10930                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10931                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10932                    needsRenderScriptOverride = true;
10933                }
10934
10935                final int copyRet;
10936                if (extractLibs) {
10937                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10938                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10939                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10940                } else {
10941                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10942                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10943                }
10944                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10945
10946                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10947                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10948                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10949                }
10950
10951                if (copyRet >= 0) {
10952                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10953                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10954                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10955                } else if (needsRenderScriptOverride) {
10956                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10957                }
10958            }
10959        } catch (IOException ioe) {
10960            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10961        } finally {
10962            IoUtils.closeQuietly(handle);
10963        }
10964
10965        // Now that we've calculated the ABIs and determined if it's an internal app,
10966        // we will go ahead and populate the nativeLibraryPath.
10967        setNativeLibraryPaths(pkg, appLib32InstallDir);
10968    }
10969
10970    /**
10971     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10972     * i.e, so that all packages can be run inside a single process if required.
10973     *
10974     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10975     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10976     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10977     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10978     * updating a package that belongs to a shared user.
10979     *
10980     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10981     * adds unnecessary complexity.
10982     */
10983    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10984            PackageParser.Package scannedPackage) {
10985        String requiredInstructionSet = null;
10986        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10987            requiredInstructionSet = VMRuntime.getInstructionSet(
10988                     scannedPackage.applicationInfo.primaryCpuAbi);
10989        }
10990
10991        PackageSetting requirer = null;
10992        for (PackageSetting ps : packagesForUser) {
10993            // If packagesForUser contains scannedPackage, we skip it. This will happen
10994            // when scannedPackage is an update of an existing package. Without this check,
10995            // we will never be able to change the ABI of any package belonging to a shared
10996            // user, even if it's compatible with other packages.
10997            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10998                if (ps.primaryCpuAbiString == null) {
10999                    continue;
11000                }
11001
11002                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11003                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11004                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11005                    // this but there's not much we can do.
11006                    String errorMessage = "Instruction set mismatch, "
11007                            + ((requirer == null) ? "[caller]" : requirer)
11008                            + " requires " + requiredInstructionSet + " whereas " + ps
11009                            + " requires " + instructionSet;
11010                    Slog.w(TAG, errorMessage);
11011                }
11012
11013                if (requiredInstructionSet == null) {
11014                    requiredInstructionSet = instructionSet;
11015                    requirer = ps;
11016                }
11017            }
11018        }
11019
11020        if (requiredInstructionSet != null) {
11021            String adjustedAbi;
11022            if (requirer != null) {
11023                // requirer != null implies that either scannedPackage was null or that scannedPackage
11024                // did not require an ABI, in which case we have to adjust scannedPackage to match
11025                // the ABI of the set (which is the same as requirer's ABI)
11026                adjustedAbi = requirer.primaryCpuAbiString;
11027                if (scannedPackage != null) {
11028                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11029                }
11030            } else {
11031                // requirer == null implies that we're updating all ABIs in the set to
11032                // match scannedPackage.
11033                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11034            }
11035
11036            for (PackageSetting ps : packagesForUser) {
11037                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11038                    if (ps.primaryCpuAbiString != null) {
11039                        continue;
11040                    }
11041
11042                    ps.primaryCpuAbiString = adjustedAbi;
11043                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11044                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11045                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11046                        if (DEBUG_ABI_SELECTION) {
11047                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11048                                    + " (requirer="
11049                                    + (requirer != null ? requirer.pkg : "null")
11050                                    + ", scannedPackage="
11051                                    + (scannedPackage != null ? scannedPackage : "null")
11052                                    + ")");
11053                        }
11054                        try {
11055                            mInstaller.rmdex(ps.codePathString,
11056                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11057                        } catch (InstallerException ignored) {
11058                        }
11059                    }
11060                }
11061            }
11062        }
11063    }
11064
11065    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11066        synchronized (mPackages) {
11067            mResolverReplaced = true;
11068            // Set up information for custom user intent resolution activity.
11069            mResolveActivity.applicationInfo = pkg.applicationInfo;
11070            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11071            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11072            mResolveActivity.processName = pkg.applicationInfo.packageName;
11073            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11074            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11075                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11076            mResolveActivity.theme = 0;
11077            mResolveActivity.exported = true;
11078            mResolveActivity.enabled = true;
11079            mResolveInfo.activityInfo = mResolveActivity;
11080            mResolveInfo.priority = 0;
11081            mResolveInfo.preferredOrder = 0;
11082            mResolveInfo.match = 0;
11083            mResolveComponentName = mCustomResolverComponentName;
11084            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11085                    mResolveComponentName);
11086        }
11087    }
11088
11089    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11090        if (installerActivity == null) {
11091            if (DEBUG_EPHEMERAL) {
11092                Slog.d(TAG, "Clear ephemeral installer activity");
11093            }
11094            mInstantAppInstallerActivity = null;
11095            return;
11096        }
11097
11098        if (DEBUG_EPHEMERAL) {
11099            Slog.d(TAG, "Set ephemeral installer activity: "
11100                    + installerActivity.getComponentName());
11101        }
11102        // Set up information for ephemeral installer activity
11103        mInstantAppInstallerActivity = installerActivity;
11104        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11105                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11106        mInstantAppInstallerActivity.exported = true;
11107        mInstantAppInstallerActivity.enabled = true;
11108        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11109        mInstantAppInstallerInfo.priority = 0;
11110        mInstantAppInstallerInfo.preferredOrder = 1;
11111        mInstantAppInstallerInfo.isDefault = true;
11112        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11113                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11114    }
11115
11116    private static String calculateBundledApkRoot(final String codePathString) {
11117        final File codePath = new File(codePathString);
11118        final File codeRoot;
11119        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11120            codeRoot = Environment.getRootDirectory();
11121        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11122            codeRoot = Environment.getOemDirectory();
11123        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11124            codeRoot = Environment.getVendorDirectory();
11125        } else {
11126            // Unrecognized code path; take its top real segment as the apk root:
11127            // e.g. /something/app/blah.apk => /something
11128            try {
11129                File f = codePath.getCanonicalFile();
11130                File parent = f.getParentFile();    // non-null because codePath is a file
11131                File tmp;
11132                while ((tmp = parent.getParentFile()) != null) {
11133                    f = parent;
11134                    parent = tmp;
11135                }
11136                codeRoot = f;
11137                Slog.w(TAG, "Unrecognized code path "
11138                        + codePath + " - using " + codeRoot);
11139            } catch (IOException e) {
11140                // Can't canonicalize the code path -- shenanigans?
11141                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11142                return Environment.getRootDirectory().getPath();
11143            }
11144        }
11145        return codeRoot.getPath();
11146    }
11147
11148    /**
11149     * Derive and set the location of native libraries for the given package,
11150     * which varies depending on where and how the package was installed.
11151     */
11152    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11153        final ApplicationInfo info = pkg.applicationInfo;
11154        final String codePath = pkg.codePath;
11155        final File codeFile = new File(codePath);
11156        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11157        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11158
11159        info.nativeLibraryRootDir = null;
11160        info.nativeLibraryRootRequiresIsa = false;
11161        info.nativeLibraryDir = null;
11162        info.secondaryNativeLibraryDir = null;
11163
11164        if (isApkFile(codeFile)) {
11165            // Monolithic install
11166            if (bundledApp) {
11167                // If "/system/lib64/apkname" exists, assume that is the per-package
11168                // native library directory to use; otherwise use "/system/lib/apkname".
11169                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11170                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11171                        getPrimaryInstructionSet(info));
11172
11173                // This is a bundled system app so choose the path based on the ABI.
11174                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11175                // is just the default path.
11176                final String apkName = deriveCodePathName(codePath);
11177                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11178                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11179                        apkName).getAbsolutePath();
11180
11181                if (info.secondaryCpuAbi != null) {
11182                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11183                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11184                            secondaryLibDir, apkName).getAbsolutePath();
11185                }
11186            } else if (asecApp) {
11187                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11188                        .getAbsolutePath();
11189            } else {
11190                final String apkName = deriveCodePathName(codePath);
11191                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11192                        .getAbsolutePath();
11193            }
11194
11195            info.nativeLibraryRootRequiresIsa = false;
11196            info.nativeLibraryDir = info.nativeLibraryRootDir;
11197        } else {
11198            // Cluster install
11199            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11200            info.nativeLibraryRootRequiresIsa = true;
11201
11202            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11203                    getPrimaryInstructionSet(info)).getAbsolutePath();
11204
11205            if (info.secondaryCpuAbi != null) {
11206                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11207                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11208            }
11209        }
11210    }
11211
11212    /**
11213     * Calculate the abis and roots for a bundled app. These can uniquely
11214     * be determined from the contents of the system partition, i.e whether
11215     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11216     * of this information, and instead assume that the system was built
11217     * sensibly.
11218     */
11219    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11220                                           PackageSetting pkgSetting) {
11221        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11222
11223        // If "/system/lib64/apkname" exists, assume that is the per-package
11224        // native library directory to use; otherwise use "/system/lib/apkname".
11225        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11226        setBundledAppAbi(pkg, apkRoot, apkName);
11227        // pkgSetting might be null during rescan following uninstall of updates
11228        // to a bundled app, so accommodate that possibility.  The settings in
11229        // that case will be established later from the parsed package.
11230        //
11231        // If the settings aren't null, sync them up with what we've just derived.
11232        // note that apkRoot isn't stored in the package settings.
11233        if (pkgSetting != null) {
11234            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11235            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11236        }
11237    }
11238
11239    /**
11240     * Deduces the ABI of a bundled app and sets the relevant fields on the
11241     * parsed pkg object.
11242     *
11243     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11244     *        under which system libraries are installed.
11245     * @param apkName the name of the installed package.
11246     */
11247    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11248        final File codeFile = new File(pkg.codePath);
11249
11250        final boolean has64BitLibs;
11251        final boolean has32BitLibs;
11252        if (isApkFile(codeFile)) {
11253            // Monolithic install
11254            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11255            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11256        } else {
11257            // Cluster install
11258            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11259            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11260                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11261                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11262                has64BitLibs = (new File(rootDir, isa)).exists();
11263            } else {
11264                has64BitLibs = false;
11265            }
11266            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11267                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11268                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11269                has32BitLibs = (new File(rootDir, isa)).exists();
11270            } else {
11271                has32BitLibs = false;
11272            }
11273        }
11274
11275        if (has64BitLibs && !has32BitLibs) {
11276            // The package has 64 bit libs, but not 32 bit libs. Its primary
11277            // ABI should be 64 bit. We can safely assume here that the bundled
11278            // native libraries correspond to the most preferred ABI in the list.
11279
11280            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11281            pkg.applicationInfo.secondaryCpuAbi = null;
11282        } else if (has32BitLibs && !has64BitLibs) {
11283            // The package has 32 bit libs but not 64 bit libs. Its primary
11284            // ABI should be 32 bit.
11285
11286            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11287            pkg.applicationInfo.secondaryCpuAbi = null;
11288        } else if (has32BitLibs && has64BitLibs) {
11289            // The application has both 64 and 32 bit bundled libraries. We check
11290            // here that the app declares multiArch support, and warn if it doesn't.
11291            //
11292            // We will be lenient here and record both ABIs. The primary will be the
11293            // ABI that's higher on the list, i.e, a device that's configured to prefer
11294            // 64 bit apps will see a 64 bit primary ABI,
11295
11296            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11297                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11298            }
11299
11300            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11301                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11302                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11303            } else {
11304                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11305                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11306            }
11307        } else {
11308            pkg.applicationInfo.primaryCpuAbi = null;
11309            pkg.applicationInfo.secondaryCpuAbi = null;
11310        }
11311    }
11312
11313    private void killApplication(String pkgName, int appId, String reason) {
11314        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11315    }
11316
11317    private void killApplication(String pkgName, int appId, int userId, String reason) {
11318        // Request the ActivityManager to kill the process(only for existing packages)
11319        // so that we do not end up in a confused state while the user is still using the older
11320        // version of the application while the new one gets installed.
11321        final long token = Binder.clearCallingIdentity();
11322        try {
11323            IActivityManager am = ActivityManager.getService();
11324            if (am != null) {
11325                try {
11326                    am.killApplication(pkgName, appId, userId, reason);
11327                } catch (RemoteException e) {
11328                }
11329            }
11330        } finally {
11331            Binder.restoreCallingIdentity(token);
11332        }
11333    }
11334
11335    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11336        // Remove the parent package setting
11337        PackageSetting ps = (PackageSetting) pkg.mExtras;
11338        if (ps != null) {
11339            removePackageLI(ps, chatty);
11340        }
11341        // Remove the child package setting
11342        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11343        for (int i = 0; i < childCount; i++) {
11344            PackageParser.Package childPkg = pkg.childPackages.get(i);
11345            ps = (PackageSetting) childPkg.mExtras;
11346            if (ps != null) {
11347                removePackageLI(ps, chatty);
11348            }
11349        }
11350    }
11351
11352    void removePackageLI(PackageSetting ps, boolean chatty) {
11353        if (DEBUG_INSTALL) {
11354            if (chatty)
11355                Log.d(TAG, "Removing package " + ps.name);
11356        }
11357
11358        // writer
11359        synchronized (mPackages) {
11360            mPackages.remove(ps.name);
11361            final PackageParser.Package pkg = ps.pkg;
11362            if (pkg != null) {
11363                cleanPackageDataStructuresLILPw(pkg, chatty);
11364            }
11365        }
11366    }
11367
11368    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11369        if (DEBUG_INSTALL) {
11370            if (chatty)
11371                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11372        }
11373
11374        // writer
11375        synchronized (mPackages) {
11376            // Remove the parent package
11377            mPackages.remove(pkg.applicationInfo.packageName);
11378            cleanPackageDataStructuresLILPw(pkg, chatty);
11379
11380            // Remove the child packages
11381            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11382            for (int i = 0; i < childCount; i++) {
11383                PackageParser.Package childPkg = pkg.childPackages.get(i);
11384                mPackages.remove(childPkg.applicationInfo.packageName);
11385                cleanPackageDataStructuresLILPw(childPkg, chatty);
11386            }
11387        }
11388    }
11389
11390    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11391        int N = pkg.providers.size();
11392        StringBuilder r = null;
11393        int i;
11394        for (i=0; i<N; i++) {
11395            PackageParser.Provider p = pkg.providers.get(i);
11396            mProviders.removeProvider(p);
11397            if (p.info.authority == null) {
11398
11399                /* There was another ContentProvider with this authority when
11400                 * this app was installed so this authority is null,
11401                 * Ignore it as we don't have to unregister the provider.
11402                 */
11403                continue;
11404            }
11405            String names[] = p.info.authority.split(";");
11406            for (int j = 0; j < names.length; j++) {
11407                if (mProvidersByAuthority.get(names[j]) == p) {
11408                    mProvidersByAuthority.remove(names[j]);
11409                    if (DEBUG_REMOVE) {
11410                        if (chatty)
11411                            Log.d(TAG, "Unregistered content provider: " + names[j]
11412                                    + ", className = " + p.info.name + ", isSyncable = "
11413                                    + p.info.isSyncable);
11414                    }
11415                }
11416            }
11417            if (DEBUG_REMOVE && chatty) {
11418                if (r == null) {
11419                    r = new StringBuilder(256);
11420                } else {
11421                    r.append(' ');
11422                }
11423                r.append(p.info.name);
11424            }
11425        }
11426        if (r != null) {
11427            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11428        }
11429
11430        N = pkg.services.size();
11431        r = null;
11432        for (i=0; i<N; i++) {
11433            PackageParser.Service s = pkg.services.get(i);
11434            mServices.removeService(s);
11435            if (chatty) {
11436                if (r == null) {
11437                    r = new StringBuilder(256);
11438                } else {
11439                    r.append(' ');
11440                }
11441                r.append(s.info.name);
11442            }
11443        }
11444        if (r != null) {
11445            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11446        }
11447
11448        N = pkg.receivers.size();
11449        r = null;
11450        for (i=0; i<N; i++) {
11451            PackageParser.Activity a = pkg.receivers.get(i);
11452            mReceivers.removeActivity(a, "receiver");
11453            if (DEBUG_REMOVE && chatty) {
11454                if (r == null) {
11455                    r = new StringBuilder(256);
11456                } else {
11457                    r.append(' ');
11458                }
11459                r.append(a.info.name);
11460            }
11461        }
11462        if (r != null) {
11463            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11464        }
11465
11466        N = pkg.activities.size();
11467        r = null;
11468        for (i=0; i<N; i++) {
11469            PackageParser.Activity a = pkg.activities.get(i);
11470            mActivities.removeActivity(a, "activity");
11471            if (DEBUG_REMOVE && chatty) {
11472                if (r == null) {
11473                    r = new StringBuilder(256);
11474                } else {
11475                    r.append(' ');
11476                }
11477                r.append(a.info.name);
11478            }
11479        }
11480        if (r != null) {
11481            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11482        }
11483
11484        N = pkg.permissions.size();
11485        r = null;
11486        for (i=0; i<N; i++) {
11487            PackageParser.Permission p = pkg.permissions.get(i);
11488            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11489            if (bp == null) {
11490                bp = mSettings.mPermissionTrees.get(p.info.name);
11491            }
11492            if (bp != null && bp.perm == p) {
11493                bp.perm = null;
11494                if (DEBUG_REMOVE && chatty) {
11495                    if (r == null) {
11496                        r = new StringBuilder(256);
11497                    } else {
11498                        r.append(' ');
11499                    }
11500                    r.append(p.info.name);
11501                }
11502            }
11503            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11504                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11505                if (appOpPkgs != null) {
11506                    appOpPkgs.remove(pkg.packageName);
11507                }
11508            }
11509        }
11510        if (r != null) {
11511            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11512        }
11513
11514        N = pkg.requestedPermissions.size();
11515        r = null;
11516        for (i=0; i<N; i++) {
11517            String perm = pkg.requestedPermissions.get(i);
11518            BasePermission bp = mSettings.mPermissions.get(perm);
11519            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11520                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11521                if (appOpPkgs != null) {
11522                    appOpPkgs.remove(pkg.packageName);
11523                    if (appOpPkgs.isEmpty()) {
11524                        mAppOpPermissionPackages.remove(perm);
11525                    }
11526                }
11527            }
11528        }
11529        if (r != null) {
11530            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11531        }
11532
11533        N = pkg.instrumentation.size();
11534        r = null;
11535        for (i=0; i<N; i++) {
11536            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11537            mInstrumentation.remove(a.getComponentName());
11538            if (DEBUG_REMOVE && chatty) {
11539                if (r == null) {
11540                    r = new StringBuilder(256);
11541                } else {
11542                    r.append(' ');
11543                }
11544                r.append(a.info.name);
11545            }
11546        }
11547        if (r != null) {
11548            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11549        }
11550
11551        r = null;
11552        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11553            // Only system apps can hold shared libraries.
11554            if (pkg.libraryNames != null) {
11555                for (i = 0; i < pkg.libraryNames.size(); i++) {
11556                    String name = pkg.libraryNames.get(i);
11557                    if (removeSharedLibraryLPw(name, 0)) {
11558                        if (DEBUG_REMOVE && chatty) {
11559                            if (r == null) {
11560                                r = new StringBuilder(256);
11561                            } else {
11562                                r.append(' ');
11563                            }
11564                            r.append(name);
11565                        }
11566                    }
11567                }
11568            }
11569        }
11570
11571        r = null;
11572
11573        // Any package can hold static shared libraries.
11574        if (pkg.staticSharedLibName != null) {
11575            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11576                if (DEBUG_REMOVE && chatty) {
11577                    if (r == null) {
11578                        r = new StringBuilder(256);
11579                    } else {
11580                        r.append(' ');
11581                    }
11582                    r.append(pkg.staticSharedLibName);
11583                }
11584            }
11585        }
11586
11587        if (r != null) {
11588            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11589        }
11590    }
11591
11592    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11593        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11594            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11595                return true;
11596            }
11597        }
11598        return false;
11599    }
11600
11601    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11602    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11603    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11604
11605    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11606        // Update the parent permissions
11607        updatePermissionsLPw(pkg.packageName, pkg, flags);
11608        // Update the child permissions
11609        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11610        for (int i = 0; i < childCount; i++) {
11611            PackageParser.Package childPkg = pkg.childPackages.get(i);
11612            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11613        }
11614    }
11615
11616    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11617            int flags) {
11618        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11619        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11620    }
11621
11622    private void updatePermissionsLPw(String changingPkg,
11623            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11624        // Make sure there are no dangling permission trees.
11625        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11626        while (it.hasNext()) {
11627            final BasePermission bp = it.next();
11628            if (bp.packageSetting == null) {
11629                // We may not yet have parsed the package, so just see if
11630                // we still know about its settings.
11631                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11632            }
11633            if (bp.packageSetting == null) {
11634                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11635                        + " from package " + bp.sourcePackage);
11636                it.remove();
11637            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11638                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11639                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11640                            + " from package " + bp.sourcePackage);
11641                    flags |= UPDATE_PERMISSIONS_ALL;
11642                    it.remove();
11643                }
11644            }
11645        }
11646
11647        // Make sure all dynamic permissions have been assigned to a package,
11648        // and make sure there are no dangling permissions.
11649        it = mSettings.mPermissions.values().iterator();
11650        while (it.hasNext()) {
11651            final BasePermission bp = it.next();
11652            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11653                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11654                        + bp.name + " pkg=" + bp.sourcePackage
11655                        + " info=" + bp.pendingInfo);
11656                if (bp.packageSetting == null && bp.pendingInfo != null) {
11657                    final BasePermission tree = findPermissionTreeLP(bp.name);
11658                    if (tree != null && tree.perm != null) {
11659                        bp.packageSetting = tree.packageSetting;
11660                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11661                                new PermissionInfo(bp.pendingInfo));
11662                        bp.perm.info.packageName = tree.perm.info.packageName;
11663                        bp.perm.info.name = bp.name;
11664                        bp.uid = tree.uid;
11665                    }
11666                }
11667            }
11668            if (bp.packageSetting == null) {
11669                // We may not yet have parsed the package, so just see if
11670                // we still know about its settings.
11671                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11672            }
11673            if (bp.packageSetting == null) {
11674                Slog.w(TAG, "Removing dangling permission: " + bp.name
11675                        + " from package " + bp.sourcePackage);
11676                it.remove();
11677            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11678                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11679                    Slog.i(TAG, "Removing old permission: " + bp.name
11680                            + " from package " + bp.sourcePackage);
11681                    flags |= UPDATE_PERMISSIONS_ALL;
11682                    it.remove();
11683                }
11684            }
11685        }
11686
11687        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11688        // Now update the permissions for all packages, in particular
11689        // replace the granted permissions of the system packages.
11690        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11691            for (PackageParser.Package pkg : mPackages.values()) {
11692                if (pkg != pkgInfo) {
11693                    // Only replace for packages on requested volume
11694                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11695                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11696                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11697                    grantPermissionsLPw(pkg, replace, changingPkg);
11698                }
11699            }
11700        }
11701
11702        if (pkgInfo != null) {
11703            // Only replace for packages on requested volume
11704            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11705            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11706                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11707            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11708        }
11709        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11710    }
11711
11712    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11713            String packageOfInterest) {
11714        // IMPORTANT: There are two types of permissions: install and runtime.
11715        // Install time permissions are granted when the app is installed to
11716        // all device users and users added in the future. Runtime permissions
11717        // are granted at runtime explicitly to specific users. Normal and signature
11718        // protected permissions are install time permissions. Dangerous permissions
11719        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11720        // otherwise they are runtime permissions. This function does not manage
11721        // runtime permissions except for the case an app targeting Lollipop MR1
11722        // being upgraded to target a newer SDK, in which case dangerous permissions
11723        // are transformed from install time to runtime ones.
11724
11725        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11726        if (ps == null) {
11727            return;
11728        }
11729
11730        PermissionsState permissionsState = ps.getPermissionsState();
11731        PermissionsState origPermissions = permissionsState;
11732
11733        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11734
11735        boolean runtimePermissionsRevoked = false;
11736        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11737
11738        boolean changedInstallPermission = false;
11739
11740        if (replace) {
11741            ps.installPermissionsFixed = false;
11742            if (!ps.isSharedUser()) {
11743                origPermissions = new PermissionsState(permissionsState);
11744                permissionsState.reset();
11745            } else {
11746                // We need to know only about runtime permission changes since the
11747                // calling code always writes the install permissions state but
11748                // the runtime ones are written only if changed. The only cases of
11749                // changed runtime permissions here are promotion of an install to
11750                // runtime and revocation of a runtime from a shared user.
11751                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11752                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11753                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11754                    runtimePermissionsRevoked = true;
11755                }
11756            }
11757        }
11758
11759        permissionsState.setGlobalGids(mGlobalGids);
11760
11761        final int N = pkg.requestedPermissions.size();
11762        for (int i=0; i<N; i++) {
11763            final String name = pkg.requestedPermissions.get(i);
11764            final BasePermission bp = mSettings.mPermissions.get(name);
11765            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11766                    >= Build.VERSION_CODES.M;
11767
11768            if (DEBUG_INSTALL) {
11769                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11770            }
11771
11772            if (bp == null || bp.packageSetting == null) {
11773                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11774                    if (DEBUG_PERMISSIONS) {
11775                        Slog.i(TAG, "Unknown permission " + name
11776                                + " in package " + pkg.packageName);
11777                    }
11778                }
11779                continue;
11780            }
11781
11782
11783            // Limit ephemeral apps to ephemeral allowed permissions.
11784            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11785                if (DEBUG_PERMISSIONS) {
11786                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11787                            + pkg.packageName);
11788                }
11789                continue;
11790            }
11791
11792            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11793                if (DEBUG_PERMISSIONS) {
11794                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11795                            + pkg.packageName);
11796                }
11797                continue;
11798            }
11799
11800            final String perm = bp.name;
11801            boolean allowedSig = false;
11802            int grant = GRANT_DENIED;
11803
11804            // Keep track of app op permissions.
11805            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11806                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11807                if (pkgs == null) {
11808                    pkgs = new ArraySet<>();
11809                    mAppOpPermissionPackages.put(bp.name, pkgs);
11810                }
11811                pkgs.add(pkg.packageName);
11812            }
11813
11814            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11815            switch (level) {
11816                case PermissionInfo.PROTECTION_NORMAL: {
11817                    // For all apps normal permissions are install time ones.
11818                    grant = GRANT_INSTALL;
11819                } break;
11820
11821                case PermissionInfo.PROTECTION_DANGEROUS: {
11822                    // If a permission review is required for legacy apps we represent
11823                    // their permissions as always granted runtime ones since we need
11824                    // to keep the review required permission flag per user while an
11825                    // install permission's state is shared across all users.
11826                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11827                        // For legacy apps dangerous permissions are install time ones.
11828                        grant = GRANT_INSTALL;
11829                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11830                        // For legacy apps that became modern, install becomes runtime.
11831                        grant = GRANT_UPGRADE;
11832                    } else if (mPromoteSystemApps
11833                            && isSystemApp(ps)
11834                            && mExistingSystemPackages.contains(ps.name)) {
11835                        // For legacy system apps, install becomes runtime.
11836                        // We cannot check hasInstallPermission() for system apps since those
11837                        // permissions were granted implicitly and not persisted pre-M.
11838                        grant = GRANT_UPGRADE;
11839                    } else {
11840                        // For modern apps keep runtime permissions unchanged.
11841                        grant = GRANT_RUNTIME;
11842                    }
11843                } break;
11844
11845                case PermissionInfo.PROTECTION_SIGNATURE: {
11846                    // For all apps signature permissions are install time ones.
11847                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11848                    if (allowedSig) {
11849                        grant = GRANT_INSTALL;
11850                    }
11851                } break;
11852            }
11853
11854            if (DEBUG_PERMISSIONS) {
11855                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
11856            }
11857
11858            if (grant != GRANT_DENIED) {
11859                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11860                    // If this is an existing, non-system package, then
11861                    // we can't add any new permissions to it.
11862                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11863                        // Except...  if this is a permission that was added
11864                        // to the platform (note: need to only do this when
11865                        // updating the platform).
11866                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11867                            grant = GRANT_DENIED;
11868                        }
11869                    }
11870                }
11871
11872                switch (grant) {
11873                    case GRANT_INSTALL: {
11874                        // Revoke this as runtime permission to handle the case of
11875                        // a runtime permission being downgraded to an install one.
11876                        // Also in permission review mode we keep dangerous permissions
11877                        // for legacy apps
11878                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11879                            if (origPermissions.getRuntimePermissionState(
11880                                    bp.name, userId) != null) {
11881                                // Revoke the runtime permission and clear the flags.
11882                                origPermissions.revokeRuntimePermission(bp, userId);
11883                                origPermissions.updatePermissionFlags(bp, userId,
11884                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11885                                // If we revoked a permission permission, we have to write.
11886                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11887                                        changedRuntimePermissionUserIds, userId);
11888                            }
11889                        }
11890                        // Grant an install permission.
11891                        if (permissionsState.grantInstallPermission(bp) !=
11892                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11893                            changedInstallPermission = true;
11894                        }
11895                    } break;
11896
11897                    case GRANT_RUNTIME: {
11898                        // Grant previously granted runtime permissions.
11899                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11900                            PermissionState permissionState = origPermissions
11901                                    .getRuntimePermissionState(bp.name, userId);
11902                            int flags = permissionState != null
11903                                    ? permissionState.getFlags() : 0;
11904                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11905                                // Don't propagate the permission in a permission review mode if
11906                                // the former was revoked, i.e. marked to not propagate on upgrade.
11907                                // Note that in a permission review mode install permissions are
11908                                // represented as constantly granted runtime ones since we need to
11909                                // keep a per user state associated with the permission. Also the
11910                                // revoke on upgrade flag is no longer applicable and is reset.
11911                                final boolean revokeOnUpgrade = (flags & PackageManager
11912                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11913                                if (revokeOnUpgrade) {
11914                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11915                                    // Since we changed the flags, we have to write.
11916                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11917                                            changedRuntimePermissionUserIds, userId);
11918                                }
11919                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11920                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11921                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11922                                        // If we cannot put the permission as it was,
11923                                        // we have to write.
11924                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11925                                                changedRuntimePermissionUserIds, userId);
11926                                    }
11927                                }
11928
11929                                // If the app supports runtime permissions no need for a review.
11930                                if (mPermissionReviewRequired
11931                                        && appSupportsRuntimePermissions
11932                                        && (flags & PackageManager
11933                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11934                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11935                                    // Since we changed the flags, we have to write.
11936                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11937                                            changedRuntimePermissionUserIds, userId);
11938                                }
11939                            } else if (mPermissionReviewRequired
11940                                    && !appSupportsRuntimePermissions) {
11941                                // For legacy apps that need a permission review, every new
11942                                // runtime permission is granted but it is pending a review.
11943                                // We also need to review only platform defined runtime
11944                                // permissions as these are the only ones the platform knows
11945                                // how to disable the API to simulate revocation as legacy
11946                                // apps don't expect to run with revoked permissions.
11947                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11948                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11949                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11950                                        // We changed the flags, hence have to write.
11951                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11952                                                changedRuntimePermissionUserIds, userId);
11953                                    }
11954                                }
11955                                if (permissionsState.grantRuntimePermission(bp, userId)
11956                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11957                                    // We changed the permission, hence have to write.
11958                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11959                                            changedRuntimePermissionUserIds, userId);
11960                                }
11961                            }
11962                            // Propagate the permission flags.
11963                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11964                        }
11965                    } break;
11966
11967                    case GRANT_UPGRADE: {
11968                        // Grant runtime permissions for a previously held install permission.
11969                        PermissionState permissionState = origPermissions
11970                                .getInstallPermissionState(bp.name);
11971                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11972
11973                        if (origPermissions.revokeInstallPermission(bp)
11974                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11975                            // We will be transferring the permission flags, so clear them.
11976                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11977                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11978                            changedInstallPermission = true;
11979                        }
11980
11981                        // If the permission is not to be promoted to runtime we ignore it and
11982                        // also its other flags as they are not applicable to install permissions.
11983                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11984                            for (int userId : currentUserIds) {
11985                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11986                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11987                                    // Transfer the permission flags.
11988                                    permissionsState.updatePermissionFlags(bp, userId,
11989                                            flags, flags);
11990                                    // If we granted the permission, we have to write.
11991                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11992                                            changedRuntimePermissionUserIds, userId);
11993                                }
11994                            }
11995                        }
11996                    } break;
11997
11998                    default: {
11999                        if (packageOfInterest == null
12000                                || packageOfInterest.equals(pkg.packageName)) {
12001                            if (DEBUG_PERMISSIONS) {
12002                                Slog.i(TAG, "Not granting permission " + perm
12003                                        + " to package " + pkg.packageName
12004                                        + " because it was previously installed without");
12005                            }
12006                        }
12007                    } break;
12008                }
12009            } else {
12010                if (permissionsState.revokeInstallPermission(bp) !=
12011                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12012                    // Also drop the permission flags.
12013                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12014                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12015                    changedInstallPermission = true;
12016                    Slog.i(TAG, "Un-granting permission " + perm
12017                            + " from package " + pkg.packageName
12018                            + " (protectionLevel=" + bp.protectionLevel
12019                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12020                            + ")");
12021                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12022                    // Don't print warning for app op permissions, since it is fine for them
12023                    // not to be granted, there is a UI for the user to decide.
12024                    if (DEBUG_PERMISSIONS
12025                            && (packageOfInterest == null
12026                                    || packageOfInterest.equals(pkg.packageName))) {
12027                        Slog.i(TAG, "Not granting permission " + perm
12028                                + " to package " + pkg.packageName
12029                                + " (protectionLevel=" + bp.protectionLevel
12030                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12031                                + ")");
12032                    }
12033                }
12034            }
12035        }
12036
12037        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12038                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12039            // This is the first that we have heard about this package, so the
12040            // permissions we have now selected are fixed until explicitly
12041            // changed.
12042            ps.installPermissionsFixed = true;
12043        }
12044
12045        // Persist the runtime permissions state for users with changes. If permissions
12046        // were revoked because no app in the shared user declares them we have to
12047        // write synchronously to avoid losing runtime permissions state.
12048        for (int userId : changedRuntimePermissionUserIds) {
12049            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12050        }
12051    }
12052
12053    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12054        boolean allowed = false;
12055        final int NP = PackageParser.NEW_PERMISSIONS.length;
12056        for (int ip=0; ip<NP; ip++) {
12057            final PackageParser.NewPermissionInfo npi
12058                    = PackageParser.NEW_PERMISSIONS[ip];
12059            if (npi.name.equals(perm)
12060                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12061                allowed = true;
12062                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12063                        + pkg.packageName);
12064                break;
12065            }
12066        }
12067        return allowed;
12068    }
12069
12070    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12071            BasePermission bp, PermissionsState origPermissions) {
12072        boolean privilegedPermission = (bp.protectionLevel
12073                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12074        boolean privappPermissionsDisable =
12075                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12076        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12077        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12078        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12079                && !platformPackage && platformPermission) {
12080            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12081                    .getPrivAppPermissions(pkg.packageName);
12082            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12083            if (!whitelisted) {
12084                Slog.w(TAG, "Privileged permission " + perm + " for package "
12085                        + pkg.packageName + " - not in privapp-permissions whitelist");
12086                // Only report violations for apps on system image
12087                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12088                    if (mPrivappPermissionsViolations == null) {
12089                        mPrivappPermissionsViolations = new ArraySet<>();
12090                    }
12091                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12092                }
12093                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12094                    return false;
12095                }
12096            }
12097        }
12098        boolean allowed = (compareSignatures(
12099                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12100                        == PackageManager.SIGNATURE_MATCH)
12101                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12102                        == PackageManager.SIGNATURE_MATCH);
12103        if (!allowed && privilegedPermission) {
12104            if (isSystemApp(pkg)) {
12105                // For updated system applications, a system permission
12106                // is granted only if it had been defined by the original application.
12107                if (pkg.isUpdatedSystemApp()) {
12108                    final PackageSetting sysPs = mSettings
12109                            .getDisabledSystemPkgLPr(pkg.packageName);
12110                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12111                        // If the original was granted this permission, we take
12112                        // that grant decision as read and propagate it to the
12113                        // update.
12114                        if (sysPs.isPrivileged()) {
12115                            allowed = true;
12116                        }
12117                    } else {
12118                        // The system apk may have been updated with an older
12119                        // version of the one on the data partition, but which
12120                        // granted a new system permission that it didn't have
12121                        // before.  In this case we do want to allow the app to
12122                        // now get the new permission if the ancestral apk is
12123                        // privileged to get it.
12124                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12125                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12126                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12127                                    allowed = true;
12128                                    break;
12129                                }
12130                            }
12131                        }
12132                        // Also if a privileged parent package on the system image or any of
12133                        // its children requested a privileged permission, the updated child
12134                        // packages can also get the permission.
12135                        if (pkg.parentPackage != null) {
12136                            final PackageSetting disabledSysParentPs = mSettings
12137                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12138                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12139                                    && disabledSysParentPs.isPrivileged()) {
12140                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12141                                    allowed = true;
12142                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12143                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12144                                    for (int i = 0; i < count; i++) {
12145                                        PackageParser.Package disabledSysChildPkg =
12146                                                disabledSysParentPs.pkg.childPackages.get(i);
12147                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12148                                                perm)) {
12149                                            allowed = true;
12150                                            break;
12151                                        }
12152                                    }
12153                                }
12154                            }
12155                        }
12156                    }
12157                } else {
12158                    allowed = isPrivilegedApp(pkg);
12159                }
12160            }
12161        }
12162        if (!allowed) {
12163            if (!allowed && (bp.protectionLevel
12164                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12165                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12166                // If this was a previously normal/dangerous permission that got moved
12167                // to a system permission as part of the runtime permission redesign, then
12168                // we still want to blindly grant it to old apps.
12169                allowed = true;
12170            }
12171            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12172                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12173                // If this permission is to be granted to the system installer and
12174                // this app is an installer, then it gets the permission.
12175                allowed = true;
12176            }
12177            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12178                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12179                // If this permission is to be granted to the system verifier and
12180                // this app is a verifier, then it gets the permission.
12181                allowed = true;
12182            }
12183            if (!allowed && (bp.protectionLevel
12184                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12185                    && isSystemApp(pkg)) {
12186                // Any pre-installed system app is allowed to get this permission.
12187                allowed = true;
12188            }
12189            if (!allowed && (bp.protectionLevel
12190                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12191                // For development permissions, a development permission
12192                // is granted only if it was already granted.
12193                allowed = origPermissions.hasInstallPermission(perm);
12194            }
12195            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12196                    && pkg.packageName.equals(mSetupWizardPackage)) {
12197                // If this permission is to be granted to the system setup wizard and
12198                // this app is a setup wizard, then it gets the permission.
12199                allowed = true;
12200            }
12201        }
12202        return allowed;
12203    }
12204
12205    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12206        final int permCount = pkg.requestedPermissions.size();
12207        for (int j = 0; j < permCount; j++) {
12208            String requestedPermission = pkg.requestedPermissions.get(j);
12209            if (permission.equals(requestedPermission)) {
12210                return true;
12211            }
12212        }
12213        return false;
12214    }
12215
12216    final class ActivityIntentResolver
12217            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12218        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12219                boolean defaultOnly, int userId) {
12220            if (!sUserManager.exists(userId)) return null;
12221            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12222            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12223        }
12224
12225        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12226                int userId) {
12227            if (!sUserManager.exists(userId)) return null;
12228            mFlags = flags;
12229            return super.queryIntent(intent, resolvedType,
12230                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12231                    userId);
12232        }
12233
12234        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12235                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12236            if (!sUserManager.exists(userId)) return null;
12237            if (packageActivities == null) {
12238                return null;
12239            }
12240            mFlags = flags;
12241            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12242            final int N = packageActivities.size();
12243            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12244                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12245
12246            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12247            for (int i = 0; i < N; ++i) {
12248                intentFilters = packageActivities.get(i).intents;
12249                if (intentFilters != null && intentFilters.size() > 0) {
12250                    PackageParser.ActivityIntentInfo[] array =
12251                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12252                    intentFilters.toArray(array);
12253                    listCut.add(array);
12254                }
12255            }
12256            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12257        }
12258
12259        /**
12260         * Finds a privileged activity that matches the specified activity names.
12261         */
12262        private PackageParser.Activity findMatchingActivity(
12263                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12264            for (PackageParser.Activity sysActivity : activityList) {
12265                if (sysActivity.info.name.equals(activityInfo.name)) {
12266                    return sysActivity;
12267                }
12268                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12269                    return sysActivity;
12270                }
12271                if (sysActivity.info.targetActivity != null) {
12272                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12273                        return sysActivity;
12274                    }
12275                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12276                        return sysActivity;
12277                    }
12278                }
12279            }
12280            return null;
12281        }
12282
12283        public class IterGenerator<E> {
12284            public Iterator<E> generate(ActivityIntentInfo info) {
12285                return null;
12286            }
12287        }
12288
12289        public class ActionIterGenerator extends IterGenerator<String> {
12290            @Override
12291            public Iterator<String> generate(ActivityIntentInfo info) {
12292                return info.actionsIterator();
12293            }
12294        }
12295
12296        public class CategoriesIterGenerator extends IterGenerator<String> {
12297            @Override
12298            public Iterator<String> generate(ActivityIntentInfo info) {
12299                return info.categoriesIterator();
12300            }
12301        }
12302
12303        public class SchemesIterGenerator extends IterGenerator<String> {
12304            @Override
12305            public Iterator<String> generate(ActivityIntentInfo info) {
12306                return info.schemesIterator();
12307            }
12308        }
12309
12310        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12311            @Override
12312            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12313                return info.authoritiesIterator();
12314            }
12315        }
12316
12317        /**
12318         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12319         * MODIFIED. Do not pass in a list that should not be changed.
12320         */
12321        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12322                IterGenerator<T> generator, Iterator<T> searchIterator) {
12323            // loop through the set of actions; every one must be found in the intent filter
12324            while (searchIterator.hasNext()) {
12325                // we must have at least one filter in the list to consider a match
12326                if (intentList.size() == 0) {
12327                    break;
12328                }
12329
12330                final T searchAction = searchIterator.next();
12331
12332                // loop through the set of intent filters
12333                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12334                while (intentIter.hasNext()) {
12335                    final ActivityIntentInfo intentInfo = intentIter.next();
12336                    boolean selectionFound = false;
12337
12338                    // loop through the intent filter's selection criteria; at least one
12339                    // of them must match the searched criteria
12340                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12341                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12342                        final T intentSelection = intentSelectionIter.next();
12343                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12344                            selectionFound = true;
12345                            break;
12346                        }
12347                    }
12348
12349                    // the selection criteria wasn't found in this filter's set; this filter
12350                    // is not a potential match
12351                    if (!selectionFound) {
12352                        intentIter.remove();
12353                    }
12354                }
12355            }
12356        }
12357
12358        private boolean isProtectedAction(ActivityIntentInfo filter) {
12359            final Iterator<String> actionsIter = filter.actionsIterator();
12360            while (actionsIter != null && actionsIter.hasNext()) {
12361                final String filterAction = actionsIter.next();
12362                if (PROTECTED_ACTIONS.contains(filterAction)) {
12363                    return true;
12364                }
12365            }
12366            return false;
12367        }
12368
12369        /**
12370         * Adjusts the priority of the given intent filter according to policy.
12371         * <p>
12372         * <ul>
12373         * <li>The priority for non privileged applications is capped to '0'</li>
12374         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12375         * <li>The priority for unbundled updates to privileged applications is capped to the
12376         *      priority defined on the system partition</li>
12377         * </ul>
12378         * <p>
12379         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12380         * allowed to obtain any priority on any action.
12381         */
12382        private void adjustPriority(
12383                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12384            // nothing to do; priority is fine as-is
12385            if (intent.getPriority() <= 0) {
12386                return;
12387            }
12388
12389            final ActivityInfo activityInfo = intent.activity.info;
12390            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12391
12392            final boolean privilegedApp =
12393                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12394            if (!privilegedApp) {
12395                // non-privileged applications can never define a priority >0
12396                if (DEBUG_FILTERS) {
12397                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12398                            + " package: " + applicationInfo.packageName
12399                            + " activity: " + intent.activity.className
12400                            + " origPrio: " + intent.getPriority());
12401                }
12402                intent.setPriority(0);
12403                return;
12404            }
12405
12406            if (systemActivities == null) {
12407                // the system package is not disabled; we're parsing the system partition
12408                if (isProtectedAction(intent)) {
12409                    if (mDeferProtectedFilters) {
12410                        // We can't deal with these just yet. No component should ever obtain a
12411                        // >0 priority for a protected actions, with ONE exception -- the setup
12412                        // wizard. The setup wizard, however, cannot be known until we're able to
12413                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12414                        // until all intent filters have been processed. Chicken, meet egg.
12415                        // Let the filter temporarily have a high priority and rectify the
12416                        // priorities after all system packages have been scanned.
12417                        mProtectedFilters.add(intent);
12418                        if (DEBUG_FILTERS) {
12419                            Slog.i(TAG, "Protected action; save for later;"
12420                                    + " package: " + applicationInfo.packageName
12421                                    + " activity: " + intent.activity.className
12422                                    + " origPrio: " + intent.getPriority());
12423                        }
12424                        return;
12425                    } else {
12426                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12427                            Slog.i(TAG, "No setup wizard;"
12428                                + " All protected intents capped to priority 0");
12429                        }
12430                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12431                            if (DEBUG_FILTERS) {
12432                                Slog.i(TAG, "Found setup wizard;"
12433                                    + " allow priority " + intent.getPriority() + ";"
12434                                    + " package: " + intent.activity.info.packageName
12435                                    + " activity: " + intent.activity.className
12436                                    + " priority: " + intent.getPriority());
12437                            }
12438                            // setup wizard gets whatever it wants
12439                            return;
12440                        }
12441                        if (DEBUG_FILTERS) {
12442                            Slog.i(TAG, "Protected action; cap priority to 0;"
12443                                    + " package: " + intent.activity.info.packageName
12444                                    + " activity: " + intent.activity.className
12445                                    + " origPrio: " + intent.getPriority());
12446                        }
12447                        intent.setPriority(0);
12448                        return;
12449                    }
12450                }
12451                // privileged apps on the system image get whatever priority they request
12452                return;
12453            }
12454
12455            // privileged app unbundled update ... try to find the same activity
12456            final PackageParser.Activity foundActivity =
12457                    findMatchingActivity(systemActivities, activityInfo);
12458            if (foundActivity == null) {
12459                // this is a new activity; it cannot obtain >0 priority
12460                if (DEBUG_FILTERS) {
12461                    Slog.i(TAG, "New activity; cap priority to 0;"
12462                            + " package: " + applicationInfo.packageName
12463                            + " activity: " + intent.activity.className
12464                            + " origPrio: " + intent.getPriority());
12465                }
12466                intent.setPriority(0);
12467                return;
12468            }
12469
12470            // found activity, now check for filter equivalence
12471
12472            // a shallow copy is enough; we modify the list, not its contents
12473            final List<ActivityIntentInfo> intentListCopy =
12474                    new ArrayList<>(foundActivity.intents);
12475            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12476
12477            // find matching action subsets
12478            final Iterator<String> actionsIterator = intent.actionsIterator();
12479            if (actionsIterator != null) {
12480                getIntentListSubset(
12481                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12482                if (intentListCopy.size() == 0) {
12483                    // no more intents to match; we're not equivalent
12484                    if (DEBUG_FILTERS) {
12485                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12486                                + " package: " + applicationInfo.packageName
12487                                + " activity: " + intent.activity.className
12488                                + " origPrio: " + intent.getPriority());
12489                    }
12490                    intent.setPriority(0);
12491                    return;
12492                }
12493            }
12494
12495            // find matching category subsets
12496            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12497            if (categoriesIterator != null) {
12498                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12499                        categoriesIterator);
12500                if (intentListCopy.size() == 0) {
12501                    // no more intents to match; we're not equivalent
12502                    if (DEBUG_FILTERS) {
12503                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12504                                + " package: " + applicationInfo.packageName
12505                                + " activity: " + intent.activity.className
12506                                + " origPrio: " + intent.getPriority());
12507                    }
12508                    intent.setPriority(0);
12509                    return;
12510                }
12511            }
12512
12513            // find matching schemes subsets
12514            final Iterator<String> schemesIterator = intent.schemesIterator();
12515            if (schemesIterator != null) {
12516                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12517                        schemesIterator);
12518                if (intentListCopy.size() == 0) {
12519                    // no more intents to match; we're not equivalent
12520                    if (DEBUG_FILTERS) {
12521                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12522                                + " package: " + applicationInfo.packageName
12523                                + " activity: " + intent.activity.className
12524                                + " origPrio: " + intent.getPriority());
12525                    }
12526                    intent.setPriority(0);
12527                    return;
12528                }
12529            }
12530
12531            // find matching authorities subsets
12532            final Iterator<IntentFilter.AuthorityEntry>
12533                    authoritiesIterator = intent.authoritiesIterator();
12534            if (authoritiesIterator != null) {
12535                getIntentListSubset(intentListCopy,
12536                        new AuthoritiesIterGenerator(),
12537                        authoritiesIterator);
12538                if (intentListCopy.size() == 0) {
12539                    // no more intents to match; we're not equivalent
12540                    if (DEBUG_FILTERS) {
12541                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12542                                + " package: " + applicationInfo.packageName
12543                                + " activity: " + intent.activity.className
12544                                + " origPrio: " + intent.getPriority());
12545                    }
12546                    intent.setPriority(0);
12547                    return;
12548                }
12549            }
12550
12551            // we found matching filter(s); app gets the max priority of all intents
12552            int cappedPriority = 0;
12553            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12554                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12555            }
12556            if (intent.getPriority() > cappedPriority) {
12557                if (DEBUG_FILTERS) {
12558                    Slog.i(TAG, "Found matching filter(s);"
12559                            + " cap priority to " + cappedPriority + ";"
12560                            + " package: " + applicationInfo.packageName
12561                            + " activity: " + intent.activity.className
12562                            + " origPrio: " + intent.getPriority());
12563                }
12564                intent.setPriority(cappedPriority);
12565                return;
12566            }
12567            // all this for nothing; the requested priority was <= what was on the system
12568        }
12569
12570        public final void addActivity(PackageParser.Activity a, String type) {
12571            mActivities.put(a.getComponentName(), a);
12572            if (DEBUG_SHOW_INFO)
12573                Log.v(
12574                TAG, "  " + type + " " +
12575                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12576            if (DEBUG_SHOW_INFO)
12577                Log.v(TAG, "    Class=" + a.info.name);
12578            final int NI = a.intents.size();
12579            for (int j=0; j<NI; j++) {
12580                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12581                if ("activity".equals(type)) {
12582                    final PackageSetting ps =
12583                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12584                    final List<PackageParser.Activity> systemActivities =
12585                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12586                    adjustPriority(systemActivities, intent);
12587                }
12588                if (DEBUG_SHOW_INFO) {
12589                    Log.v(TAG, "    IntentFilter:");
12590                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12591                }
12592                if (!intent.debugCheck()) {
12593                    Log.w(TAG, "==> For Activity " + a.info.name);
12594                }
12595                addFilter(intent);
12596            }
12597        }
12598
12599        public final void removeActivity(PackageParser.Activity a, String type) {
12600            mActivities.remove(a.getComponentName());
12601            if (DEBUG_SHOW_INFO) {
12602                Log.v(TAG, "  " + type + " "
12603                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12604                                : a.info.name) + ":");
12605                Log.v(TAG, "    Class=" + a.info.name);
12606            }
12607            final int NI = a.intents.size();
12608            for (int j=0; j<NI; j++) {
12609                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12610                if (DEBUG_SHOW_INFO) {
12611                    Log.v(TAG, "    IntentFilter:");
12612                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12613                }
12614                removeFilter(intent);
12615            }
12616        }
12617
12618        @Override
12619        protected boolean allowFilterResult(
12620                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12621            ActivityInfo filterAi = filter.activity.info;
12622            for (int i=dest.size()-1; i>=0; i--) {
12623                ActivityInfo destAi = dest.get(i).activityInfo;
12624                if (destAi.name == filterAi.name
12625                        && destAi.packageName == filterAi.packageName) {
12626                    return false;
12627                }
12628            }
12629            return true;
12630        }
12631
12632        @Override
12633        protected ActivityIntentInfo[] newArray(int size) {
12634            return new ActivityIntentInfo[size];
12635        }
12636
12637        @Override
12638        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12639            if (!sUserManager.exists(userId)) return true;
12640            PackageParser.Package p = filter.activity.owner;
12641            if (p != null) {
12642                PackageSetting ps = (PackageSetting)p.mExtras;
12643                if (ps != null) {
12644                    // System apps are never considered stopped for purposes of
12645                    // filtering, because there may be no way for the user to
12646                    // actually re-launch them.
12647                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12648                            && ps.getStopped(userId);
12649                }
12650            }
12651            return false;
12652        }
12653
12654        @Override
12655        protected boolean isPackageForFilter(String packageName,
12656                PackageParser.ActivityIntentInfo info) {
12657            return packageName.equals(info.activity.owner.packageName);
12658        }
12659
12660        @Override
12661        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12662                int match, int userId) {
12663            if (!sUserManager.exists(userId)) return null;
12664            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12665                return null;
12666            }
12667            final PackageParser.Activity activity = info.activity;
12668            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12669            if (ps == null) {
12670                return null;
12671            }
12672            final PackageUserState userState = ps.readUserState(userId);
12673            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12674            if (ai == null) {
12675                return null;
12676            }
12677            final boolean matchExplicitlyVisibleOnly =
12678                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12679            final boolean matchVisibleToInstantApp =
12680                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12681            final boolean componentVisible =
12682                    matchVisibleToInstantApp
12683                    && info.isVisibleToInstantApp()
12684                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12685            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12686            // throw out filters that aren't visible to ephemeral apps
12687            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12688                return null;
12689            }
12690            // throw out instant app filters if we're not explicitly requesting them
12691            if (!matchInstantApp && userState.instantApp) {
12692                return null;
12693            }
12694            // throw out instant app filters if updates are available; will trigger
12695            // instant app resolution
12696            if (userState.instantApp && ps.isUpdateAvailable()) {
12697                return null;
12698            }
12699            final ResolveInfo res = new ResolveInfo();
12700            res.activityInfo = ai;
12701            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12702                res.filter = info;
12703            }
12704            if (info != null) {
12705                res.handleAllWebDataURI = info.handleAllWebDataURI();
12706            }
12707            res.priority = info.getPriority();
12708            res.preferredOrder = activity.owner.mPreferredOrder;
12709            //System.out.println("Result: " + res.activityInfo.className +
12710            //                   " = " + res.priority);
12711            res.match = match;
12712            res.isDefault = info.hasDefault;
12713            res.labelRes = info.labelRes;
12714            res.nonLocalizedLabel = info.nonLocalizedLabel;
12715            if (userNeedsBadging(userId)) {
12716                res.noResourceId = true;
12717            } else {
12718                res.icon = info.icon;
12719            }
12720            res.iconResourceId = info.icon;
12721            res.system = res.activityInfo.applicationInfo.isSystemApp();
12722            res.isInstantAppAvailable = userState.instantApp;
12723            return res;
12724        }
12725
12726        @Override
12727        protected void sortResults(List<ResolveInfo> results) {
12728            Collections.sort(results, mResolvePrioritySorter);
12729        }
12730
12731        @Override
12732        protected void dumpFilter(PrintWriter out, String prefix,
12733                PackageParser.ActivityIntentInfo filter) {
12734            out.print(prefix); out.print(
12735                    Integer.toHexString(System.identityHashCode(filter.activity)));
12736                    out.print(' ');
12737                    filter.activity.printComponentShortName(out);
12738                    out.print(" filter ");
12739                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12740        }
12741
12742        @Override
12743        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12744            return filter.activity;
12745        }
12746
12747        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12748            PackageParser.Activity activity = (PackageParser.Activity)label;
12749            out.print(prefix); out.print(
12750                    Integer.toHexString(System.identityHashCode(activity)));
12751                    out.print(' ');
12752                    activity.printComponentShortName(out);
12753            if (count > 1) {
12754                out.print(" ("); out.print(count); out.print(" filters)");
12755            }
12756            out.println();
12757        }
12758
12759        // Keys are String (activity class name), values are Activity.
12760        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12761                = new ArrayMap<ComponentName, PackageParser.Activity>();
12762        private int mFlags;
12763    }
12764
12765    private final class ServiceIntentResolver
12766            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12767        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12768                boolean defaultOnly, int userId) {
12769            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12770            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12771        }
12772
12773        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12774                int userId) {
12775            if (!sUserManager.exists(userId)) return null;
12776            mFlags = flags;
12777            return super.queryIntent(intent, resolvedType,
12778                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12779                    userId);
12780        }
12781
12782        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12783                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12784            if (!sUserManager.exists(userId)) return null;
12785            if (packageServices == null) {
12786                return null;
12787            }
12788            mFlags = flags;
12789            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12790            final int N = packageServices.size();
12791            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12792                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12793
12794            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12795            for (int i = 0; i < N; ++i) {
12796                intentFilters = packageServices.get(i).intents;
12797                if (intentFilters != null && intentFilters.size() > 0) {
12798                    PackageParser.ServiceIntentInfo[] array =
12799                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12800                    intentFilters.toArray(array);
12801                    listCut.add(array);
12802                }
12803            }
12804            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12805        }
12806
12807        public final void addService(PackageParser.Service s) {
12808            mServices.put(s.getComponentName(), s);
12809            if (DEBUG_SHOW_INFO) {
12810                Log.v(TAG, "  "
12811                        + (s.info.nonLocalizedLabel != null
12812                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12813                Log.v(TAG, "    Class=" + s.info.name);
12814            }
12815            final int NI = s.intents.size();
12816            int j;
12817            for (j=0; j<NI; j++) {
12818                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12819                if (DEBUG_SHOW_INFO) {
12820                    Log.v(TAG, "    IntentFilter:");
12821                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12822                }
12823                if (!intent.debugCheck()) {
12824                    Log.w(TAG, "==> For Service " + s.info.name);
12825                }
12826                addFilter(intent);
12827            }
12828        }
12829
12830        public final void removeService(PackageParser.Service s) {
12831            mServices.remove(s.getComponentName());
12832            if (DEBUG_SHOW_INFO) {
12833                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12834                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12835                Log.v(TAG, "    Class=" + s.info.name);
12836            }
12837            final int NI = s.intents.size();
12838            int j;
12839            for (j=0; j<NI; j++) {
12840                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12841                if (DEBUG_SHOW_INFO) {
12842                    Log.v(TAG, "    IntentFilter:");
12843                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12844                }
12845                removeFilter(intent);
12846            }
12847        }
12848
12849        @Override
12850        protected boolean allowFilterResult(
12851                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12852            ServiceInfo filterSi = filter.service.info;
12853            for (int i=dest.size()-1; i>=0; i--) {
12854                ServiceInfo destAi = dest.get(i).serviceInfo;
12855                if (destAi.name == filterSi.name
12856                        && destAi.packageName == filterSi.packageName) {
12857                    return false;
12858                }
12859            }
12860            return true;
12861        }
12862
12863        @Override
12864        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12865            return new PackageParser.ServiceIntentInfo[size];
12866        }
12867
12868        @Override
12869        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12870            if (!sUserManager.exists(userId)) return true;
12871            PackageParser.Package p = filter.service.owner;
12872            if (p != null) {
12873                PackageSetting ps = (PackageSetting)p.mExtras;
12874                if (ps != null) {
12875                    // System apps are never considered stopped for purposes of
12876                    // filtering, because there may be no way for the user to
12877                    // actually re-launch them.
12878                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12879                            && ps.getStopped(userId);
12880                }
12881            }
12882            return false;
12883        }
12884
12885        @Override
12886        protected boolean isPackageForFilter(String packageName,
12887                PackageParser.ServiceIntentInfo info) {
12888            return packageName.equals(info.service.owner.packageName);
12889        }
12890
12891        @Override
12892        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12893                int match, int userId) {
12894            if (!sUserManager.exists(userId)) return null;
12895            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12896            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12897                return null;
12898            }
12899            final PackageParser.Service service = info.service;
12900            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12901            if (ps == null) {
12902                return null;
12903            }
12904            final PackageUserState userState = ps.readUserState(userId);
12905            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12906                    userState, userId);
12907            if (si == null) {
12908                return null;
12909            }
12910            final boolean matchVisibleToInstantApp =
12911                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12912            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12913            // throw out filters that aren't visible to ephemeral apps
12914            if (matchVisibleToInstantApp
12915                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12916                return null;
12917            }
12918            // throw out ephemeral filters if we're not explicitly requesting them
12919            if (!isInstantApp && userState.instantApp) {
12920                return null;
12921            }
12922            // throw out instant app filters if updates are available; will trigger
12923            // instant app resolution
12924            if (userState.instantApp && ps.isUpdateAvailable()) {
12925                return null;
12926            }
12927            final ResolveInfo res = new ResolveInfo();
12928            res.serviceInfo = si;
12929            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12930                res.filter = filter;
12931            }
12932            res.priority = info.getPriority();
12933            res.preferredOrder = service.owner.mPreferredOrder;
12934            res.match = match;
12935            res.isDefault = info.hasDefault;
12936            res.labelRes = info.labelRes;
12937            res.nonLocalizedLabel = info.nonLocalizedLabel;
12938            res.icon = info.icon;
12939            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12940            return res;
12941        }
12942
12943        @Override
12944        protected void sortResults(List<ResolveInfo> results) {
12945            Collections.sort(results, mResolvePrioritySorter);
12946        }
12947
12948        @Override
12949        protected void dumpFilter(PrintWriter out, String prefix,
12950                PackageParser.ServiceIntentInfo filter) {
12951            out.print(prefix); out.print(
12952                    Integer.toHexString(System.identityHashCode(filter.service)));
12953                    out.print(' ');
12954                    filter.service.printComponentShortName(out);
12955                    out.print(" filter ");
12956                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12957        }
12958
12959        @Override
12960        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12961            return filter.service;
12962        }
12963
12964        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12965            PackageParser.Service service = (PackageParser.Service)label;
12966            out.print(prefix); out.print(
12967                    Integer.toHexString(System.identityHashCode(service)));
12968                    out.print(' ');
12969                    service.printComponentShortName(out);
12970            if (count > 1) {
12971                out.print(" ("); out.print(count); out.print(" filters)");
12972            }
12973            out.println();
12974        }
12975
12976//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12977//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12978//            final List<ResolveInfo> retList = Lists.newArrayList();
12979//            while (i.hasNext()) {
12980//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12981//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12982//                    retList.add(resolveInfo);
12983//                }
12984//            }
12985//            return retList;
12986//        }
12987
12988        // Keys are String (activity class name), values are Activity.
12989        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12990                = new ArrayMap<ComponentName, PackageParser.Service>();
12991        private int mFlags;
12992    }
12993
12994    private final class ProviderIntentResolver
12995            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12996        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12997                boolean defaultOnly, int userId) {
12998            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12999            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13000        }
13001
13002        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13003                int userId) {
13004            if (!sUserManager.exists(userId))
13005                return null;
13006            mFlags = flags;
13007            return super.queryIntent(intent, resolvedType,
13008                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13009                    userId);
13010        }
13011
13012        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13013                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13014            if (!sUserManager.exists(userId))
13015                return null;
13016            if (packageProviders == null) {
13017                return null;
13018            }
13019            mFlags = flags;
13020            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13021            final int N = packageProviders.size();
13022            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13023                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13024
13025            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13026            for (int i = 0; i < N; ++i) {
13027                intentFilters = packageProviders.get(i).intents;
13028                if (intentFilters != null && intentFilters.size() > 0) {
13029                    PackageParser.ProviderIntentInfo[] array =
13030                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13031                    intentFilters.toArray(array);
13032                    listCut.add(array);
13033                }
13034            }
13035            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13036        }
13037
13038        public final void addProvider(PackageParser.Provider p) {
13039            if (mProviders.containsKey(p.getComponentName())) {
13040                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13041                return;
13042            }
13043
13044            mProviders.put(p.getComponentName(), p);
13045            if (DEBUG_SHOW_INFO) {
13046                Log.v(TAG, "  "
13047                        + (p.info.nonLocalizedLabel != null
13048                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13049                Log.v(TAG, "    Class=" + p.info.name);
13050            }
13051            final int NI = p.intents.size();
13052            int j;
13053            for (j = 0; j < NI; j++) {
13054                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13055                if (DEBUG_SHOW_INFO) {
13056                    Log.v(TAG, "    IntentFilter:");
13057                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13058                }
13059                if (!intent.debugCheck()) {
13060                    Log.w(TAG, "==> For Provider " + p.info.name);
13061                }
13062                addFilter(intent);
13063            }
13064        }
13065
13066        public final void removeProvider(PackageParser.Provider p) {
13067            mProviders.remove(p.getComponentName());
13068            if (DEBUG_SHOW_INFO) {
13069                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13070                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13071                Log.v(TAG, "    Class=" + p.info.name);
13072            }
13073            final int NI = p.intents.size();
13074            int j;
13075            for (j = 0; j < NI; j++) {
13076                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13077                if (DEBUG_SHOW_INFO) {
13078                    Log.v(TAG, "    IntentFilter:");
13079                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13080                }
13081                removeFilter(intent);
13082            }
13083        }
13084
13085        @Override
13086        protected boolean allowFilterResult(
13087                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13088            ProviderInfo filterPi = filter.provider.info;
13089            for (int i = dest.size() - 1; i >= 0; i--) {
13090                ProviderInfo destPi = dest.get(i).providerInfo;
13091                if (destPi.name == filterPi.name
13092                        && destPi.packageName == filterPi.packageName) {
13093                    return false;
13094                }
13095            }
13096            return true;
13097        }
13098
13099        @Override
13100        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13101            return new PackageParser.ProviderIntentInfo[size];
13102        }
13103
13104        @Override
13105        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13106            if (!sUserManager.exists(userId))
13107                return true;
13108            PackageParser.Package p = filter.provider.owner;
13109            if (p != null) {
13110                PackageSetting ps = (PackageSetting) p.mExtras;
13111                if (ps != null) {
13112                    // System apps are never considered stopped for purposes of
13113                    // filtering, because there may be no way for the user to
13114                    // actually re-launch them.
13115                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13116                            && ps.getStopped(userId);
13117                }
13118            }
13119            return false;
13120        }
13121
13122        @Override
13123        protected boolean isPackageForFilter(String packageName,
13124                PackageParser.ProviderIntentInfo info) {
13125            return packageName.equals(info.provider.owner.packageName);
13126        }
13127
13128        @Override
13129        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13130                int match, int userId) {
13131            if (!sUserManager.exists(userId))
13132                return null;
13133            final PackageParser.ProviderIntentInfo info = filter;
13134            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13135                return null;
13136            }
13137            final PackageParser.Provider provider = info.provider;
13138            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13139            if (ps == null) {
13140                return null;
13141            }
13142            final PackageUserState userState = ps.readUserState(userId);
13143            final boolean matchVisibleToInstantApp =
13144                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13145            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13146            // throw out filters that aren't visible to instant applications
13147            if (matchVisibleToInstantApp
13148                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13149                return null;
13150            }
13151            // throw out instant application filters if we're not explicitly requesting them
13152            if (!isInstantApp && userState.instantApp) {
13153                return null;
13154            }
13155            // throw out instant application filters if updates are available; will trigger
13156            // instant application resolution
13157            if (userState.instantApp && ps.isUpdateAvailable()) {
13158                return null;
13159            }
13160            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13161                    userState, userId);
13162            if (pi == null) {
13163                return null;
13164            }
13165            final ResolveInfo res = new ResolveInfo();
13166            res.providerInfo = pi;
13167            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13168                res.filter = filter;
13169            }
13170            res.priority = info.getPriority();
13171            res.preferredOrder = provider.owner.mPreferredOrder;
13172            res.match = match;
13173            res.isDefault = info.hasDefault;
13174            res.labelRes = info.labelRes;
13175            res.nonLocalizedLabel = info.nonLocalizedLabel;
13176            res.icon = info.icon;
13177            res.system = res.providerInfo.applicationInfo.isSystemApp();
13178            return res;
13179        }
13180
13181        @Override
13182        protected void sortResults(List<ResolveInfo> results) {
13183            Collections.sort(results, mResolvePrioritySorter);
13184        }
13185
13186        @Override
13187        protected void dumpFilter(PrintWriter out, String prefix,
13188                PackageParser.ProviderIntentInfo filter) {
13189            out.print(prefix);
13190            out.print(
13191                    Integer.toHexString(System.identityHashCode(filter.provider)));
13192            out.print(' ');
13193            filter.provider.printComponentShortName(out);
13194            out.print(" filter ");
13195            out.println(Integer.toHexString(System.identityHashCode(filter)));
13196        }
13197
13198        @Override
13199        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13200            return filter.provider;
13201        }
13202
13203        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13204            PackageParser.Provider provider = (PackageParser.Provider)label;
13205            out.print(prefix); out.print(
13206                    Integer.toHexString(System.identityHashCode(provider)));
13207                    out.print(' ');
13208                    provider.printComponentShortName(out);
13209            if (count > 1) {
13210                out.print(" ("); out.print(count); out.print(" filters)");
13211            }
13212            out.println();
13213        }
13214
13215        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13216                = new ArrayMap<ComponentName, PackageParser.Provider>();
13217        private int mFlags;
13218    }
13219
13220    static final class EphemeralIntentResolver
13221            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13222        /**
13223         * The result that has the highest defined order. Ordering applies on a
13224         * per-package basis. Mapping is from package name to Pair of order and
13225         * EphemeralResolveInfo.
13226         * <p>
13227         * NOTE: This is implemented as a field variable for convenience and efficiency.
13228         * By having a field variable, we're able to track filter ordering as soon as
13229         * a non-zero order is defined. Otherwise, multiple loops across the result set
13230         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13231         * this needs to be contained entirely within {@link #filterResults}.
13232         */
13233        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13234
13235        @Override
13236        protected AuxiliaryResolveInfo[] newArray(int size) {
13237            return new AuxiliaryResolveInfo[size];
13238        }
13239
13240        @Override
13241        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13242            return true;
13243        }
13244
13245        @Override
13246        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13247                int userId) {
13248            if (!sUserManager.exists(userId)) {
13249                return null;
13250            }
13251            final String packageName = responseObj.resolveInfo.getPackageName();
13252            final Integer order = responseObj.getOrder();
13253            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13254                    mOrderResult.get(packageName);
13255            // ordering is enabled and this item's order isn't high enough
13256            if (lastOrderResult != null && lastOrderResult.first >= order) {
13257                return null;
13258            }
13259            final InstantAppResolveInfo res = responseObj.resolveInfo;
13260            if (order > 0) {
13261                // non-zero order, enable ordering
13262                mOrderResult.put(packageName, new Pair<>(order, res));
13263            }
13264            return responseObj;
13265        }
13266
13267        @Override
13268        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13269            // only do work if ordering is enabled [most of the time it won't be]
13270            if (mOrderResult.size() == 0) {
13271                return;
13272            }
13273            int resultSize = results.size();
13274            for (int i = 0; i < resultSize; i++) {
13275                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13276                final String packageName = info.getPackageName();
13277                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13278                if (savedInfo == null) {
13279                    // package doesn't having ordering
13280                    continue;
13281                }
13282                if (savedInfo.second == info) {
13283                    // circled back to the highest ordered item; remove from order list
13284                    mOrderResult.remove(savedInfo);
13285                    if (mOrderResult.size() == 0) {
13286                        // no more ordered items
13287                        break;
13288                    }
13289                    continue;
13290                }
13291                // item has a worse order, remove it from the result list
13292                results.remove(i);
13293                resultSize--;
13294                i--;
13295            }
13296        }
13297    }
13298
13299    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13300            new Comparator<ResolveInfo>() {
13301        public int compare(ResolveInfo r1, ResolveInfo r2) {
13302            int v1 = r1.priority;
13303            int v2 = r2.priority;
13304            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13305            if (v1 != v2) {
13306                return (v1 > v2) ? -1 : 1;
13307            }
13308            v1 = r1.preferredOrder;
13309            v2 = r2.preferredOrder;
13310            if (v1 != v2) {
13311                return (v1 > v2) ? -1 : 1;
13312            }
13313            if (r1.isDefault != r2.isDefault) {
13314                return r1.isDefault ? -1 : 1;
13315            }
13316            v1 = r1.match;
13317            v2 = r2.match;
13318            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13319            if (v1 != v2) {
13320                return (v1 > v2) ? -1 : 1;
13321            }
13322            if (r1.system != r2.system) {
13323                return r1.system ? -1 : 1;
13324            }
13325            if (r1.activityInfo != null) {
13326                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13327            }
13328            if (r1.serviceInfo != null) {
13329                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13330            }
13331            if (r1.providerInfo != null) {
13332                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13333            }
13334            return 0;
13335        }
13336    };
13337
13338    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13339            new Comparator<ProviderInfo>() {
13340        public int compare(ProviderInfo p1, ProviderInfo p2) {
13341            final int v1 = p1.initOrder;
13342            final int v2 = p2.initOrder;
13343            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13344        }
13345    };
13346
13347    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13348            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13349            final int[] userIds) {
13350        mHandler.post(new Runnable() {
13351            @Override
13352            public void run() {
13353                try {
13354                    final IActivityManager am = ActivityManager.getService();
13355                    if (am == null) return;
13356                    final int[] resolvedUserIds;
13357                    if (userIds == null) {
13358                        resolvedUserIds = am.getRunningUserIds();
13359                    } else {
13360                        resolvedUserIds = userIds;
13361                    }
13362                    for (int id : resolvedUserIds) {
13363                        final Intent intent = new Intent(action,
13364                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13365                        if (extras != null) {
13366                            intent.putExtras(extras);
13367                        }
13368                        if (targetPkg != null) {
13369                            intent.setPackage(targetPkg);
13370                        }
13371                        // Modify the UID when posting to other users
13372                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13373                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13374                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13375                            intent.putExtra(Intent.EXTRA_UID, uid);
13376                        }
13377                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13378                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13379                        if (DEBUG_BROADCASTS) {
13380                            RuntimeException here = new RuntimeException("here");
13381                            here.fillInStackTrace();
13382                            Slog.d(TAG, "Sending to user " + id + ": "
13383                                    + intent.toShortString(false, true, false, false)
13384                                    + " " + intent.getExtras(), here);
13385                        }
13386                        am.broadcastIntent(null, intent, null, finishedReceiver,
13387                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13388                                null, finishedReceiver != null, false, id);
13389                    }
13390                } catch (RemoteException ex) {
13391                }
13392            }
13393        });
13394    }
13395
13396    /**
13397     * Check if the external storage media is available. This is true if there
13398     * is a mounted external storage medium or if the external storage is
13399     * emulated.
13400     */
13401    private boolean isExternalMediaAvailable() {
13402        return mMediaMounted || Environment.isExternalStorageEmulated();
13403    }
13404
13405    @Override
13406    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13407        // writer
13408        synchronized (mPackages) {
13409            if (!isExternalMediaAvailable()) {
13410                // If the external storage is no longer mounted at this point,
13411                // the caller may not have been able to delete all of this
13412                // packages files and can not delete any more.  Bail.
13413                return null;
13414            }
13415            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13416            if (lastPackage != null) {
13417                pkgs.remove(lastPackage);
13418            }
13419            if (pkgs.size() > 0) {
13420                return pkgs.get(0);
13421            }
13422        }
13423        return null;
13424    }
13425
13426    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13427        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13428                userId, andCode ? 1 : 0, packageName);
13429        if (mSystemReady) {
13430            msg.sendToTarget();
13431        } else {
13432            if (mPostSystemReadyMessages == null) {
13433                mPostSystemReadyMessages = new ArrayList<>();
13434            }
13435            mPostSystemReadyMessages.add(msg);
13436        }
13437    }
13438
13439    void startCleaningPackages() {
13440        // reader
13441        if (!isExternalMediaAvailable()) {
13442            return;
13443        }
13444        synchronized (mPackages) {
13445            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13446                return;
13447            }
13448        }
13449        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13450        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13451        IActivityManager am = ActivityManager.getService();
13452        if (am != null) {
13453            int dcsUid = -1;
13454            synchronized (mPackages) {
13455                if (!mDefaultContainerWhitelisted) {
13456                    mDefaultContainerWhitelisted = true;
13457                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13458                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13459                }
13460            }
13461            try {
13462                if (dcsUid > 0) {
13463                    am.backgroundWhitelistUid(dcsUid);
13464                }
13465                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13466                        UserHandle.USER_SYSTEM);
13467            } catch (RemoteException e) {
13468            }
13469        }
13470    }
13471
13472    @Override
13473    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13474            int installFlags, String installerPackageName, int userId) {
13475        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13476
13477        final int callingUid = Binder.getCallingUid();
13478        enforceCrossUserPermission(callingUid, userId,
13479                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13480
13481        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13482            try {
13483                if (observer != null) {
13484                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13485                }
13486            } catch (RemoteException re) {
13487            }
13488            return;
13489        }
13490
13491        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13492            installFlags |= PackageManager.INSTALL_FROM_ADB;
13493
13494        } else {
13495            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13496            // about installerPackageName.
13497
13498            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13499            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13500        }
13501
13502        UserHandle user;
13503        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13504            user = UserHandle.ALL;
13505        } else {
13506            user = new UserHandle(userId);
13507        }
13508
13509        // Only system components can circumvent runtime permissions when installing.
13510        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13511                && mContext.checkCallingOrSelfPermission(Manifest.permission
13512                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13513            throw new SecurityException("You need the "
13514                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13515                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13516        }
13517
13518        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13519                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13520            throw new IllegalArgumentException(
13521                    "New installs into ASEC containers no longer supported");
13522        }
13523
13524        final File originFile = new File(originPath);
13525        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13526
13527        final Message msg = mHandler.obtainMessage(INIT_COPY);
13528        final VerificationInfo verificationInfo = new VerificationInfo(
13529                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13530        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13531                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13532                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13533                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13534        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13535        msg.obj = params;
13536
13537        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13538                System.identityHashCode(msg.obj));
13539        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13540                System.identityHashCode(msg.obj));
13541
13542        mHandler.sendMessage(msg);
13543    }
13544
13545
13546    /**
13547     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13548     * it is acting on behalf on an enterprise or the user).
13549     *
13550     * Note that the ordering of the conditionals in this method is important. The checks we perform
13551     * are as follows, in this order:
13552     *
13553     * 1) If the install is being performed by a system app, we can trust the app to have set the
13554     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13555     *    what it is.
13556     * 2) If the install is being performed by a device or profile owner app, the install reason
13557     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13558     *    set the install reason correctly. If the app targets an older SDK version where install
13559     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13560     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13561     * 3) In all other cases, the install is being performed by a regular app that is neither part
13562     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13563     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13564     *    set to enterprise policy and if so, change it to unknown instead.
13565     */
13566    private int fixUpInstallReason(String installerPackageName, int installerUid,
13567            int installReason) {
13568        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13569                == PERMISSION_GRANTED) {
13570            // If the install is being performed by a system app, we trust that app to have set the
13571            // install reason correctly.
13572            return installReason;
13573        }
13574
13575        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13576            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13577        if (dpm != null) {
13578            ComponentName owner = null;
13579            try {
13580                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13581                if (owner == null) {
13582                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13583                }
13584            } catch (RemoteException e) {
13585            }
13586            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13587                // If the install is being performed by a device or profile owner, the install
13588                // reason should be enterprise policy.
13589                return PackageManager.INSTALL_REASON_POLICY;
13590            }
13591        }
13592
13593        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13594            // If the install is being performed by a regular app (i.e. neither system app nor
13595            // device or profile owner), we have no reason to believe that the app is acting on
13596            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13597            // change it to unknown instead.
13598            return PackageManager.INSTALL_REASON_UNKNOWN;
13599        }
13600
13601        // If the install is being performed by a regular app and the install reason was set to any
13602        // value but enterprise policy, leave the install reason unchanged.
13603        return installReason;
13604    }
13605
13606    void installStage(String packageName, File stagedDir, String stagedCid,
13607            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13608            String installerPackageName, int installerUid, UserHandle user,
13609            Certificate[][] certificates) {
13610        if (DEBUG_EPHEMERAL) {
13611            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13612                Slog.d(TAG, "Ephemeral install of " + packageName);
13613            }
13614        }
13615        final VerificationInfo verificationInfo = new VerificationInfo(
13616                sessionParams.originatingUri, sessionParams.referrerUri,
13617                sessionParams.originatingUid, installerUid);
13618
13619        final OriginInfo origin;
13620        if (stagedDir != null) {
13621            origin = OriginInfo.fromStagedFile(stagedDir);
13622        } else {
13623            origin = OriginInfo.fromStagedContainer(stagedCid);
13624        }
13625
13626        final Message msg = mHandler.obtainMessage(INIT_COPY);
13627        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13628                sessionParams.installReason);
13629        final InstallParams params = new InstallParams(origin, null, observer,
13630                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13631                verificationInfo, user, sessionParams.abiOverride,
13632                sessionParams.grantedRuntimePermissions, certificates, installReason);
13633        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13634        msg.obj = params;
13635
13636        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13637                System.identityHashCode(msg.obj));
13638        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13639                System.identityHashCode(msg.obj));
13640
13641        mHandler.sendMessage(msg);
13642    }
13643
13644    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13645            int userId) {
13646        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13647        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13648
13649        // Send a session commit broadcast
13650        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13651        info.installReason = pkgSetting.getInstallReason(userId);
13652        info.appPackageName = packageName;
13653        sendSessionCommitBroadcast(info, userId);
13654    }
13655
13656    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13657        if (ArrayUtils.isEmpty(userIds)) {
13658            return;
13659        }
13660        Bundle extras = new Bundle(1);
13661        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13662        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13663
13664        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13665                packageName, extras, 0, null, null, userIds);
13666        if (isSystem) {
13667            mHandler.post(() -> {
13668                        for (int userId : userIds) {
13669                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13670                        }
13671                    }
13672            );
13673        }
13674    }
13675
13676    /**
13677     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13678     * automatically without needing an explicit launch.
13679     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13680     */
13681    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13682        // If user is not running, the app didn't miss any broadcast
13683        if (!mUserManagerInternal.isUserRunning(userId)) {
13684            return;
13685        }
13686        final IActivityManager am = ActivityManager.getService();
13687        try {
13688            // Deliver LOCKED_BOOT_COMPLETED first
13689            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13690                    .setPackage(packageName);
13691            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13692            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13693                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13694
13695            // Deliver BOOT_COMPLETED only if user is unlocked
13696            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13697                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13698                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13699                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13700            }
13701        } catch (RemoteException e) {
13702            throw e.rethrowFromSystemServer();
13703        }
13704    }
13705
13706    @Override
13707    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13708            int userId) {
13709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13710        PackageSetting pkgSetting;
13711        final int uid = Binder.getCallingUid();
13712        enforceCrossUserPermission(uid, userId,
13713                true /* requireFullPermission */, true /* checkShell */,
13714                "setApplicationHiddenSetting for user " + userId);
13715
13716        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13717            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13718            return false;
13719        }
13720
13721        long callingId = Binder.clearCallingIdentity();
13722        try {
13723            boolean sendAdded = false;
13724            boolean sendRemoved = false;
13725            // writer
13726            synchronized (mPackages) {
13727                pkgSetting = mSettings.mPackages.get(packageName);
13728                if (pkgSetting == null) {
13729                    return false;
13730                }
13731                // Do not allow "android" is being disabled
13732                if ("android".equals(packageName)) {
13733                    Slog.w(TAG, "Cannot hide package: android");
13734                    return false;
13735                }
13736                // Cannot hide static shared libs as they are considered
13737                // a part of the using app (emulating static linking). Also
13738                // static libs are installed always on internal storage.
13739                PackageParser.Package pkg = mPackages.get(packageName);
13740                if (pkg != null && pkg.staticSharedLibName != null) {
13741                    Slog.w(TAG, "Cannot hide package: " + packageName
13742                            + " providing static shared library: "
13743                            + pkg.staticSharedLibName);
13744                    return false;
13745                }
13746                // Only allow protected packages to hide themselves.
13747                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13748                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13749                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13750                    return false;
13751                }
13752
13753                if (pkgSetting.getHidden(userId) != hidden) {
13754                    pkgSetting.setHidden(hidden, userId);
13755                    mSettings.writePackageRestrictionsLPr(userId);
13756                    if (hidden) {
13757                        sendRemoved = true;
13758                    } else {
13759                        sendAdded = true;
13760                    }
13761                }
13762            }
13763            if (sendAdded) {
13764                sendPackageAddedForUser(packageName, pkgSetting, userId);
13765                return true;
13766            }
13767            if (sendRemoved) {
13768                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13769                        "hiding pkg");
13770                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13771                return true;
13772            }
13773        } finally {
13774            Binder.restoreCallingIdentity(callingId);
13775        }
13776        return false;
13777    }
13778
13779    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13780            int userId) {
13781        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13782        info.removedPackage = packageName;
13783        info.installerPackageName = pkgSetting.installerPackageName;
13784        info.removedUsers = new int[] {userId};
13785        info.broadcastUsers = new int[] {userId};
13786        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13787        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13788    }
13789
13790    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13791        if (pkgList.length > 0) {
13792            Bundle extras = new Bundle(1);
13793            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13794
13795            sendPackageBroadcast(
13796                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13797                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13798                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13799                    new int[] {userId});
13800        }
13801    }
13802
13803    /**
13804     * Returns true if application is not found or there was an error. Otherwise it returns
13805     * the hidden state of the package for the given user.
13806     */
13807    @Override
13808    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13809        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13810        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13811                true /* requireFullPermission */, false /* checkShell */,
13812                "getApplicationHidden for user " + userId);
13813        PackageSetting pkgSetting;
13814        long callingId = Binder.clearCallingIdentity();
13815        try {
13816            // writer
13817            synchronized (mPackages) {
13818                pkgSetting = mSettings.mPackages.get(packageName);
13819                if (pkgSetting == null) {
13820                    return true;
13821                }
13822                return pkgSetting.getHidden(userId);
13823            }
13824        } finally {
13825            Binder.restoreCallingIdentity(callingId);
13826        }
13827    }
13828
13829    /**
13830     * @hide
13831     */
13832    @Override
13833    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13834            int installReason) {
13835        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13836                null);
13837        PackageSetting pkgSetting;
13838        final int uid = Binder.getCallingUid();
13839        enforceCrossUserPermission(uid, userId,
13840                true /* requireFullPermission */, true /* checkShell */,
13841                "installExistingPackage for user " + userId);
13842        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13843            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13844        }
13845
13846        long callingId = Binder.clearCallingIdentity();
13847        try {
13848            boolean installed = false;
13849            final boolean instantApp =
13850                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13851            final boolean fullApp =
13852                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13853
13854            // writer
13855            synchronized (mPackages) {
13856                pkgSetting = mSettings.mPackages.get(packageName);
13857                if (pkgSetting == null) {
13858                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13859                }
13860                if (!pkgSetting.getInstalled(userId)) {
13861                    pkgSetting.setInstalled(true, userId);
13862                    pkgSetting.setHidden(false, userId);
13863                    pkgSetting.setInstallReason(installReason, userId);
13864                    mSettings.writePackageRestrictionsLPr(userId);
13865                    mSettings.writeKernelMappingLPr(pkgSetting);
13866                    installed = true;
13867                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13868                    // upgrade app from instant to full; we don't allow app downgrade
13869                    installed = true;
13870                }
13871                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13872            }
13873
13874            if (installed) {
13875                if (pkgSetting.pkg != null) {
13876                    synchronized (mInstallLock) {
13877                        // We don't need to freeze for a brand new install
13878                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13879                    }
13880                }
13881                sendPackageAddedForUser(packageName, pkgSetting, userId);
13882                synchronized (mPackages) {
13883                    updateSequenceNumberLP(packageName, new int[]{ userId });
13884                }
13885            }
13886        } finally {
13887            Binder.restoreCallingIdentity(callingId);
13888        }
13889
13890        return PackageManager.INSTALL_SUCCEEDED;
13891    }
13892
13893    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13894            boolean instantApp, boolean fullApp) {
13895        // no state specified; do nothing
13896        if (!instantApp && !fullApp) {
13897            return;
13898        }
13899        if (userId != UserHandle.USER_ALL) {
13900            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13901                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13902            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13903                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13904            }
13905        } else {
13906            for (int currentUserId : sUserManager.getUserIds()) {
13907                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13908                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13909                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13910                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13911                }
13912            }
13913        }
13914    }
13915
13916    boolean isUserRestricted(int userId, String restrictionKey) {
13917        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13918        if (restrictions.getBoolean(restrictionKey, false)) {
13919            Log.w(TAG, "User is restricted: " + restrictionKey);
13920            return true;
13921        }
13922        return false;
13923    }
13924
13925    @Override
13926    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13927            int userId) {
13928        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13929        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13930                true /* requireFullPermission */, true /* checkShell */,
13931                "setPackagesSuspended for user " + userId);
13932
13933        if (ArrayUtils.isEmpty(packageNames)) {
13934            return packageNames;
13935        }
13936
13937        // List of package names for whom the suspended state has changed.
13938        List<String> changedPackages = new ArrayList<>(packageNames.length);
13939        // List of package names for whom the suspended state is not set as requested in this
13940        // method.
13941        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13942        long callingId = Binder.clearCallingIdentity();
13943        try {
13944            for (int i = 0; i < packageNames.length; i++) {
13945                String packageName = packageNames[i];
13946                boolean changed = false;
13947                final int appId;
13948                synchronized (mPackages) {
13949                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13950                    if (pkgSetting == null) {
13951                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13952                                + "\". Skipping suspending/un-suspending.");
13953                        unactionedPackages.add(packageName);
13954                        continue;
13955                    }
13956                    appId = pkgSetting.appId;
13957                    if (pkgSetting.getSuspended(userId) != suspended) {
13958                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13959                            unactionedPackages.add(packageName);
13960                            continue;
13961                        }
13962                        pkgSetting.setSuspended(suspended, userId);
13963                        mSettings.writePackageRestrictionsLPr(userId);
13964                        changed = true;
13965                        changedPackages.add(packageName);
13966                    }
13967                }
13968
13969                if (changed && suspended) {
13970                    killApplication(packageName, UserHandle.getUid(userId, appId),
13971                            "suspending package");
13972                }
13973            }
13974        } finally {
13975            Binder.restoreCallingIdentity(callingId);
13976        }
13977
13978        if (!changedPackages.isEmpty()) {
13979            sendPackagesSuspendedForUser(changedPackages.toArray(
13980                    new String[changedPackages.size()]), userId, suspended);
13981        }
13982
13983        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13984    }
13985
13986    @Override
13987    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13988        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13989                true /* requireFullPermission */, false /* checkShell */,
13990                "isPackageSuspendedForUser for user " + userId);
13991        synchronized (mPackages) {
13992            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13993            if (pkgSetting == null) {
13994                throw new IllegalArgumentException("Unknown target package: " + packageName);
13995            }
13996            return pkgSetting.getSuspended(userId);
13997        }
13998    }
13999
14000    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14001        if (isPackageDeviceAdmin(packageName, userId)) {
14002            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14003                    + "\": has an active device admin");
14004            return false;
14005        }
14006
14007        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14008        if (packageName.equals(activeLauncherPackageName)) {
14009            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14010                    + "\": contains the active launcher");
14011            return false;
14012        }
14013
14014        if (packageName.equals(mRequiredInstallerPackage)) {
14015            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14016                    + "\": required for package installation");
14017            return false;
14018        }
14019
14020        if (packageName.equals(mRequiredUninstallerPackage)) {
14021            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14022                    + "\": required for package uninstallation");
14023            return false;
14024        }
14025
14026        if (packageName.equals(mRequiredVerifierPackage)) {
14027            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14028                    + "\": required for package verification");
14029            return false;
14030        }
14031
14032        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14033            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14034                    + "\": is the default dialer");
14035            return false;
14036        }
14037
14038        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14039            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14040                    + "\": protected package");
14041            return false;
14042        }
14043
14044        // Cannot suspend static shared libs as they are considered
14045        // a part of the using app (emulating static linking). Also
14046        // static libs are installed always on internal storage.
14047        PackageParser.Package pkg = mPackages.get(packageName);
14048        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14049            Slog.w(TAG, "Cannot suspend package: " + packageName
14050                    + " providing static shared library: "
14051                    + pkg.staticSharedLibName);
14052            return false;
14053        }
14054
14055        return true;
14056    }
14057
14058    private String getActiveLauncherPackageName(int userId) {
14059        Intent intent = new Intent(Intent.ACTION_MAIN);
14060        intent.addCategory(Intent.CATEGORY_HOME);
14061        ResolveInfo resolveInfo = resolveIntent(
14062                intent,
14063                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14064                PackageManager.MATCH_DEFAULT_ONLY,
14065                userId);
14066
14067        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14068    }
14069
14070    private String getDefaultDialerPackageName(int userId) {
14071        synchronized (mPackages) {
14072            return mSettings.getDefaultDialerPackageNameLPw(userId);
14073        }
14074    }
14075
14076    @Override
14077    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14078        mContext.enforceCallingOrSelfPermission(
14079                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14080                "Only package verification agents can verify applications");
14081
14082        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14083        final PackageVerificationResponse response = new PackageVerificationResponse(
14084                verificationCode, Binder.getCallingUid());
14085        msg.arg1 = id;
14086        msg.obj = response;
14087        mHandler.sendMessage(msg);
14088    }
14089
14090    @Override
14091    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14092            long millisecondsToDelay) {
14093        mContext.enforceCallingOrSelfPermission(
14094                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14095                "Only package verification agents can extend verification timeouts");
14096
14097        final PackageVerificationState state = mPendingVerification.get(id);
14098        final PackageVerificationResponse response = new PackageVerificationResponse(
14099                verificationCodeAtTimeout, Binder.getCallingUid());
14100
14101        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14102            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14103        }
14104        if (millisecondsToDelay < 0) {
14105            millisecondsToDelay = 0;
14106        }
14107        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14108                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14109            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14110        }
14111
14112        if ((state != null) && !state.timeoutExtended()) {
14113            state.extendTimeout();
14114
14115            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14116            msg.arg1 = id;
14117            msg.obj = response;
14118            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14119        }
14120    }
14121
14122    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14123            int verificationCode, UserHandle user) {
14124        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14125        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14126        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14127        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14128        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14129
14130        mContext.sendBroadcastAsUser(intent, user,
14131                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14132    }
14133
14134    private ComponentName matchComponentForVerifier(String packageName,
14135            List<ResolveInfo> receivers) {
14136        ActivityInfo targetReceiver = null;
14137
14138        final int NR = receivers.size();
14139        for (int i = 0; i < NR; i++) {
14140            final ResolveInfo info = receivers.get(i);
14141            if (info.activityInfo == null) {
14142                continue;
14143            }
14144
14145            if (packageName.equals(info.activityInfo.packageName)) {
14146                targetReceiver = info.activityInfo;
14147                break;
14148            }
14149        }
14150
14151        if (targetReceiver == null) {
14152            return null;
14153        }
14154
14155        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14156    }
14157
14158    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14159            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14160        if (pkgInfo.verifiers.length == 0) {
14161            return null;
14162        }
14163
14164        final int N = pkgInfo.verifiers.length;
14165        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14166        for (int i = 0; i < N; i++) {
14167            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14168
14169            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14170                    receivers);
14171            if (comp == null) {
14172                continue;
14173            }
14174
14175            final int verifierUid = getUidForVerifier(verifierInfo);
14176            if (verifierUid == -1) {
14177                continue;
14178            }
14179
14180            if (DEBUG_VERIFY) {
14181                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14182                        + " with the correct signature");
14183            }
14184            sufficientVerifiers.add(comp);
14185            verificationState.addSufficientVerifier(verifierUid);
14186        }
14187
14188        return sufficientVerifiers;
14189    }
14190
14191    private int getUidForVerifier(VerifierInfo verifierInfo) {
14192        synchronized (mPackages) {
14193            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14194            if (pkg == null) {
14195                return -1;
14196            } else if (pkg.mSignatures.length != 1) {
14197                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14198                        + " has more than one signature; ignoring");
14199                return -1;
14200            }
14201
14202            /*
14203             * If the public key of the package's signature does not match
14204             * our expected public key, then this is a different package and
14205             * we should skip.
14206             */
14207
14208            final byte[] expectedPublicKey;
14209            try {
14210                final Signature verifierSig = pkg.mSignatures[0];
14211                final PublicKey publicKey = verifierSig.getPublicKey();
14212                expectedPublicKey = publicKey.getEncoded();
14213            } catch (CertificateException e) {
14214                return -1;
14215            }
14216
14217            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14218
14219            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14220                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14221                        + " does not have the expected public key; ignoring");
14222                return -1;
14223            }
14224
14225            return pkg.applicationInfo.uid;
14226        }
14227    }
14228
14229    @Override
14230    public void finishPackageInstall(int token, boolean didLaunch) {
14231        enforceSystemOrRoot("Only the system is allowed to finish installs");
14232
14233        if (DEBUG_INSTALL) {
14234            Slog.v(TAG, "BM finishing package install for " + token);
14235        }
14236        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14237
14238        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14239        mHandler.sendMessage(msg);
14240    }
14241
14242    /**
14243     * Get the verification agent timeout.  Used for both the APK verifier and the
14244     * intent filter verifier.
14245     *
14246     * @return verification timeout in milliseconds
14247     */
14248    private long getVerificationTimeout() {
14249        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14250                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14251                DEFAULT_VERIFICATION_TIMEOUT);
14252    }
14253
14254    /**
14255     * Get the default verification agent response code.
14256     *
14257     * @return default verification response code
14258     */
14259    private int getDefaultVerificationResponse(UserHandle user) {
14260        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14261            return PackageManager.VERIFICATION_REJECT;
14262        }
14263        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14264                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14265                DEFAULT_VERIFICATION_RESPONSE);
14266    }
14267
14268    /**
14269     * Check whether or not package verification has been enabled.
14270     *
14271     * @return true if verification should be performed
14272     */
14273    private boolean isVerificationEnabled(int userId, int installFlags) {
14274        if (!DEFAULT_VERIFY_ENABLE) {
14275            return false;
14276        }
14277
14278        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14279
14280        // Check if installing from ADB
14281        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14282            // Do not run verification in a test harness environment
14283            if (ActivityManager.isRunningInTestHarness()) {
14284                return false;
14285            }
14286            if (ensureVerifyAppsEnabled) {
14287                return true;
14288            }
14289            // Check if the developer does not want package verification for ADB installs
14290            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14291                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14292                return false;
14293            }
14294        }
14295
14296        if (ensureVerifyAppsEnabled) {
14297            return true;
14298        }
14299
14300        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14301                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14302    }
14303
14304    @Override
14305    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14306            throws RemoteException {
14307        mContext.enforceCallingOrSelfPermission(
14308                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14309                "Only intentfilter verification agents can verify applications");
14310
14311        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14312        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14313                Binder.getCallingUid(), verificationCode, failedDomains);
14314        msg.arg1 = id;
14315        msg.obj = response;
14316        mHandler.sendMessage(msg);
14317    }
14318
14319    @Override
14320    public int getIntentVerificationStatus(String packageName, int userId) {
14321        synchronized (mPackages) {
14322            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14323        }
14324    }
14325
14326    @Override
14327    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14328        mContext.enforceCallingOrSelfPermission(
14329                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14330
14331        boolean result = false;
14332        synchronized (mPackages) {
14333            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14334        }
14335        if (result) {
14336            scheduleWritePackageRestrictionsLocked(userId);
14337        }
14338        return result;
14339    }
14340
14341    @Override
14342    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14343            String packageName) {
14344        synchronized (mPackages) {
14345            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14346        }
14347    }
14348
14349    @Override
14350    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14351        if (TextUtils.isEmpty(packageName)) {
14352            return ParceledListSlice.emptyList();
14353        }
14354        synchronized (mPackages) {
14355            PackageParser.Package pkg = mPackages.get(packageName);
14356            if (pkg == null || pkg.activities == null) {
14357                return ParceledListSlice.emptyList();
14358            }
14359            final int count = pkg.activities.size();
14360            ArrayList<IntentFilter> result = new ArrayList<>();
14361            for (int n=0; n<count; n++) {
14362                PackageParser.Activity activity = pkg.activities.get(n);
14363                if (activity.intents != null && activity.intents.size() > 0) {
14364                    result.addAll(activity.intents);
14365                }
14366            }
14367            return new ParceledListSlice<>(result);
14368        }
14369    }
14370
14371    @Override
14372    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14373        mContext.enforceCallingOrSelfPermission(
14374                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14375
14376        synchronized (mPackages) {
14377            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14378            if (packageName != null) {
14379                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14380                        packageName, userId);
14381            }
14382            return result;
14383        }
14384    }
14385
14386    @Override
14387    public String getDefaultBrowserPackageName(int userId) {
14388        synchronized (mPackages) {
14389            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14390        }
14391    }
14392
14393    /**
14394     * Get the "allow unknown sources" setting.
14395     *
14396     * @return the current "allow unknown sources" setting
14397     */
14398    private int getUnknownSourcesSettings() {
14399        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14400                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14401                -1);
14402    }
14403
14404    @Override
14405    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14406        final int uid = Binder.getCallingUid();
14407        // writer
14408        synchronized (mPackages) {
14409            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14410            if (targetPackageSetting == null) {
14411                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14412            }
14413
14414            PackageSetting installerPackageSetting;
14415            if (installerPackageName != null) {
14416                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14417                if (installerPackageSetting == null) {
14418                    throw new IllegalArgumentException("Unknown installer package: "
14419                            + installerPackageName);
14420                }
14421            } else {
14422                installerPackageSetting = null;
14423            }
14424
14425            Signature[] callerSignature;
14426            Object obj = mSettings.getUserIdLPr(uid);
14427            if (obj != null) {
14428                if (obj instanceof SharedUserSetting) {
14429                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14430                } else if (obj instanceof PackageSetting) {
14431                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14432                } else {
14433                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14434                }
14435            } else {
14436                throw new SecurityException("Unknown calling UID: " + uid);
14437            }
14438
14439            // Verify: can't set installerPackageName to a package that is
14440            // not signed with the same cert as the caller.
14441            if (installerPackageSetting != null) {
14442                if (compareSignatures(callerSignature,
14443                        installerPackageSetting.signatures.mSignatures)
14444                        != PackageManager.SIGNATURE_MATCH) {
14445                    throw new SecurityException(
14446                            "Caller does not have same cert as new installer package "
14447                            + installerPackageName);
14448                }
14449            }
14450
14451            // Verify: if target already has an installer package, it must
14452            // be signed with the same cert as the caller.
14453            if (targetPackageSetting.installerPackageName != null) {
14454                PackageSetting setting = mSettings.mPackages.get(
14455                        targetPackageSetting.installerPackageName);
14456                // If the currently set package isn't valid, then it's always
14457                // okay to change it.
14458                if (setting != null) {
14459                    if (compareSignatures(callerSignature,
14460                            setting.signatures.mSignatures)
14461                            != PackageManager.SIGNATURE_MATCH) {
14462                        throw new SecurityException(
14463                                "Caller does not have same cert as old installer package "
14464                                + targetPackageSetting.installerPackageName);
14465                    }
14466                }
14467            }
14468
14469            // Okay!
14470            targetPackageSetting.installerPackageName = installerPackageName;
14471            if (installerPackageName != null) {
14472                mSettings.mInstallerPackages.add(installerPackageName);
14473            }
14474            scheduleWriteSettingsLocked();
14475        }
14476    }
14477
14478    @Override
14479    public void setApplicationCategoryHint(String packageName, int categoryHint,
14480            String callerPackageName) {
14481        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14482                callerPackageName);
14483        synchronized (mPackages) {
14484            PackageSetting ps = mSettings.mPackages.get(packageName);
14485            if (ps == null) {
14486                throw new IllegalArgumentException("Unknown target package " + packageName);
14487            }
14488
14489            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14490                throw new IllegalArgumentException("Calling package " + callerPackageName
14491                        + " is not installer for " + packageName);
14492            }
14493
14494            if (ps.categoryHint != categoryHint) {
14495                ps.categoryHint = categoryHint;
14496                scheduleWriteSettingsLocked();
14497            }
14498        }
14499    }
14500
14501    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14502        // Queue up an async operation since the package installation may take a little while.
14503        mHandler.post(new Runnable() {
14504            public void run() {
14505                mHandler.removeCallbacks(this);
14506                 // Result object to be returned
14507                PackageInstalledInfo res = new PackageInstalledInfo();
14508                res.setReturnCode(currentStatus);
14509                res.uid = -1;
14510                res.pkg = null;
14511                res.removedInfo = null;
14512                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14513                    args.doPreInstall(res.returnCode);
14514                    synchronized (mInstallLock) {
14515                        installPackageTracedLI(args, res);
14516                    }
14517                    args.doPostInstall(res.returnCode, res.uid);
14518                }
14519
14520                // A restore should be performed at this point if (a) the install
14521                // succeeded, (b) the operation is not an update, and (c) the new
14522                // package has not opted out of backup participation.
14523                final boolean update = res.removedInfo != null
14524                        && res.removedInfo.removedPackage != null;
14525                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14526                boolean doRestore = !update
14527                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14528
14529                // Set up the post-install work request bookkeeping.  This will be used
14530                // and cleaned up by the post-install event handling regardless of whether
14531                // there's a restore pass performed.  Token values are >= 1.
14532                int token;
14533                if (mNextInstallToken < 0) mNextInstallToken = 1;
14534                token = mNextInstallToken++;
14535
14536                PostInstallData data = new PostInstallData(args, res);
14537                mRunningInstalls.put(token, data);
14538                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14539
14540                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14541                    // Pass responsibility to the Backup Manager.  It will perform a
14542                    // restore if appropriate, then pass responsibility back to the
14543                    // Package Manager to run the post-install observer callbacks
14544                    // and broadcasts.
14545                    IBackupManager bm = IBackupManager.Stub.asInterface(
14546                            ServiceManager.getService(Context.BACKUP_SERVICE));
14547                    if (bm != null) {
14548                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14549                                + " to BM for possible restore");
14550                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14551                        try {
14552                            // TODO: http://b/22388012
14553                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14554                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14555                            } else {
14556                                doRestore = false;
14557                            }
14558                        } catch (RemoteException e) {
14559                            // can't happen; the backup manager is local
14560                        } catch (Exception e) {
14561                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14562                            doRestore = false;
14563                        }
14564                    } else {
14565                        Slog.e(TAG, "Backup Manager not found!");
14566                        doRestore = false;
14567                    }
14568                }
14569
14570                if (!doRestore) {
14571                    // No restore possible, or the Backup Manager was mysteriously not
14572                    // available -- just fire the post-install work request directly.
14573                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14574
14575                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14576
14577                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14578                    mHandler.sendMessage(msg);
14579                }
14580            }
14581        });
14582    }
14583
14584    /**
14585     * Callback from PackageSettings whenever an app is first transitioned out of the
14586     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14587     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14588     * here whether the app is the target of an ongoing install, and only send the
14589     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14590     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14591     * handling.
14592     */
14593    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14594        // Serialize this with the rest of the install-process message chain.  In the
14595        // restore-at-install case, this Runnable will necessarily run before the
14596        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14597        // are coherent.  In the non-restore case, the app has already completed install
14598        // and been launched through some other means, so it is not in a problematic
14599        // state for observers to see the FIRST_LAUNCH signal.
14600        mHandler.post(new Runnable() {
14601            @Override
14602            public void run() {
14603                for (int i = 0; i < mRunningInstalls.size(); i++) {
14604                    final PostInstallData data = mRunningInstalls.valueAt(i);
14605                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14606                        continue;
14607                    }
14608                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14609                        // right package; but is it for the right user?
14610                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14611                            if (userId == data.res.newUsers[uIndex]) {
14612                                if (DEBUG_BACKUP) {
14613                                    Slog.i(TAG, "Package " + pkgName
14614                                            + " being restored so deferring FIRST_LAUNCH");
14615                                }
14616                                return;
14617                            }
14618                        }
14619                    }
14620                }
14621                // didn't find it, so not being restored
14622                if (DEBUG_BACKUP) {
14623                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14624                }
14625                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14626            }
14627        });
14628    }
14629
14630    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14631        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14632                installerPkg, null, userIds);
14633    }
14634
14635    private abstract class HandlerParams {
14636        private static final int MAX_RETRIES = 4;
14637
14638        /**
14639         * Number of times startCopy() has been attempted and had a non-fatal
14640         * error.
14641         */
14642        private int mRetries = 0;
14643
14644        /** User handle for the user requesting the information or installation. */
14645        private final UserHandle mUser;
14646        String traceMethod;
14647        int traceCookie;
14648
14649        HandlerParams(UserHandle user) {
14650            mUser = user;
14651        }
14652
14653        UserHandle getUser() {
14654            return mUser;
14655        }
14656
14657        HandlerParams setTraceMethod(String traceMethod) {
14658            this.traceMethod = traceMethod;
14659            return this;
14660        }
14661
14662        HandlerParams setTraceCookie(int traceCookie) {
14663            this.traceCookie = traceCookie;
14664            return this;
14665        }
14666
14667        final boolean startCopy() {
14668            boolean res;
14669            try {
14670                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14671
14672                if (++mRetries > MAX_RETRIES) {
14673                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14674                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14675                    handleServiceError();
14676                    return false;
14677                } else {
14678                    handleStartCopy();
14679                    res = true;
14680                }
14681            } catch (RemoteException e) {
14682                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14683                mHandler.sendEmptyMessage(MCS_RECONNECT);
14684                res = false;
14685            }
14686            handleReturnCode();
14687            return res;
14688        }
14689
14690        final void serviceError() {
14691            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14692            handleServiceError();
14693            handleReturnCode();
14694        }
14695
14696        abstract void handleStartCopy() throws RemoteException;
14697        abstract void handleServiceError();
14698        abstract void handleReturnCode();
14699    }
14700
14701    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14702        for (File path : paths) {
14703            try {
14704                mcs.clearDirectory(path.getAbsolutePath());
14705            } catch (RemoteException e) {
14706            }
14707        }
14708    }
14709
14710    static class OriginInfo {
14711        /**
14712         * Location where install is coming from, before it has been
14713         * copied/renamed into place. This could be a single monolithic APK
14714         * file, or a cluster directory. This location may be untrusted.
14715         */
14716        final File file;
14717        final String cid;
14718
14719        /**
14720         * Flag indicating that {@link #file} or {@link #cid} has already been
14721         * staged, meaning downstream users don't need to defensively copy the
14722         * contents.
14723         */
14724        final boolean staged;
14725
14726        /**
14727         * Flag indicating that {@link #file} or {@link #cid} is an already
14728         * installed app that is being moved.
14729         */
14730        final boolean existing;
14731
14732        final String resolvedPath;
14733        final File resolvedFile;
14734
14735        static OriginInfo fromNothing() {
14736            return new OriginInfo(null, null, false, false);
14737        }
14738
14739        static OriginInfo fromUntrustedFile(File file) {
14740            return new OriginInfo(file, null, false, false);
14741        }
14742
14743        static OriginInfo fromExistingFile(File file) {
14744            return new OriginInfo(file, null, false, true);
14745        }
14746
14747        static OriginInfo fromStagedFile(File file) {
14748            return new OriginInfo(file, null, true, false);
14749        }
14750
14751        static OriginInfo fromStagedContainer(String cid) {
14752            return new OriginInfo(null, cid, true, false);
14753        }
14754
14755        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14756            this.file = file;
14757            this.cid = cid;
14758            this.staged = staged;
14759            this.existing = existing;
14760
14761            if (cid != null) {
14762                resolvedPath = PackageHelper.getSdDir(cid);
14763                resolvedFile = new File(resolvedPath);
14764            } else if (file != null) {
14765                resolvedPath = file.getAbsolutePath();
14766                resolvedFile = file;
14767            } else {
14768                resolvedPath = null;
14769                resolvedFile = null;
14770            }
14771        }
14772    }
14773
14774    static class MoveInfo {
14775        final int moveId;
14776        final String fromUuid;
14777        final String toUuid;
14778        final String packageName;
14779        final String dataAppName;
14780        final int appId;
14781        final String seinfo;
14782        final int targetSdkVersion;
14783
14784        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14785                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14786            this.moveId = moveId;
14787            this.fromUuid = fromUuid;
14788            this.toUuid = toUuid;
14789            this.packageName = packageName;
14790            this.dataAppName = dataAppName;
14791            this.appId = appId;
14792            this.seinfo = seinfo;
14793            this.targetSdkVersion = targetSdkVersion;
14794        }
14795    }
14796
14797    static class VerificationInfo {
14798        /** A constant used to indicate that a uid value is not present. */
14799        public static final int NO_UID = -1;
14800
14801        /** URI referencing where the package was downloaded from. */
14802        final Uri originatingUri;
14803
14804        /** HTTP referrer URI associated with the originatingURI. */
14805        final Uri referrer;
14806
14807        /** UID of the application that the install request originated from. */
14808        final int originatingUid;
14809
14810        /** UID of application requesting the install */
14811        final int installerUid;
14812
14813        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14814            this.originatingUri = originatingUri;
14815            this.referrer = referrer;
14816            this.originatingUid = originatingUid;
14817            this.installerUid = installerUid;
14818        }
14819    }
14820
14821    class InstallParams extends HandlerParams {
14822        final OriginInfo origin;
14823        final MoveInfo move;
14824        final IPackageInstallObserver2 observer;
14825        int installFlags;
14826        final String installerPackageName;
14827        final String volumeUuid;
14828        private InstallArgs mArgs;
14829        private int mRet;
14830        final String packageAbiOverride;
14831        final String[] grantedRuntimePermissions;
14832        final VerificationInfo verificationInfo;
14833        final Certificate[][] certificates;
14834        final int installReason;
14835
14836        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14837                int installFlags, String installerPackageName, String volumeUuid,
14838                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14839                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14840            super(user);
14841            this.origin = origin;
14842            this.move = move;
14843            this.observer = observer;
14844            this.installFlags = installFlags;
14845            this.installerPackageName = installerPackageName;
14846            this.volumeUuid = volumeUuid;
14847            this.verificationInfo = verificationInfo;
14848            this.packageAbiOverride = packageAbiOverride;
14849            this.grantedRuntimePermissions = grantedPermissions;
14850            this.certificates = certificates;
14851            this.installReason = installReason;
14852        }
14853
14854        @Override
14855        public String toString() {
14856            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14857                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14858        }
14859
14860        private int installLocationPolicy(PackageInfoLite pkgLite) {
14861            String packageName = pkgLite.packageName;
14862            int installLocation = pkgLite.installLocation;
14863            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14864            // reader
14865            synchronized (mPackages) {
14866                // Currently installed package which the new package is attempting to replace or
14867                // null if no such package is installed.
14868                PackageParser.Package installedPkg = mPackages.get(packageName);
14869                // Package which currently owns the data which the new package will own if installed.
14870                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14871                // will be null whereas dataOwnerPkg will contain information about the package
14872                // which was uninstalled while keeping its data.
14873                PackageParser.Package dataOwnerPkg = installedPkg;
14874                if (dataOwnerPkg  == null) {
14875                    PackageSetting ps = mSettings.mPackages.get(packageName);
14876                    if (ps != null) {
14877                        dataOwnerPkg = ps.pkg;
14878                    }
14879                }
14880
14881                if (dataOwnerPkg != null) {
14882                    // If installed, the package will get access to data left on the device by its
14883                    // predecessor. As a security measure, this is permited only if this is not a
14884                    // version downgrade or if the predecessor package is marked as debuggable and
14885                    // a downgrade is explicitly requested.
14886                    //
14887                    // On debuggable platform builds, downgrades are permitted even for
14888                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14889                    // not offer security guarantees and thus it's OK to disable some security
14890                    // mechanisms to make debugging/testing easier on those builds. However, even on
14891                    // debuggable builds downgrades of packages are permitted only if requested via
14892                    // installFlags. This is because we aim to keep the behavior of debuggable
14893                    // platform builds as close as possible to the behavior of non-debuggable
14894                    // platform builds.
14895                    final boolean downgradeRequested =
14896                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14897                    final boolean packageDebuggable =
14898                                (dataOwnerPkg.applicationInfo.flags
14899                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14900                    final boolean downgradePermitted =
14901                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14902                    if (!downgradePermitted) {
14903                        try {
14904                            checkDowngrade(dataOwnerPkg, pkgLite);
14905                        } catch (PackageManagerException e) {
14906                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14907                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14908                        }
14909                    }
14910                }
14911
14912                if (installedPkg != null) {
14913                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14914                        // Check for updated system application.
14915                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14916                            if (onSd) {
14917                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14918                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14919                            }
14920                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14921                        } else {
14922                            if (onSd) {
14923                                // Install flag overrides everything.
14924                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14925                            }
14926                            // If current upgrade specifies particular preference
14927                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14928                                // Application explicitly specified internal.
14929                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14930                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14931                                // App explictly prefers external. Let policy decide
14932                            } else {
14933                                // Prefer previous location
14934                                if (isExternal(installedPkg)) {
14935                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14936                                }
14937                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14938                            }
14939                        }
14940                    } else {
14941                        // Invalid install. Return error code
14942                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14943                    }
14944                }
14945            }
14946            // All the special cases have been taken care of.
14947            // Return result based on recommended install location.
14948            if (onSd) {
14949                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14950            }
14951            return pkgLite.recommendedInstallLocation;
14952        }
14953
14954        /*
14955         * Invoke remote method to get package information and install
14956         * location values. Override install location based on default
14957         * policy if needed and then create install arguments based
14958         * on the install location.
14959         */
14960        public void handleStartCopy() throws RemoteException {
14961            int ret = PackageManager.INSTALL_SUCCEEDED;
14962
14963            // If we're already staged, we've firmly committed to an install location
14964            if (origin.staged) {
14965                if (origin.file != null) {
14966                    installFlags |= PackageManager.INSTALL_INTERNAL;
14967                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14968                } else if (origin.cid != null) {
14969                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14970                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14971                } else {
14972                    throw new IllegalStateException("Invalid stage location");
14973                }
14974            }
14975
14976            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14977            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14978            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14979            PackageInfoLite pkgLite = null;
14980
14981            if (onInt && onSd) {
14982                // Check if both bits are set.
14983                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14984                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14985            } else if (onSd && ephemeral) {
14986                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14987                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14988            } else {
14989                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14990                        packageAbiOverride);
14991
14992                if (DEBUG_EPHEMERAL && ephemeral) {
14993                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14994                }
14995
14996                /*
14997                 * If we have too little free space, try to free cache
14998                 * before giving up.
14999                 */
15000                if (!origin.staged && pkgLite.recommendedInstallLocation
15001                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15002                    // TODO: focus freeing disk space on the target device
15003                    final StorageManager storage = StorageManager.from(mContext);
15004                    final long lowThreshold = storage.getStorageLowBytes(
15005                            Environment.getDataDirectory());
15006
15007                    final long sizeBytes = mContainerService.calculateInstalledSize(
15008                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15009
15010                    try {
15011                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
15012                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15013                                installFlags, packageAbiOverride);
15014                    } catch (InstallerException e) {
15015                        Slog.w(TAG, "Failed to free cache", e);
15016                    }
15017
15018                    /*
15019                     * The cache free must have deleted the file we
15020                     * downloaded to install.
15021                     *
15022                     * TODO: fix the "freeCache" call to not delete
15023                     *       the file we care about.
15024                     */
15025                    if (pkgLite.recommendedInstallLocation
15026                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15027                        pkgLite.recommendedInstallLocation
15028                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15029                    }
15030                }
15031            }
15032
15033            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15034                int loc = pkgLite.recommendedInstallLocation;
15035                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15036                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15037                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15038                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15039                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15040                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15041                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15042                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15043                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15044                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15045                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15046                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15047                } else {
15048                    // Override with defaults if needed.
15049                    loc = installLocationPolicy(pkgLite);
15050                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15051                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15052                    } else if (!onSd && !onInt) {
15053                        // Override install location with flags
15054                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15055                            // Set the flag to install on external media.
15056                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15057                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15058                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15059                            if (DEBUG_EPHEMERAL) {
15060                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15061                            }
15062                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15063                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15064                                    |PackageManager.INSTALL_INTERNAL);
15065                        } else {
15066                            // Make sure the flag for installing on external
15067                            // media is unset
15068                            installFlags |= PackageManager.INSTALL_INTERNAL;
15069                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15070                        }
15071                    }
15072                }
15073            }
15074
15075            final InstallArgs args = createInstallArgs(this);
15076            mArgs = args;
15077
15078            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15079                // TODO: http://b/22976637
15080                // Apps installed for "all" users use the device owner to verify the app
15081                UserHandle verifierUser = getUser();
15082                if (verifierUser == UserHandle.ALL) {
15083                    verifierUser = UserHandle.SYSTEM;
15084                }
15085
15086                /*
15087                 * Determine if we have any installed package verifiers. If we
15088                 * do, then we'll defer to them to verify the packages.
15089                 */
15090                final int requiredUid = mRequiredVerifierPackage == null ? -1
15091                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15092                                verifierUser.getIdentifier());
15093                if (!origin.existing && requiredUid != -1
15094                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15095                    final Intent verification = new Intent(
15096                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15097                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15098                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15099                            PACKAGE_MIME_TYPE);
15100                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15101
15102                    // Query all live verifiers based on current user state
15103                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15104                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15105
15106                    if (DEBUG_VERIFY) {
15107                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15108                                + verification.toString() + " with " + pkgLite.verifiers.length
15109                                + " optional verifiers");
15110                    }
15111
15112                    final int verificationId = mPendingVerificationToken++;
15113
15114                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15115
15116                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15117                            installerPackageName);
15118
15119                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15120                            installFlags);
15121
15122                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15123                            pkgLite.packageName);
15124
15125                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15126                            pkgLite.versionCode);
15127
15128                    if (verificationInfo != null) {
15129                        if (verificationInfo.originatingUri != null) {
15130                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15131                                    verificationInfo.originatingUri);
15132                        }
15133                        if (verificationInfo.referrer != null) {
15134                            verification.putExtra(Intent.EXTRA_REFERRER,
15135                                    verificationInfo.referrer);
15136                        }
15137                        if (verificationInfo.originatingUid >= 0) {
15138                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15139                                    verificationInfo.originatingUid);
15140                        }
15141                        if (verificationInfo.installerUid >= 0) {
15142                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15143                                    verificationInfo.installerUid);
15144                        }
15145                    }
15146
15147                    final PackageVerificationState verificationState = new PackageVerificationState(
15148                            requiredUid, args);
15149
15150                    mPendingVerification.append(verificationId, verificationState);
15151
15152                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15153                            receivers, verificationState);
15154
15155                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15156                    final long idleDuration = getVerificationTimeout();
15157
15158                    /*
15159                     * If any sufficient verifiers were listed in the package
15160                     * manifest, attempt to ask them.
15161                     */
15162                    if (sufficientVerifiers != null) {
15163                        final int N = sufficientVerifiers.size();
15164                        if (N == 0) {
15165                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15166                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15167                        } else {
15168                            for (int i = 0; i < N; i++) {
15169                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15170                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15171                                        verifierComponent.getPackageName(), idleDuration,
15172                                        verifierUser.getIdentifier(), false, "package verifier");
15173
15174                                final Intent sufficientIntent = new Intent(verification);
15175                                sufficientIntent.setComponent(verifierComponent);
15176                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15177                            }
15178                        }
15179                    }
15180
15181                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15182                            mRequiredVerifierPackage, receivers);
15183                    if (ret == PackageManager.INSTALL_SUCCEEDED
15184                            && mRequiredVerifierPackage != null) {
15185                        Trace.asyncTraceBegin(
15186                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15187                        /*
15188                         * Send the intent to the required verification agent,
15189                         * but only start the verification timeout after the
15190                         * target BroadcastReceivers have run.
15191                         */
15192                        verification.setComponent(requiredVerifierComponent);
15193                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15194                                mRequiredVerifierPackage, idleDuration,
15195                                verifierUser.getIdentifier(), false, "package verifier");
15196                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15197                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15198                                new BroadcastReceiver() {
15199                                    @Override
15200                                    public void onReceive(Context context, Intent intent) {
15201                                        final Message msg = mHandler
15202                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15203                                        msg.arg1 = verificationId;
15204                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15205                                    }
15206                                }, null, 0, null, null);
15207
15208                        /*
15209                         * We don't want the copy to proceed until verification
15210                         * succeeds, so null out this field.
15211                         */
15212                        mArgs = null;
15213                    }
15214                } else {
15215                    /*
15216                     * No package verification is enabled, so immediately start
15217                     * the remote call to initiate copy using temporary file.
15218                     */
15219                    ret = args.copyApk(mContainerService, true);
15220                }
15221            }
15222
15223            mRet = ret;
15224        }
15225
15226        @Override
15227        void handleReturnCode() {
15228            // If mArgs is null, then MCS couldn't be reached. When it
15229            // reconnects, it will try again to install. At that point, this
15230            // will succeed.
15231            if (mArgs != null) {
15232                processPendingInstall(mArgs, mRet);
15233            }
15234        }
15235
15236        @Override
15237        void handleServiceError() {
15238            mArgs = createInstallArgs(this);
15239            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15240        }
15241
15242        public boolean isForwardLocked() {
15243            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15244        }
15245    }
15246
15247    /**
15248     * Used during creation of InstallArgs
15249     *
15250     * @param installFlags package installation flags
15251     * @return true if should be installed on external storage
15252     */
15253    private static boolean installOnExternalAsec(int installFlags) {
15254        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15255            return false;
15256        }
15257        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15258            return true;
15259        }
15260        return false;
15261    }
15262
15263    /**
15264     * Used during creation of InstallArgs
15265     *
15266     * @param installFlags package installation flags
15267     * @return true if should be installed as forward locked
15268     */
15269    private static boolean installForwardLocked(int installFlags) {
15270        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15271    }
15272
15273    private InstallArgs createInstallArgs(InstallParams params) {
15274        if (params.move != null) {
15275            return new MoveInstallArgs(params);
15276        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15277            return new AsecInstallArgs(params);
15278        } else {
15279            return new FileInstallArgs(params);
15280        }
15281    }
15282
15283    /**
15284     * Create args that describe an existing installed package. Typically used
15285     * when cleaning up old installs, or used as a move source.
15286     */
15287    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15288            String resourcePath, String[] instructionSets) {
15289        final boolean isInAsec;
15290        if (installOnExternalAsec(installFlags)) {
15291            /* Apps on SD card are always in ASEC containers. */
15292            isInAsec = true;
15293        } else if (installForwardLocked(installFlags)
15294                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15295            /*
15296             * Forward-locked apps are only in ASEC containers if they're the
15297             * new style
15298             */
15299            isInAsec = true;
15300        } else {
15301            isInAsec = false;
15302        }
15303
15304        if (isInAsec) {
15305            return new AsecInstallArgs(codePath, instructionSets,
15306                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15307        } else {
15308            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15309        }
15310    }
15311
15312    static abstract class InstallArgs {
15313        /** @see InstallParams#origin */
15314        final OriginInfo origin;
15315        /** @see InstallParams#move */
15316        final MoveInfo move;
15317
15318        final IPackageInstallObserver2 observer;
15319        // Always refers to PackageManager flags only
15320        final int installFlags;
15321        final String installerPackageName;
15322        final String volumeUuid;
15323        final UserHandle user;
15324        final String abiOverride;
15325        final String[] installGrantPermissions;
15326        /** If non-null, drop an async trace when the install completes */
15327        final String traceMethod;
15328        final int traceCookie;
15329        final Certificate[][] certificates;
15330        final int installReason;
15331
15332        // The list of instruction sets supported by this app. This is currently
15333        // only used during the rmdex() phase to clean up resources. We can get rid of this
15334        // if we move dex files under the common app path.
15335        /* nullable */ String[] instructionSets;
15336
15337        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15338                int installFlags, String installerPackageName, String volumeUuid,
15339                UserHandle user, String[] instructionSets,
15340                String abiOverride, String[] installGrantPermissions,
15341                String traceMethod, int traceCookie, Certificate[][] certificates,
15342                int installReason) {
15343            this.origin = origin;
15344            this.move = move;
15345            this.installFlags = installFlags;
15346            this.observer = observer;
15347            this.installerPackageName = installerPackageName;
15348            this.volumeUuid = volumeUuid;
15349            this.user = user;
15350            this.instructionSets = instructionSets;
15351            this.abiOverride = abiOverride;
15352            this.installGrantPermissions = installGrantPermissions;
15353            this.traceMethod = traceMethod;
15354            this.traceCookie = traceCookie;
15355            this.certificates = certificates;
15356            this.installReason = installReason;
15357        }
15358
15359        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15360        abstract int doPreInstall(int status);
15361
15362        /**
15363         * Rename package into final resting place. All paths on the given
15364         * scanned package should be updated to reflect the rename.
15365         */
15366        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15367        abstract int doPostInstall(int status, int uid);
15368
15369        /** @see PackageSettingBase#codePathString */
15370        abstract String getCodePath();
15371        /** @see PackageSettingBase#resourcePathString */
15372        abstract String getResourcePath();
15373
15374        // Need installer lock especially for dex file removal.
15375        abstract void cleanUpResourcesLI();
15376        abstract boolean doPostDeleteLI(boolean delete);
15377
15378        /**
15379         * Called before the source arguments are copied. This is used mostly
15380         * for MoveParams when it needs to read the source file to put it in the
15381         * destination.
15382         */
15383        int doPreCopy() {
15384            return PackageManager.INSTALL_SUCCEEDED;
15385        }
15386
15387        /**
15388         * Called after the source arguments are copied. This is used mostly for
15389         * MoveParams when it needs to read the source file to put it in the
15390         * destination.
15391         */
15392        int doPostCopy(int uid) {
15393            return PackageManager.INSTALL_SUCCEEDED;
15394        }
15395
15396        protected boolean isFwdLocked() {
15397            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15398        }
15399
15400        protected boolean isExternalAsec() {
15401            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15402        }
15403
15404        protected boolean isEphemeral() {
15405            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15406        }
15407
15408        UserHandle getUser() {
15409            return user;
15410        }
15411    }
15412
15413    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15414        if (!allCodePaths.isEmpty()) {
15415            if (instructionSets == null) {
15416                throw new IllegalStateException("instructionSet == null");
15417            }
15418            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15419            for (String codePath : allCodePaths) {
15420                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15421                    try {
15422                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15423                    } catch (InstallerException ignored) {
15424                    }
15425                }
15426            }
15427        }
15428    }
15429
15430    /**
15431     * Logic to handle installation of non-ASEC applications, including copying
15432     * and renaming logic.
15433     */
15434    class FileInstallArgs extends InstallArgs {
15435        private File codeFile;
15436        private File resourceFile;
15437
15438        // Example topology:
15439        // /data/app/com.example/base.apk
15440        // /data/app/com.example/split_foo.apk
15441        // /data/app/com.example/lib/arm/libfoo.so
15442        // /data/app/com.example/lib/arm64/libfoo.so
15443        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15444
15445        /** New install */
15446        FileInstallArgs(InstallParams params) {
15447            super(params.origin, params.move, params.observer, params.installFlags,
15448                    params.installerPackageName, params.volumeUuid,
15449                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15450                    params.grantedRuntimePermissions,
15451                    params.traceMethod, params.traceCookie, params.certificates,
15452                    params.installReason);
15453            if (isFwdLocked()) {
15454                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15455            }
15456        }
15457
15458        /** Existing install */
15459        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15460            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15461                    null, null, null, 0, null /*certificates*/,
15462                    PackageManager.INSTALL_REASON_UNKNOWN);
15463            this.codeFile = (codePath != null) ? new File(codePath) : null;
15464            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15465        }
15466
15467        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15468            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15469            try {
15470                return doCopyApk(imcs, temp);
15471            } finally {
15472                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15473            }
15474        }
15475
15476        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15477            if (origin.staged) {
15478                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15479                codeFile = origin.file;
15480                resourceFile = origin.file;
15481                return PackageManager.INSTALL_SUCCEEDED;
15482            }
15483
15484            try {
15485                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15486                final File tempDir =
15487                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15488                codeFile = tempDir;
15489                resourceFile = tempDir;
15490            } catch (IOException e) {
15491                Slog.w(TAG, "Failed to create copy file: " + e);
15492                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15493            }
15494
15495            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15496                @Override
15497                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15498                    if (!FileUtils.isValidExtFilename(name)) {
15499                        throw new IllegalArgumentException("Invalid filename: " + name);
15500                    }
15501                    try {
15502                        final File file = new File(codeFile, name);
15503                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15504                                O_RDWR | O_CREAT, 0644);
15505                        Os.chmod(file.getAbsolutePath(), 0644);
15506                        return new ParcelFileDescriptor(fd);
15507                    } catch (ErrnoException e) {
15508                        throw new RemoteException("Failed to open: " + e.getMessage());
15509                    }
15510                }
15511            };
15512
15513            int ret = PackageManager.INSTALL_SUCCEEDED;
15514            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15515            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15516                Slog.e(TAG, "Failed to copy package");
15517                return ret;
15518            }
15519
15520            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15521            NativeLibraryHelper.Handle handle = null;
15522            try {
15523                handle = NativeLibraryHelper.Handle.create(codeFile);
15524                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15525                        abiOverride);
15526            } catch (IOException e) {
15527                Slog.e(TAG, "Copying native libraries failed", e);
15528                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15529            } finally {
15530                IoUtils.closeQuietly(handle);
15531            }
15532
15533            return ret;
15534        }
15535
15536        int doPreInstall(int status) {
15537            if (status != PackageManager.INSTALL_SUCCEEDED) {
15538                cleanUp();
15539            }
15540            return status;
15541        }
15542
15543        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15544            if (status != PackageManager.INSTALL_SUCCEEDED) {
15545                cleanUp();
15546                return false;
15547            }
15548
15549            final File targetDir = codeFile.getParentFile();
15550            final File beforeCodeFile = codeFile;
15551            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15552
15553            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15554            try {
15555                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15556            } catch (ErrnoException e) {
15557                Slog.w(TAG, "Failed to rename", e);
15558                return false;
15559            }
15560
15561            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15562                Slog.w(TAG, "Failed to restorecon");
15563                return false;
15564            }
15565
15566            // Reflect the rename internally
15567            codeFile = afterCodeFile;
15568            resourceFile = afterCodeFile;
15569
15570            // Reflect the rename in scanned details
15571            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15572            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15573                    afterCodeFile, pkg.baseCodePath));
15574            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15575                    afterCodeFile, pkg.splitCodePaths));
15576
15577            // Reflect the rename in app info
15578            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15579            pkg.setApplicationInfoCodePath(pkg.codePath);
15580            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15581            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15582            pkg.setApplicationInfoResourcePath(pkg.codePath);
15583            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15584            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15585
15586            return true;
15587        }
15588
15589        int doPostInstall(int status, int uid) {
15590            if (status != PackageManager.INSTALL_SUCCEEDED) {
15591                cleanUp();
15592            }
15593            return status;
15594        }
15595
15596        @Override
15597        String getCodePath() {
15598            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15599        }
15600
15601        @Override
15602        String getResourcePath() {
15603            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15604        }
15605
15606        private boolean cleanUp() {
15607            if (codeFile == null || !codeFile.exists()) {
15608                return false;
15609            }
15610
15611            removeCodePathLI(codeFile);
15612
15613            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15614                resourceFile.delete();
15615            }
15616
15617            return true;
15618        }
15619
15620        void cleanUpResourcesLI() {
15621            // Try enumerating all code paths before deleting
15622            List<String> allCodePaths = Collections.EMPTY_LIST;
15623            if (codeFile != null && codeFile.exists()) {
15624                try {
15625                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15626                    allCodePaths = pkg.getAllCodePaths();
15627                } catch (PackageParserException e) {
15628                    // Ignored; we tried our best
15629                }
15630            }
15631
15632            cleanUp();
15633            removeDexFiles(allCodePaths, instructionSets);
15634        }
15635
15636        boolean doPostDeleteLI(boolean delete) {
15637            // XXX err, shouldn't we respect the delete flag?
15638            cleanUpResourcesLI();
15639            return true;
15640        }
15641    }
15642
15643    private boolean isAsecExternal(String cid) {
15644        final String asecPath = PackageHelper.getSdFilesystem(cid);
15645        return !asecPath.startsWith(mAsecInternalPath);
15646    }
15647
15648    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15649            PackageManagerException {
15650        if (copyRet < 0) {
15651            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15652                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15653                throw new PackageManagerException(copyRet, message);
15654            }
15655        }
15656    }
15657
15658    /**
15659     * Extract the StorageManagerService "container ID" from the full code path of an
15660     * .apk.
15661     */
15662    static String cidFromCodePath(String fullCodePath) {
15663        int eidx = fullCodePath.lastIndexOf("/");
15664        String subStr1 = fullCodePath.substring(0, eidx);
15665        int sidx = subStr1.lastIndexOf("/");
15666        return subStr1.substring(sidx+1, eidx);
15667    }
15668
15669    /**
15670     * Logic to handle installation of ASEC applications, including copying and
15671     * renaming logic.
15672     */
15673    class AsecInstallArgs extends InstallArgs {
15674        static final String RES_FILE_NAME = "pkg.apk";
15675        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15676
15677        String cid;
15678        String packagePath;
15679        String resourcePath;
15680
15681        /** New install */
15682        AsecInstallArgs(InstallParams params) {
15683            super(params.origin, params.move, params.observer, params.installFlags,
15684                    params.installerPackageName, params.volumeUuid,
15685                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15686                    params.grantedRuntimePermissions,
15687                    params.traceMethod, params.traceCookie, params.certificates,
15688                    params.installReason);
15689        }
15690
15691        /** Existing install */
15692        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15693                        boolean isExternal, boolean isForwardLocked) {
15694            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15695                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15696                    instructionSets, null, null, null, 0, null /*certificates*/,
15697                    PackageManager.INSTALL_REASON_UNKNOWN);
15698            // Hackily pretend we're still looking at a full code path
15699            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15700                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15701            }
15702
15703            // Extract cid from fullCodePath
15704            int eidx = fullCodePath.lastIndexOf("/");
15705            String subStr1 = fullCodePath.substring(0, eidx);
15706            int sidx = subStr1.lastIndexOf("/");
15707            cid = subStr1.substring(sidx+1, eidx);
15708            setMountPath(subStr1);
15709        }
15710
15711        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15712            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15713                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15714                    instructionSets, null, null, null, 0, null /*certificates*/,
15715                    PackageManager.INSTALL_REASON_UNKNOWN);
15716            this.cid = cid;
15717            setMountPath(PackageHelper.getSdDir(cid));
15718        }
15719
15720        void createCopyFile() {
15721            cid = mInstallerService.allocateExternalStageCidLegacy();
15722        }
15723
15724        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15725            if (origin.staged && origin.cid != null) {
15726                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15727                cid = origin.cid;
15728                setMountPath(PackageHelper.getSdDir(cid));
15729                return PackageManager.INSTALL_SUCCEEDED;
15730            }
15731
15732            if (temp) {
15733                createCopyFile();
15734            } else {
15735                /*
15736                 * Pre-emptively destroy the container since it's destroyed if
15737                 * copying fails due to it existing anyway.
15738                 */
15739                PackageHelper.destroySdDir(cid);
15740            }
15741
15742            final String newMountPath = imcs.copyPackageToContainer(
15743                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15744                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15745
15746            if (newMountPath != null) {
15747                setMountPath(newMountPath);
15748                return PackageManager.INSTALL_SUCCEEDED;
15749            } else {
15750                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15751            }
15752        }
15753
15754        @Override
15755        String getCodePath() {
15756            return packagePath;
15757        }
15758
15759        @Override
15760        String getResourcePath() {
15761            return resourcePath;
15762        }
15763
15764        int doPreInstall(int status) {
15765            if (status != PackageManager.INSTALL_SUCCEEDED) {
15766                // Destroy container
15767                PackageHelper.destroySdDir(cid);
15768            } else {
15769                boolean mounted = PackageHelper.isContainerMounted(cid);
15770                if (!mounted) {
15771                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15772                            Process.SYSTEM_UID);
15773                    if (newMountPath != null) {
15774                        setMountPath(newMountPath);
15775                    } else {
15776                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15777                    }
15778                }
15779            }
15780            return status;
15781        }
15782
15783        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15784            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15785            String newMountPath = null;
15786            if (PackageHelper.isContainerMounted(cid)) {
15787                // Unmount the container
15788                if (!PackageHelper.unMountSdDir(cid)) {
15789                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15790                    return false;
15791                }
15792            }
15793            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15794                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15795                        " which might be stale. Will try to clean up.");
15796                // Clean up the stale container and proceed to recreate.
15797                if (!PackageHelper.destroySdDir(newCacheId)) {
15798                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15799                    return false;
15800                }
15801                // Successfully cleaned up stale container. Try to rename again.
15802                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15803                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15804                            + " inspite of cleaning it up.");
15805                    return false;
15806                }
15807            }
15808            if (!PackageHelper.isContainerMounted(newCacheId)) {
15809                Slog.w(TAG, "Mounting container " + newCacheId);
15810                newMountPath = PackageHelper.mountSdDir(newCacheId,
15811                        getEncryptKey(), Process.SYSTEM_UID);
15812            } else {
15813                newMountPath = PackageHelper.getSdDir(newCacheId);
15814            }
15815            if (newMountPath == null) {
15816                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15817                return false;
15818            }
15819            Log.i(TAG, "Succesfully renamed " + cid +
15820                    " to " + newCacheId +
15821                    " at new path: " + newMountPath);
15822            cid = newCacheId;
15823
15824            final File beforeCodeFile = new File(packagePath);
15825            setMountPath(newMountPath);
15826            final File afterCodeFile = new File(packagePath);
15827
15828            // Reflect the rename in scanned details
15829            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15830            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15831                    afterCodeFile, pkg.baseCodePath));
15832            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15833                    afterCodeFile, pkg.splitCodePaths));
15834
15835            // Reflect the rename in app info
15836            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15837            pkg.setApplicationInfoCodePath(pkg.codePath);
15838            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15839            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15840            pkg.setApplicationInfoResourcePath(pkg.codePath);
15841            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15842            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15843
15844            return true;
15845        }
15846
15847        private void setMountPath(String mountPath) {
15848            final File mountFile = new File(mountPath);
15849
15850            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15851            if (monolithicFile.exists()) {
15852                packagePath = monolithicFile.getAbsolutePath();
15853                if (isFwdLocked()) {
15854                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15855                } else {
15856                    resourcePath = packagePath;
15857                }
15858            } else {
15859                packagePath = mountFile.getAbsolutePath();
15860                resourcePath = packagePath;
15861            }
15862        }
15863
15864        int doPostInstall(int status, int uid) {
15865            if (status != PackageManager.INSTALL_SUCCEEDED) {
15866                cleanUp();
15867            } else {
15868                final int groupOwner;
15869                final String protectedFile;
15870                if (isFwdLocked()) {
15871                    groupOwner = UserHandle.getSharedAppGid(uid);
15872                    protectedFile = RES_FILE_NAME;
15873                } else {
15874                    groupOwner = -1;
15875                    protectedFile = null;
15876                }
15877
15878                if (uid < Process.FIRST_APPLICATION_UID
15879                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15880                    Slog.e(TAG, "Failed to finalize " + cid);
15881                    PackageHelper.destroySdDir(cid);
15882                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15883                }
15884
15885                boolean mounted = PackageHelper.isContainerMounted(cid);
15886                if (!mounted) {
15887                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15888                }
15889            }
15890            return status;
15891        }
15892
15893        private void cleanUp() {
15894            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15895
15896            // Destroy secure container
15897            PackageHelper.destroySdDir(cid);
15898        }
15899
15900        private List<String> getAllCodePaths() {
15901            final File codeFile = new File(getCodePath());
15902            if (codeFile != null && codeFile.exists()) {
15903                try {
15904                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15905                    return pkg.getAllCodePaths();
15906                } catch (PackageParserException e) {
15907                    // Ignored; we tried our best
15908                }
15909            }
15910            return Collections.EMPTY_LIST;
15911        }
15912
15913        void cleanUpResourcesLI() {
15914            // Enumerate all code paths before deleting
15915            cleanUpResourcesLI(getAllCodePaths());
15916        }
15917
15918        private void cleanUpResourcesLI(List<String> allCodePaths) {
15919            cleanUp();
15920            removeDexFiles(allCodePaths, instructionSets);
15921        }
15922
15923        String getPackageName() {
15924            return getAsecPackageName(cid);
15925        }
15926
15927        boolean doPostDeleteLI(boolean delete) {
15928            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15929            final List<String> allCodePaths = getAllCodePaths();
15930            boolean mounted = PackageHelper.isContainerMounted(cid);
15931            if (mounted) {
15932                // Unmount first
15933                if (PackageHelper.unMountSdDir(cid)) {
15934                    mounted = false;
15935                }
15936            }
15937            if (!mounted && delete) {
15938                cleanUpResourcesLI(allCodePaths);
15939            }
15940            return !mounted;
15941        }
15942
15943        @Override
15944        int doPreCopy() {
15945            if (isFwdLocked()) {
15946                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15947                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15948                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15949                }
15950            }
15951
15952            return PackageManager.INSTALL_SUCCEEDED;
15953        }
15954
15955        @Override
15956        int doPostCopy(int uid) {
15957            if (isFwdLocked()) {
15958                if (uid < Process.FIRST_APPLICATION_UID
15959                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15960                                RES_FILE_NAME)) {
15961                    Slog.e(TAG, "Failed to finalize " + cid);
15962                    PackageHelper.destroySdDir(cid);
15963                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15964                }
15965            }
15966
15967            return PackageManager.INSTALL_SUCCEEDED;
15968        }
15969    }
15970
15971    /**
15972     * Logic to handle movement of existing installed applications.
15973     */
15974    class MoveInstallArgs extends InstallArgs {
15975        private File codeFile;
15976        private File resourceFile;
15977
15978        /** New install */
15979        MoveInstallArgs(InstallParams params) {
15980            super(params.origin, params.move, params.observer, params.installFlags,
15981                    params.installerPackageName, params.volumeUuid,
15982                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15983                    params.grantedRuntimePermissions,
15984                    params.traceMethod, params.traceCookie, params.certificates,
15985                    params.installReason);
15986        }
15987
15988        int copyApk(IMediaContainerService imcs, boolean temp) {
15989            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15990                    + move.fromUuid + " to " + move.toUuid);
15991            synchronized (mInstaller) {
15992                try {
15993                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15994                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15995                } catch (InstallerException e) {
15996                    Slog.w(TAG, "Failed to move app", e);
15997                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15998                }
15999            }
16000
16001            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16002            resourceFile = codeFile;
16003            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16004
16005            return PackageManager.INSTALL_SUCCEEDED;
16006        }
16007
16008        int doPreInstall(int status) {
16009            if (status != PackageManager.INSTALL_SUCCEEDED) {
16010                cleanUp(move.toUuid);
16011            }
16012            return status;
16013        }
16014
16015        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16016            if (status != PackageManager.INSTALL_SUCCEEDED) {
16017                cleanUp(move.toUuid);
16018                return false;
16019            }
16020
16021            // Reflect the move in app info
16022            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16023            pkg.setApplicationInfoCodePath(pkg.codePath);
16024            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16025            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16026            pkg.setApplicationInfoResourcePath(pkg.codePath);
16027            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16028            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16029
16030            return true;
16031        }
16032
16033        int doPostInstall(int status, int uid) {
16034            if (status == PackageManager.INSTALL_SUCCEEDED) {
16035                cleanUp(move.fromUuid);
16036            } else {
16037                cleanUp(move.toUuid);
16038            }
16039            return status;
16040        }
16041
16042        @Override
16043        String getCodePath() {
16044            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16045        }
16046
16047        @Override
16048        String getResourcePath() {
16049            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16050        }
16051
16052        private boolean cleanUp(String volumeUuid) {
16053            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16054                    move.dataAppName);
16055            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16056            final int[] userIds = sUserManager.getUserIds();
16057            synchronized (mInstallLock) {
16058                // Clean up both app data and code
16059                // All package moves are frozen until finished
16060                for (int userId : userIds) {
16061                    try {
16062                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16063                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16064                    } catch (InstallerException e) {
16065                        Slog.w(TAG, String.valueOf(e));
16066                    }
16067                }
16068                removeCodePathLI(codeFile);
16069            }
16070            return true;
16071        }
16072
16073        void cleanUpResourcesLI() {
16074            throw new UnsupportedOperationException();
16075        }
16076
16077        boolean doPostDeleteLI(boolean delete) {
16078            throw new UnsupportedOperationException();
16079        }
16080    }
16081
16082    static String getAsecPackageName(String packageCid) {
16083        int idx = packageCid.lastIndexOf("-");
16084        if (idx == -1) {
16085            return packageCid;
16086        }
16087        return packageCid.substring(0, idx);
16088    }
16089
16090    // Utility method used to create code paths based on package name and available index.
16091    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16092        String idxStr = "";
16093        int idx = 1;
16094        // Fall back to default value of idx=1 if prefix is not
16095        // part of oldCodePath
16096        if (oldCodePath != null) {
16097            String subStr = oldCodePath;
16098            // Drop the suffix right away
16099            if (suffix != null && subStr.endsWith(suffix)) {
16100                subStr = subStr.substring(0, subStr.length() - suffix.length());
16101            }
16102            // If oldCodePath already contains prefix find out the
16103            // ending index to either increment or decrement.
16104            int sidx = subStr.lastIndexOf(prefix);
16105            if (sidx != -1) {
16106                subStr = subStr.substring(sidx + prefix.length());
16107                if (subStr != null) {
16108                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16109                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16110                    }
16111                    try {
16112                        idx = Integer.parseInt(subStr);
16113                        if (idx <= 1) {
16114                            idx++;
16115                        } else {
16116                            idx--;
16117                        }
16118                    } catch(NumberFormatException e) {
16119                    }
16120                }
16121            }
16122        }
16123        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16124        return prefix + idxStr;
16125    }
16126
16127    private File getNextCodePath(File targetDir, String packageName) {
16128        File result;
16129        SecureRandom random = new SecureRandom();
16130        byte[] bytes = new byte[16];
16131        do {
16132            random.nextBytes(bytes);
16133            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16134            result = new File(targetDir, packageName + "-" + suffix);
16135        } while (result.exists());
16136        return result;
16137    }
16138
16139    // Utility method that returns the relative package path with respect
16140    // to the installation directory. Like say for /data/data/com.test-1.apk
16141    // string com.test-1 is returned.
16142    static String deriveCodePathName(String codePath) {
16143        if (codePath == null) {
16144            return null;
16145        }
16146        final File codeFile = new File(codePath);
16147        final String name = codeFile.getName();
16148        if (codeFile.isDirectory()) {
16149            return name;
16150        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16151            final int lastDot = name.lastIndexOf('.');
16152            return name.substring(0, lastDot);
16153        } else {
16154            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16155            return null;
16156        }
16157    }
16158
16159    static class PackageInstalledInfo {
16160        String name;
16161        int uid;
16162        // The set of users that originally had this package installed.
16163        int[] origUsers;
16164        // The set of users that now have this package installed.
16165        int[] newUsers;
16166        PackageParser.Package pkg;
16167        int returnCode;
16168        String returnMsg;
16169        PackageRemovedInfo removedInfo;
16170        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16171
16172        public void setError(int code, String msg) {
16173            setReturnCode(code);
16174            setReturnMessage(msg);
16175            Slog.w(TAG, msg);
16176        }
16177
16178        public void setError(String msg, PackageParserException e) {
16179            setReturnCode(e.error);
16180            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16181            Slog.w(TAG, msg, e);
16182        }
16183
16184        public void setError(String msg, PackageManagerException e) {
16185            returnCode = e.error;
16186            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16187            Slog.w(TAG, msg, e);
16188        }
16189
16190        public void setReturnCode(int returnCode) {
16191            this.returnCode = returnCode;
16192            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16193            for (int i = 0; i < childCount; i++) {
16194                addedChildPackages.valueAt(i).returnCode = returnCode;
16195            }
16196        }
16197
16198        private void setReturnMessage(String returnMsg) {
16199            this.returnMsg = returnMsg;
16200            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16201            for (int i = 0; i < childCount; i++) {
16202                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16203            }
16204        }
16205
16206        // In some error cases we want to convey more info back to the observer
16207        String origPackage;
16208        String origPermission;
16209    }
16210
16211    /*
16212     * Install a non-existing package.
16213     */
16214    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16215            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16216            PackageInstalledInfo res, int installReason) {
16217        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16218
16219        // Remember this for later, in case we need to rollback this install
16220        String pkgName = pkg.packageName;
16221
16222        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16223
16224        synchronized(mPackages) {
16225            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16226            if (renamedPackage != null) {
16227                // A package with the same name is already installed, though
16228                // it has been renamed to an older name.  The package we
16229                // are trying to install should be installed as an update to
16230                // the existing one, but that has not been requested, so bail.
16231                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16232                        + " without first uninstalling package running as "
16233                        + renamedPackage);
16234                return;
16235            }
16236            if (mPackages.containsKey(pkgName)) {
16237                // Don't allow installation over an existing package with the same name.
16238                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16239                        + " without first uninstalling.");
16240                return;
16241            }
16242        }
16243
16244        try {
16245            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16246                    System.currentTimeMillis(), user);
16247
16248            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16249
16250            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16251                prepareAppDataAfterInstallLIF(newPackage);
16252
16253            } else {
16254                // Remove package from internal structures, but keep around any
16255                // data that might have already existed
16256                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16257                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16258            }
16259        } catch (PackageManagerException e) {
16260            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16261        }
16262
16263        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16264    }
16265
16266    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16267        // Can't rotate keys during boot or if sharedUser.
16268        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16269                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16270            return false;
16271        }
16272        // app is using upgradeKeySets; make sure all are valid
16273        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16274        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16275        for (int i = 0; i < upgradeKeySets.length; i++) {
16276            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16277                Slog.wtf(TAG, "Package "
16278                         + (oldPs.name != null ? oldPs.name : "<null>")
16279                         + " contains upgrade-key-set reference to unknown key-set: "
16280                         + upgradeKeySets[i]
16281                         + " reverting to signatures check.");
16282                return false;
16283            }
16284        }
16285        return true;
16286    }
16287
16288    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16289        // Upgrade keysets are being used.  Determine if new package has a superset of the
16290        // required keys.
16291        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16292        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16293        for (int i = 0; i < upgradeKeySets.length; i++) {
16294            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16295            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16296                return true;
16297            }
16298        }
16299        return false;
16300    }
16301
16302    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16303        try (DigestInputStream digestStream =
16304                new DigestInputStream(new FileInputStream(file), digest)) {
16305            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16306        }
16307    }
16308
16309    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16310            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16311            int installReason) {
16312        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16313
16314        final PackageParser.Package oldPackage;
16315        final PackageSetting ps;
16316        final String pkgName = pkg.packageName;
16317        final int[] allUsers;
16318        final int[] installedUsers;
16319
16320        synchronized(mPackages) {
16321            oldPackage = mPackages.get(pkgName);
16322            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16323
16324            // don't allow upgrade to target a release SDK from a pre-release SDK
16325            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16326                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16327            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16328                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16329            if (oldTargetsPreRelease
16330                    && !newTargetsPreRelease
16331                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16332                Slog.w(TAG, "Can't install package targeting released sdk");
16333                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16334                return;
16335            }
16336
16337            ps = mSettings.mPackages.get(pkgName);
16338
16339            // verify signatures are valid
16340            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16341                if (!checkUpgradeKeySetLP(ps, pkg)) {
16342                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16343                            "New package not signed by keys specified by upgrade-keysets: "
16344                                    + pkgName);
16345                    return;
16346                }
16347            } else {
16348                // default to original signature matching
16349                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16350                        != PackageManager.SIGNATURE_MATCH) {
16351                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16352                            "New package has a different signature: " + pkgName);
16353                    return;
16354                }
16355            }
16356
16357            // don't allow a system upgrade unless the upgrade hash matches
16358            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16359                byte[] digestBytes = null;
16360                try {
16361                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16362                    updateDigest(digest, new File(pkg.baseCodePath));
16363                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16364                        for (String path : pkg.splitCodePaths) {
16365                            updateDigest(digest, new File(path));
16366                        }
16367                    }
16368                    digestBytes = digest.digest();
16369                } catch (NoSuchAlgorithmException | IOException e) {
16370                    res.setError(INSTALL_FAILED_INVALID_APK,
16371                            "Could not compute hash: " + pkgName);
16372                    return;
16373                }
16374                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16375                    res.setError(INSTALL_FAILED_INVALID_APK,
16376                            "New package fails restrict-update check: " + pkgName);
16377                    return;
16378                }
16379                // retain upgrade restriction
16380                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16381            }
16382
16383            // Check for shared user id changes
16384            String invalidPackageName =
16385                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16386            if (invalidPackageName != null) {
16387                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16388                        "Package " + invalidPackageName + " tried to change user "
16389                                + oldPackage.mSharedUserId);
16390                return;
16391            }
16392
16393            // In case of rollback, remember per-user/profile install state
16394            allUsers = sUserManager.getUserIds();
16395            installedUsers = ps.queryInstalledUsers(allUsers, true);
16396
16397            // don't allow an upgrade from full to ephemeral
16398            if (isInstantApp) {
16399                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16400                    for (int currentUser : allUsers) {
16401                        if (!ps.getInstantApp(currentUser)) {
16402                            // can't downgrade from full to instant
16403                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16404                                    + " for user: " + currentUser);
16405                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16406                            return;
16407                        }
16408                    }
16409                } else if (!ps.getInstantApp(user.getIdentifier())) {
16410                    // can't downgrade from full to instant
16411                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16412                            + " for user: " + user.getIdentifier());
16413                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16414                    return;
16415                }
16416            }
16417        }
16418
16419        // Update what is removed
16420        res.removedInfo = new PackageRemovedInfo(this);
16421        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16422        res.removedInfo.removedPackage = oldPackage.packageName;
16423        res.removedInfo.installerPackageName = ps.installerPackageName;
16424        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16425        res.removedInfo.isUpdate = true;
16426        res.removedInfo.origUsers = installedUsers;
16427        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16428        for (int i = 0; i < installedUsers.length; i++) {
16429            final int userId = installedUsers[i];
16430            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16431        }
16432
16433        final int childCount = (oldPackage.childPackages != null)
16434                ? oldPackage.childPackages.size() : 0;
16435        for (int i = 0; i < childCount; i++) {
16436            boolean childPackageUpdated = false;
16437            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16438            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16439            if (res.addedChildPackages != null) {
16440                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16441                if (childRes != null) {
16442                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16443                    childRes.removedInfo.removedPackage = childPkg.packageName;
16444                    if (childPs != null) {
16445                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16446                    }
16447                    childRes.removedInfo.isUpdate = true;
16448                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16449                    childPackageUpdated = true;
16450                }
16451            }
16452            if (!childPackageUpdated) {
16453                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16454                childRemovedRes.removedPackage = childPkg.packageName;
16455                if (childPs != null) {
16456                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16457                }
16458                childRemovedRes.isUpdate = false;
16459                childRemovedRes.dataRemoved = true;
16460                synchronized (mPackages) {
16461                    if (childPs != null) {
16462                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16463                    }
16464                }
16465                if (res.removedInfo.removedChildPackages == null) {
16466                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16467                }
16468                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16469            }
16470        }
16471
16472        boolean sysPkg = (isSystemApp(oldPackage));
16473        if (sysPkg) {
16474            // Set the system/privileged flags as needed
16475            final boolean privileged =
16476                    (oldPackage.applicationInfo.privateFlags
16477                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16478            final int systemPolicyFlags = policyFlags
16479                    | PackageParser.PARSE_IS_SYSTEM
16480                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16481
16482            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16483                    user, allUsers, installerPackageName, res, installReason);
16484        } else {
16485            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16486                    user, allUsers, installerPackageName, res, installReason);
16487        }
16488    }
16489
16490    public List<String> getPreviousCodePaths(String packageName) {
16491        final PackageSetting ps = mSettings.mPackages.get(packageName);
16492        final List<String> result = new ArrayList<String>();
16493        if (ps != null && ps.oldCodePaths != null) {
16494            result.addAll(ps.oldCodePaths);
16495        }
16496        return result;
16497    }
16498
16499    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16500            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16501            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16502            int installReason) {
16503        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16504                + deletedPackage);
16505
16506        String pkgName = deletedPackage.packageName;
16507        boolean deletedPkg = true;
16508        boolean addedPkg = false;
16509        boolean updatedSettings = false;
16510        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16511        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16512                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16513
16514        final long origUpdateTime = (pkg.mExtras != null)
16515                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16516
16517        // First delete the existing package while retaining the data directory
16518        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16519                res.removedInfo, true, pkg)) {
16520            // If the existing package wasn't successfully deleted
16521            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16522            deletedPkg = false;
16523        } else {
16524            // Successfully deleted the old package; proceed with replace.
16525
16526            // If deleted package lived in a container, give users a chance to
16527            // relinquish resources before killing.
16528            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16529                if (DEBUG_INSTALL) {
16530                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16531                }
16532                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16533                final ArrayList<String> pkgList = new ArrayList<String>(1);
16534                pkgList.add(deletedPackage.applicationInfo.packageName);
16535                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16536            }
16537
16538            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16539                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16540            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16541
16542            try {
16543                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16544                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16545                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16546                        installReason);
16547
16548                // Update the in-memory copy of the previous code paths.
16549                PackageSetting ps = mSettings.mPackages.get(pkgName);
16550                if (!killApp) {
16551                    if (ps.oldCodePaths == null) {
16552                        ps.oldCodePaths = new ArraySet<>();
16553                    }
16554                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16555                    if (deletedPackage.splitCodePaths != null) {
16556                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16557                    }
16558                } else {
16559                    ps.oldCodePaths = null;
16560                }
16561                if (ps.childPackageNames != null) {
16562                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16563                        final String childPkgName = ps.childPackageNames.get(i);
16564                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16565                        childPs.oldCodePaths = ps.oldCodePaths;
16566                    }
16567                }
16568                // set instant app status, but, only if it's explicitly specified
16569                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16570                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16571                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16572                prepareAppDataAfterInstallLIF(newPackage);
16573                addedPkg = true;
16574                mDexManager.notifyPackageUpdated(newPackage.packageName,
16575                        newPackage.baseCodePath, newPackage.splitCodePaths);
16576            } catch (PackageManagerException e) {
16577                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16578            }
16579        }
16580
16581        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16582            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16583
16584            // Revert all internal state mutations and added folders for the failed install
16585            if (addedPkg) {
16586                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16587                        res.removedInfo, true, null);
16588            }
16589
16590            // Restore the old package
16591            if (deletedPkg) {
16592                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16593                File restoreFile = new File(deletedPackage.codePath);
16594                // Parse old package
16595                boolean oldExternal = isExternal(deletedPackage);
16596                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16597                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16598                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16599                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16600                try {
16601                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16602                            null);
16603                } catch (PackageManagerException e) {
16604                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16605                            + e.getMessage());
16606                    return;
16607                }
16608
16609                synchronized (mPackages) {
16610                    // Ensure the installer package name up to date
16611                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16612
16613                    // Update permissions for restored package
16614                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16615
16616                    mSettings.writeLPr();
16617                }
16618
16619                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16620            }
16621        } else {
16622            synchronized (mPackages) {
16623                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16624                if (ps != null) {
16625                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16626                    if (res.removedInfo.removedChildPackages != null) {
16627                        final int childCount = res.removedInfo.removedChildPackages.size();
16628                        // Iterate in reverse as we may modify the collection
16629                        for (int i = childCount - 1; i >= 0; i--) {
16630                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16631                            if (res.addedChildPackages.containsKey(childPackageName)) {
16632                                res.removedInfo.removedChildPackages.removeAt(i);
16633                            } else {
16634                                PackageRemovedInfo childInfo = res.removedInfo
16635                                        .removedChildPackages.valueAt(i);
16636                                childInfo.removedForAllUsers = mPackages.get(
16637                                        childInfo.removedPackage) == null;
16638                            }
16639                        }
16640                    }
16641                }
16642            }
16643        }
16644    }
16645
16646    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16647            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16648            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16649            int installReason) {
16650        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16651                + ", old=" + deletedPackage);
16652
16653        final boolean disabledSystem;
16654
16655        // Remove existing system package
16656        removePackageLI(deletedPackage, true);
16657
16658        synchronized (mPackages) {
16659            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16660        }
16661        if (!disabledSystem) {
16662            // We didn't need to disable the .apk as a current system package,
16663            // which means we are replacing another update that is already
16664            // installed.  We need to make sure to delete the older one's .apk.
16665            res.removedInfo.args = createInstallArgsForExisting(0,
16666                    deletedPackage.applicationInfo.getCodePath(),
16667                    deletedPackage.applicationInfo.getResourcePath(),
16668                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16669        } else {
16670            res.removedInfo.args = null;
16671        }
16672
16673        // Successfully disabled the old package. Now proceed with re-installation
16674        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16675                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16676        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16677
16678        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16679        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16680                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16681
16682        PackageParser.Package newPackage = null;
16683        try {
16684            // Add the package to the internal data structures
16685            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16686
16687            // Set the update and install times
16688            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16689            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16690                    System.currentTimeMillis());
16691
16692            // Update the package dynamic state if succeeded
16693            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16694                // Now that the install succeeded make sure we remove data
16695                // directories for any child package the update removed.
16696                final int deletedChildCount = (deletedPackage.childPackages != null)
16697                        ? deletedPackage.childPackages.size() : 0;
16698                final int newChildCount = (newPackage.childPackages != null)
16699                        ? newPackage.childPackages.size() : 0;
16700                for (int i = 0; i < deletedChildCount; i++) {
16701                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16702                    boolean childPackageDeleted = true;
16703                    for (int j = 0; j < newChildCount; j++) {
16704                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16705                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16706                            childPackageDeleted = false;
16707                            break;
16708                        }
16709                    }
16710                    if (childPackageDeleted) {
16711                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16712                                deletedChildPkg.packageName);
16713                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16714                            PackageRemovedInfo removedChildRes = res.removedInfo
16715                                    .removedChildPackages.get(deletedChildPkg.packageName);
16716                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16717                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16718                        }
16719                    }
16720                }
16721
16722                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16723                        installReason);
16724                prepareAppDataAfterInstallLIF(newPackage);
16725
16726                mDexManager.notifyPackageUpdated(newPackage.packageName,
16727                            newPackage.baseCodePath, newPackage.splitCodePaths);
16728            }
16729        } catch (PackageManagerException e) {
16730            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16731            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16732        }
16733
16734        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16735            // Re installation failed. Restore old information
16736            // Remove new pkg information
16737            if (newPackage != null) {
16738                removeInstalledPackageLI(newPackage, true);
16739            }
16740            // Add back the old system package
16741            try {
16742                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16743            } catch (PackageManagerException e) {
16744                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16745            }
16746
16747            synchronized (mPackages) {
16748                if (disabledSystem) {
16749                    enableSystemPackageLPw(deletedPackage);
16750                }
16751
16752                // Ensure the installer package name up to date
16753                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16754
16755                // Update permissions for restored package
16756                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16757
16758                mSettings.writeLPr();
16759            }
16760
16761            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16762                    + " after failed upgrade");
16763        }
16764    }
16765
16766    /**
16767     * Checks whether the parent or any of the child packages have a change shared
16768     * user. For a package to be a valid update the shred users of the parent and
16769     * the children should match. We may later support changing child shared users.
16770     * @param oldPkg The updated package.
16771     * @param newPkg The update package.
16772     * @return The shared user that change between the versions.
16773     */
16774    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16775            PackageParser.Package newPkg) {
16776        // Check parent shared user
16777        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16778            return newPkg.packageName;
16779        }
16780        // Check child shared users
16781        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16782        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16783        for (int i = 0; i < newChildCount; i++) {
16784            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16785            // If this child was present, did it have the same shared user?
16786            for (int j = 0; j < oldChildCount; j++) {
16787                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16788                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16789                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16790                    return newChildPkg.packageName;
16791                }
16792            }
16793        }
16794        return null;
16795    }
16796
16797    private void removeNativeBinariesLI(PackageSetting ps) {
16798        // Remove the lib path for the parent package
16799        if (ps != null) {
16800            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16801            // Remove the lib path for the child packages
16802            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16803            for (int i = 0; i < childCount; i++) {
16804                PackageSetting childPs = null;
16805                synchronized (mPackages) {
16806                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16807                }
16808                if (childPs != null) {
16809                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16810                            .legacyNativeLibraryPathString);
16811                }
16812            }
16813        }
16814    }
16815
16816    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16817        // Enable the parent package
16818        mSettings.enableSystemPackageLPw(pkg.packageName);
16819        // Enable the child packages
16820        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16821        for (int i = 0; i < childCount; i++) {
16822            PackageParser.Package childPkg = pkg.childPackages.get(i);
16823            mSettings.enableSystemPackageLPw(childPkg.packageName);
16824        }
16825    }
16826
16827    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16828            PackageParser.Package newPkg) {
16829        // Disable the parent package (parent always replaced)
16830        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16831        // Disable the child packages
16832        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16833        for (int i = 0; i < childCount; i++) {
16834            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16835            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16836            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16837        }
16838        return disabled;
16839    }
16840
16841    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16842            String installerPackageName) {
16843        // Enable the parent package
16844        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16845        // Enable the child packages
16846        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16847        for (int i = 0; i < childCount; i++) {
16848            PackageParser.Package childPkg = pkg.childPackages.get(i);
16849            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16850        }
16851    }
16852
16853    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16854        // Collect all used permissions in the UID
16855        ArraySet<String> usedPermissions = new ArraySet<>();
16856        final int packageCount = su.packages.size();
16857        for (int i = 0; i < packageCount; i++) {
16858            PackageSetting ps = su.packages.valueAt(i);
16859            if (ps.pkg == null) {
16860                continue;
16861            }
16862            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16863            for (int j = 0; j < requestedPermCount; j++) {
16864                String permission = ps.pkg.requestedPermissions.get(j);
16865                BasePermission bp = mSettings.mPermissions.get(permission);
16866                if (bp != null) {
16867                    usedPermissions.add(permission);
16868                }
16869            }
16870        }
16871
16872        PermissionsState permissionsState = su.getPermissionsState();
16873        // Prune install permissions
16874        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16875        final int installPermCount = installPermStates.size();
16876        for (int i = installPermCount - 1; i >= 0;  i--) {
16877            PermissionState permissionState = installPermStates.get(i);
16878            if (!usedPermissions.contains(permissionState.getName())) {
16879                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16880                if (bp != null) {
16881                    permissionsState.revokeInstallPermission(bp);
16882                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16883                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16884                }
16885            }
16886        }
16887
16888        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16889
16890        // Prune runtime permissions
16891        for (int userId : allUserIds) {
16892            List<PermissionState> runtimePermStates = permissionsState
16893                    .getRuntimePermissionStates(userId);
16894            final int runtimePermCount = runtimePermStates.size();
16895            for (int i = runtimePermCount - 1; i >= 0; i--) {
16896                PermissionState permissionState = runtimePermStates.get(i);
16897                if (!usedPermissions.contains(permissionState.getName())) {
16898                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16899                    if (bp != null) {
16900                        permissionsState.revokeRuntimePermission(bp, userId);
16901                        permissionsState.updatePermissionFlags(bp, userId,
16902                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16903                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16904                                runtimePermissionChangedUserIds, userId);
16905                    }
16906                }
16907            }
16908        }
16909
16910        return runtimePermissionChangedUserIds;
16911    }
16912
16913    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16914            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16915        // Update the parent package setting
16916        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16917                res, user, installReason);
16918        // Update the child packages setting
16919        final int childCount = (newPackage.childPackages != null)
16920                ? newPackage.childPackages.size() : 0;
16921        for (int i = 0; i < childCount; i++) {
16922            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16923            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16924            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16925                    childRes.origUsers, childRes, user, installReason);
16926        }
16927    }
16928
16929    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16930            String installerPackageName, int[] allUsers, int[] installedForUsers,
16931            PackageInstalledInfo res, UserHandle user, int installReason) {
16932        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16933
16934        String pkgName = newPackage.packageName;
16935        synchronized (mPackages) {
16936            //write settings. the installStatus will be incomplete at this stage.
16937            //note that the new package setting would have already been
16938            //added to mPackages. It hasn't been persisted yet.
16939            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16940            // TODO: Remove this write? It's also written at the end of this method
16941            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16942            mSettings.writeLPr();
16943            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16944        }
16945
16946        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16947        synchronized (mPackages) {
16948            updatePermissionsLPw(newPackage.packageName, newPackage,
16949                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16950                            ? UPDATE_PERMISSIONS_ALL : 0));
16951            // For system-bundled packages, we assume that installing an upgraded version
16952            // of the package implies that the user actually wants to run that new code,
16953            // so we enable the package.
16954            PackageSetting ps = mSettings.mPackages.get(pkgName);
16955            final int userId = user.getIdentifier();
16956            if (ps != null) {
16957                if (isSystemApp(newPackage)) {
16958                    if (DEBUG_INSTALL) {
16959                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16960                    }
16961                    // Enable system package for requested users
16962                    if (res.origUsers != null) {
16963                        for (int origUserId : res.origUsers) {
16964                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16965                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16966                                        origUserId, installerPackageName);
16967                            }
16968                        }
16969                    }
16970                    // Also convey the prior install/uninstall state
16971                    if (allUsers != null && installedForUsers != null) {
16972                        for (int currentUserId : allUsers) {
16973                            final boolean installed = ArrayUtils.contains(
16974                                    installedForUsers, currentUserId);
16975                            if (DEBUG_INSTALL) {
16976                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16977                            }
16978                            ps.setInstalled(installed, currentUserId);
16979                        }
16980                        // these install state changes will be persisted in the
16981                        // upcoming call to mSettings.writeLPr().
16982                    }
16983                }
16984                // It's implied that when a user requests installation, they want the app to be
16985                // installed and enabled.
16986                if (userId != UserHandle.USER_ALL) {
16987                    ps.setInstalled(true, userId);
16988                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16989                }
16990
16991                // When replacing an existing package, preserve the original install reason for all
16992                // users that had the package installed before.
16993                final Set<Integer> previousUserIds = new ArraySet<>();
16994                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16995                    final int installReasonCount = res.removedInfo.installReasons.size();
16996                    for (int i = 0; i < installReasonCount; i++) {
16997                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16998                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16999                        ps.setInstallReason(previousInstallReason, previousUserId);
17000                        previousUserIds.add(previousUserId);
17001                    }
17002                }
17003
17004                // Set install reason for users that are having the package newly installed.
17005                if (userId == UserHandle.USER_ALL) {
17006                    for (int currentUserId : sUserManager.getUserIds()) {
17007                        if (!previousUserIds.contains(currentUserId)) {
17008                            ps.setInstallReason(installReason, currentUserId);
17009                        }
17010                    }
17011                } else if (!previousUserIds.contains(userId)) {
17012                    ps.setInstallReason(installReason, userId);
17013                }
17014                mSettings.writeKernelMappingLPr(ps);
17015            }
17016            res.name = pkgName;
17017            res.uid = newPackage.applicationInfo.uid;
17018            res.pkg = newPackage;
17019            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17020            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17021            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17022            //to update install status
17023            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17024            mSettings.writeLPr();
17025            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17026        }
17027
17028        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17029    }
17030
17031    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17032        try {
17033            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17034            installPackageLI(args, res);
17035        } finally {
17036            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17037        }
17038    }
17039
17040    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17041        final int installFlags = args.installFlags;
17042        final String installerPackageName = args.installerPackageName;
17043        final String volumeUuid = args.volumeUuid;
17044        final File tmpPackageFile = new File(args.getCodePath());
17045        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17046        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17047                || (args.volumeUuid != null));
17048        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17049        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17050        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17051        boolean replace = false;
17052        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17053        if (args.move != null) {
17054            // moving a complete application; perform an initial scan on the new install location
17055            scanFlags |= SCAN_INITIAL;
17056        }
17057        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17058            scanFlags |= SCAN_DONT_KILL_APP;
17059        }
17060        if (instantApp) {
17061            scanFlags |= SCAN_AS_INSTANT_APP;
17062        }
17063        if (fullApp) {
17064            scanFlags |= SCAN_AS_FULL_APP;
17065        }
17066
17067        // Result object to be returned
17068        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17069
17070        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17071
17072        // Sanity check
17073        if (instantApp && (forwardLocked || onExternal)) {
17074            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17075                    + " external=" + onExternal);
17076            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17077            return;
17078        }
17079
17080        // Retrieve PackageSettings and parse package
17081        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17082                | PackageParser.PARSE_ENFORCE_CODE
17083                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17084                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17085                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17086                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17087        PackageParser pp = new PackageParser();
17088        pp.setSeparateProcesses(mSeparateProcesses);
17089        pp.setDisplayMetrics(mMetrics);
17090        pp.setCallback(mPackageParserCallback);
17091
17092        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17093        final PackageParser.Package pkg;
17094        try {
17095            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17096        } catch (PackageParserException e) {
17097            res.setError("Failed parse during installPackageLI", e);
17098            return;
17099        } finally {
17100            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17101        }
17102
17103        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17104        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17105            Slog.w(TAG, "Instant app package " + pkg.packageName
17106                    + " does not target O, this will be a fatal error.");
17107            // STOPSHIP: Make this a fatal error
17108            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17109        }
17110        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17111            Slog.w(TAG, "Instant app package " + pkg.packageName
17112                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17113            // STOPSHIP: Make this a fatal error
17114            pkg.applicationInfo.targetSandboxVersion = 2;
17115        }
17116
17117        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17118            // Static shared libraries have synthetic package names
17119            renameStaticSharedLibraryPackage(pkg);
17120
17121            // No static shared libs on external storage
17122            if (onExternal) {
17123                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17124                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17125                        "Packages declaring static-shared libs cannot be updated");
17126                return;
17127            }
17128        }
17129
17130        // If we are installing a clustered package add results for the children
17131        if (pkg.childPackages != null) {
17132            synchronized (mPackages) {
17133                final int childCount = pkg.childPackages.size();
17134                for (int i = 0; i < childCount; i++) {
17135                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17136                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17137                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17138                    childRes.pkg = childPkg;
17139                    childRes.name = childPkg.packageName;
17140                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17141                    if (childPs != null) {
17142                        childRes.origUsers = childPs.queryInstalledUsers(
17143                                sUserManager.getUserIds(), true);
17144                    }
17145                    if ((mPackages.containsKey(childPkg.packageName))) {
17146                        childRes.removedInfo = new PackageRemovedInfo(this);
17147                        childRes.removedInfo.removedPackage = childPkg.packageName;
17148                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17149                    }
17150                    if (res.addedChildPackages == null) {
17151                        res.addedChildPackages = new ArrayMap<>();
17152                    }
17153                    res.addedChildPackages.put(childPkg.packageName, childRes);
17154                }
17155            }
17156        }
17157
17158        // If package doesn't declare API override, mark that we have an install
17159        // time CPU ABI override.
17160        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17161            pkg.cpuAbiOverride = args.abiOverride;
17162        }
17163
17164        String pkgName = res.name = pkg.packageName;
17165        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17166            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17167                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17168                return;
17169            }
17170        }
17171
17172        try {
17173            // either use what we've been given or parse directly from the APK
17174            if (args.certificates != null) {
17175                try {
17176                    PackageParser.populateCertificates(pkg, args.certificates);
17177                } catch (PackageParserException e) {
17178                    // there was something wrong with the certificates we were given;
17179                    // try to pull them from the APK
17180                    PackageParser.collectCertificates(pkg, parseFlags);
17181                }
17182            } else {
17183                PackageParser.collectCertificates(pkg, parseFlags);
17184            }
17185        } catch (PackageParserException e) {
17186            res.setError("Failed collect during installPackageLI", e);
17187            return;
17188        }
17189
17190        // Get rid of all references to package scan path via parser.
17191        pp = null;
17192        String oldCodePath = null;
17193        boolean systemApp = false;
17194        synchronized (mPackages) {
17195            // Check if installing already existing package
17196            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17197                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17198                if (pkg.mOriginalPackages != null
17199                        && pkg.mOriginalPackages.contains(oldName)
17200                        && mPackages.containsKey(oldName)) {
17201                    // This package is derived from an original package,
17202                    // and this device has been updating from that original
17203                    // name.  We must continue using the original name, so
17204                    // rename the new package here.
17205                    pkg.setPackageName(oldName);
17206                    pkgName = pkg.packageName;
17207                    replace = true;
17208                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17209                            + oldName + " pkgName=" + pkgName);
17210                } else if (mPackages.containsKey(pkgName)) {
17211                    // This package, under its official name, already exists
17212                    // on the device; we should replace it.
17213                    replace = true;
17214                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17215                }
17216
17217                // Child packages are installed through the parent package
17218                if (pkg.parentPackage != null) {
17219                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17220                            "Package " + pkg.packageName + " is child of package "
17221                                    + pkg.parentPackage.parentPackage + ". Child packages "
17222                                    + "can be updated only through the parent package.");
17223                    return;
17224                }
17225
17226                if (replace) {
17227                    // Prevent apps opting out from runtime permissions
17228                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17229                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17230                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17231                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17232                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17233                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17234                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17235                                        + " doesn't support runtime permissions but the old"
17236                                        + " target SDK " + oldTargetSdk + " does.");
17237                        return;
17238                    }
17239                    // Prevent apps from downgrading their targetSandbox.
17240                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17241                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17242                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17243                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17244                                "Package " + pkg.packageName + " new target sandbox "
17245                                + newTargetSandbox + " is incompatible with the previous value of"
17246                                + oldTargetSandbox + ".");
17247                        return;
17248                    }
17249
17250                    // Prevent installing of child packages
17251                    if (oldPackage.parentPackage != null) {
17252                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17253                                "Package " + pkg.packageName + " is child of package "
17254                                        + oldPackage.parentPackage + ". Child packages "
17255                                        + "can be updated only through the parent package.");
17256                        return;
17257                    }
17258                }
17259            }
17260
17261            PackageSetting ps = mSettings.mPackages.get(pkgName);
17262            if (ps != null) {
17263                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17264
17265                // Static shared libs have same package with different versions where
17266                // we internally use a synthetic package name to allow multiple versions
17267                // of the same package, therefore we need to compare signatures against
17268                // the package setting for the latest library version.
17269                PackageSetting signatureCheckPs = ps;
17270                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17271                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17272                    if (libraryEntry != null) {
17273                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17274                    }
17275                }
17276
17277                // Quick sanity check that we're signed correctly if updating;
17278                // we'll check this again later when scanning, but we want to
17279                // bail early here before tripping over redefined permissions.
17280                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17281                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17282                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17283                                + pkg.packageName + " upgrade keys do not match the "
17284                                + "previously installed version");
17285                        return;
17286                    }
17287                } else {
17288                    try {
17289                        verifySignaturesLP(signatureCheckPs, pkg);
17290                    } catch (PackageManagerException e) {
17291                        res.setError(e.error, e.getMessage());
17292                        return;
17293                    }
17294                }
17295
17296                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17297                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17298                    systemApp = (ps.pkg.applicationInfo.flags &
17299                            ApplicationInfo.FLAG_SYSTEM) != 0;
17300                }
17301                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17302            }
17303
17304            int N = pkg.permissions.size();
17305            for (int i = N-1; i >= 0; i--) {
17306                PackageParser.Permission perm = pkg.permissions.get(i);
17307                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17308
17309                // Don't allow anyone but the system to define ephemeral permissions.
17310                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17311                        && !systemApp) {
17312                    Slog.w(TAG, "Non-System package " + pkg.packageName
17313                            + " attempting to delcare ephemeral permission "
17314                            + perm.info.name + "; Removing ephemeral.");
17315                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17316                }
17317                // Check whether the newly-scanned package wants to define an already-defined perm
17318                if (bp != null) {
17319                    // If the defining package is signed with our cert, it's okay.  This
17320                    // also includes the "updating the same package" case, of course.
17321                    // "updating same package" could also involve key-rotation.
17322                    final boolean sigsOk;
17323                    if (bp.sourcePackage.equals(pkg.packageName)
17324                            && (bp.packageSetting instanceof PackageSetting)
17325                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17326                                    scanFlags))) {
17327                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17328                    } else {
17329                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17330                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17331                    }
17332                    if (!sigsOk) {
17333                        // If the owning package is the system itself, we log but allow
17334                        // install to proceed; we fail the install on all other permission
17335                        // redefinitions.
17336                        if (!bp.sourcePackage.equals("android")) {
17337                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17338                                    + pkg.packageName + " attempting to redeclare permission "
17339                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17340                            res.origPermission = perm.info.name;
17341                            res.origPackage = bp.sourcePackage;
17342                            return;
17343                        } else {
17344                            Slog.w(TAG, "Package " + pkg.packageName
17345                                    + " attempting to redeclare system permission "
17346                                    + perm.info.name + "; ignoring new declaration");
17347                            pkg.permissions.remove(i);
17348                        }
17349                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17350                        // Prevent apps to change protection level to dangerous from any other
17351                        // type as this would allow a privilege escalation where an app adds a
17352                        // normal/signature permission in other app's group and later redefines
17353                        // it as dangerous leading to the group auto-grant.
17354                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17355                                == PermissionInfo.PROTECTION_DANGEROUS) {
17356                            if (bp != null && !bp.isRuntime()) {
17357                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17358                                        + "non-runtime permission " + perm.info.name
17359                                        + " to runtime; keeping old protection level");
17360                                perm.info.protectionLevel = bp.protectionLevel;
17361                            }
17362                        }
17363                    }
17364                }
17365            }
17366        }
17367
17368        if (systemApp) {
17369            if (onExternal) {
17370                // Abort update; system app can't be replaced with app on sdcard
17371                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17372                        "Cannot install updates to system apps on sdcard");
17373                return;
17374            } else if (instantApp) {
17375                // Abort update; system app can't be replaced with an instant app
17376                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17377                        "Cannot update a system app with an instant app");
17378                return;
17379            }
17380        }
17381
17382        if (args.move != null) {
17383            // We did an in-place move, so dex is ready to roll
17384            scanFlags |= SCAN_NO_DEX;
17385            scanFlags |= SCAN_MOVE;
17386
17387            synchronized (mPackages) {
17388                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17389                if (ps == null) {
17390                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17391                            "Missing settings for moved package " + pkgName);
17392                }
17393
17394                // We moved the entire application as-is, so bring over the
17395                // previously derived ABI information.
17396                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17397                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17398            }
17399
17400        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17401            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17402            scanFlags |= SCAN_NO_DEX;
17403
17404            try {
17405                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17406                    args.abiOverride : pkg.cpuAbiOverride);
17407                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17408                        true /*extractLibs*/, mAppLib32InstallDir);
17409            } catch (PackageManagerException pme) {
17410                Slog.e(TAG, "Error deriving application ABI", pme);
17411                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17412                return;
17413            }
17414
17415            // Shared libraries for the package need to be updated.
17416            synchronized (mPackages) {
17417                try {
17418                    updateSharedLibrariesLPr(pkg, null);
17419                } catch (PackageManagerException e) {
17420                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17421                }
17422            }
17423
17424            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17425            // Do not run PackageDexOptimizer through the local performDexOpt
17426            // method because `pkg` may not be in `mPackages` yet.
17427            //
17428            // Also, don't fail application installs if the dexopt step fails.
17429            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17430                    null /* instructionSets */, false /* checkProfiles */,
17431                    getCompilerFilterForReason(REASON_INSTALL),
17432                    getOrCreateCompilerPackageStats(pkg),
17433                    mDexManager.isUsedByOtherApps(pkg.packageName));
17434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17435
17436            // Notify BackgroundDexOptService that the package has been changed.
17437            // If this is an update of a package which used to fail to compile,
17438            // BDOS will remove it from its blacklist.
17439            // TODO: Layering violation
17440            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17441        }
17442
17443        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17444            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17445            return;
17446        }
17447
17448        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17449
17450        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17451                "installPackageLI")) {
17452            if (replace) {
17453                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17454                    // Static libs have a synthetic package name containing the version
17455                    // and cannot be updated as an update would get a new package name,
17456                    // unless this is the exact same version code which is useful for
17457                    // development.
17458                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17459                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17460                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17461                                + "static-shared libs cannot be updated");
17462                        return;
17463                    }
17464                }
17465                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17466                        installerPackageName, res, args.installReason);
17467            } else {
17468                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17469                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17470            }
17471        }
17472
17473        synchronized (mPackages) {
17474            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17475            if (ps != null) {
17476                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17477                ps.setUpdateAvailable(false /*updateAvailable*/);
17478            }
17479
17480            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17481            for (int i = 0; i < childCount; i++) {
17482                PackageParser.Package childPkg = pkg.childPackages.get(i);
17483                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17484                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17485                if (childPs != null) {
17486                    childRes.newUsers = childPs.queryInstalledUsers(
17487                            sUserManager.getUserIds(), true);
17488                }
17489            }
17490
17491            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17492                updateSequenceNumberLP(pkgName, res.newUsers);
17493                updateInstantAppInstallerLocked(pkgName);
17494            }
17495        }
17496    }
17497
17498    private void startIntentFilterVerifications(int userId, boolean replacing,
17499            PackageParser.Package pkg) {
17500        if (mIntentFilterVerifierComponent == null) {
17501            Slog.w(TAG, "No IntentFilter verification will not be done as "
17502                    + "there is no IntentFilterVerifier available!");
17503            return;
17504        }
17505
17506        final int verifierUid = getPackageUid(
17507                mIntentFilterVerifierComponent.getPackageName(),
17508                MATCH_DEBUG_TRIAGED_MISSING,
17509                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17510
17511        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17512        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17513        mHandler.sendMessage(msg);
17514
17515        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17516        for (int i = 0; i < childCount; i++) {
17517            PackageParser.Package childPkg = pkg.childPackages.get(i);
17518            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17519            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17520            mHandler.sendMessage(msg);
17521        }
17522    }
17523
17524    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17525            PackageParser.Package pkg) {
17526        int size = pkg.activities.size();
17527        if (size == 0) {
17528            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17529                    "No activity, so no need to verify any IntentFilter!");
17530            return;
17531        }
17532
17533        final boolean hasDomainURLs = hasDomainURLs(pkg);
17534        if (!hasDomainURLs) {
17535            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17536                    "No domain URLs, so no need to verify any IntentFilter!");
17537            return;
17538        }
17539
17540        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17541                + " if any IntentFilter from the " + size
17542                + " Activities needs verification ...");
17543
17544        int count = 0;
17545        final String packageName = pkg.packageName;
17546
17547        synchronized (mPackages) {
17548            // If this is a new install and we see that we've already run verification for this
17549            // package, we have nothing to do: it means the state was restored from backup.
17550            if (!replacing) {
17551                IntentFilterVerificationInfo ivi =
17552                        mSettings.getIntentFilterVerificationLPr(packageName);
17553                if (ivi != null) {
17554                    if (DEBUG_DOMAIN_VERIFICATION) {
17555                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17556                                + ivi.getStatusString());
17557                    }
17558                    return;
17559                }
17560            }
17561
17562            // If any filters need to be verified, then all need to be.
17563            boolean needToVerify = false;
17564            for (PackageParser.Activity a : pkg.activities) {
17565                for (ActivityIntentInfo filter : a.intents) {
17566                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17567                        if (DEBUG_DOMAIN_VERIFICATION) {
17568                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17569                        }
17570                        needToVerify = true;
17571                        break;
17572                    }
17573                }
17574            }
17575
17576            if (needToVerify) {
17577                final int verificationId = mIntentFilterVerificationToken++;
17578                for (PackageParser.Activity a : pkg.activities) {
17579                    for (ActivityIntentInfo filter : a.intents) {
17580                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17581                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17582                                    "Verification needed for IntentFilter:" + filter.toString());
17583                            mIntentFilterVerifier.addOneIntentFilterVerification(
17584                                    verifierUid, userId, verificationId, filter, packageName);
17585                            count++;
17586                        }
17587                    }
17588                }
17589            }
17590        }
17591
17592        if (count > 0) {
17593            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17594                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17595                    +  " for userId:" + userId);
17596            mIntentFilterVerifier.startVerifications(userId);
17597        } else {
17598            if (DEBUG_DOMAIN_VERIFICATION) {
17599                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17600            }
17601        }
17602    }
17603
17604    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17605        final ComponentName cn  = filter.activity.getComponentName();
17606        final String packageName = cn.getPackageName();
17607
17608        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17609                packageName);
17610        if (ivi == null) {
17611            return true;
17612        }
17613        int status = ivi.getStatus();
17614        switch (status) {
17615            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17616            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17617                return true;
17618
17619            default:
17620                // Nothing to do
17621                return false;
17622        }
17623    }
17624
17625    private static boolean isMultiArch(ApplicationInfo info) {
17626        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17627    }
17628
17629    private static boolean isExternal(PackageParser.Package pkg) {
17630        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17631    }
17632
17633    private static boolean isExternal(PackageSetting ps) {
17634        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17635    }
17636
17637    private static boolean isSystemApp(PackageParser.Package pkg) {
17638        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17639    }
17640
17641    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17642        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17643    }
17644
17645    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17646        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17647    }
17648
17649    private static boolean isSystemApp(PackageSetting ps) {
17650        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17651    }
17652
17653    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17654        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17655    }
17656
17657    private int packageFlagsToInstallFlags(PackageSetting ps) {
17658        int installFlags = 0;
17659        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17660            // This existing package was an external ASEC install when we have
17661            // the external flag without a UUID
17662            installFlags |= PackageManager.INSTALL_EXTERNAL;
17663        }
17664        if (ps.isForwardLocked()) {
17665            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17666        }
17667        return installFlags;
17668    }
17669
17670    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17671        if (isExternal(pkg)) {
17672            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17673                return StorageManager.UUID_PRIMARY_PHYSICAL;
17674            } else {
17675                return pkg.volumeUuid;
17676            }
17677        } else {
17678            return StorageManager.UUID_PRIVATE_INTERNAL;
17679        }
17680    }
17681
17682    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17683        if (isExternal(pkg)) {
17684            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17685                return mSettings.getExternalVersion();
17686            } else {
17687                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17688            }
17689        } else {
17690            return mSettings.getInternalVersion();
17691        }
17692    }
17693
17694    private void deleteTempPackageFiles() {
17695        final FilenameFilter filter = new FilenameFilter() {
17696            public boolean accept(File dir, String name) {
17697                return name.startsWith("vmdl") && name.endsWith(".tmp");
17698            }
17699        };
17700        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17701            file.delete();
17702        }
17703    }
17704
17705    @Override
17706    public void deletePackageAsUser(String packageName, int versionCode,
17707            IPackageDeleteObserver observer, int userId, int flags) {
17708        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17709                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17710    }
17711
17712    @Override
17713    public void deletePackageVersioned(VersionedPackage versionedPackage,
17714            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17715        mContext.enforceCallingOrSelfPermission(
17716                android.Manifest.permission.DELETE_PACKAGES, null);
17717        Preconditions.checkNotNull(versionedPackage);
17718        Preconditions.checkNotNull(observer);
17719        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17720                PackageManager.VERSION_CODE_HIGHEST,
17721                Integer.MAX_VALUE, "versionCode must be >= -1");
17722
17723        final String packageName = versionedPackage.getPackageName();
17724        final int versionCode = versionedPackage.getVersionCode();
17725        final String internalPackageName;
17726        synchronized (mPackages) {
17727            // Normalize package name to handle renamed packages and static libs
17728            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17729                    versionedPackage.getVersionCode());
17730        }
17731
17732        final int uid = Binder.getCallingUid();
17733        if (!isOrphaned(internalPackageName)
17734                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17735            try {
17736                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17737                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17738                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17739                observer.onUserActionRequired(intent);
17740            } catch (RemoteException re) {
17741            }
17742            return;
17743        }
17744        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17745        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17746        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17747            mContext.enforceCallingOrSelfPermission(
17748                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17749                    "deletePackage for user " + userId);
17750        }
17751
17752        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17753            try {
17754                observer.onPackageDeleted(packageName,
17755                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17756            } catch (RemoteException re) {
17757            }
17758            return;
17759        }
17760
17761        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17762            try {
17763                observer.onPackageDeleted(packageName,
17764                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17765            } catch (RemoteException re) {
17766            }
17767            return;
17768        }
17769
17770        if (DEBUG_REMOVE) {
17771            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17772                    + " deleteAllUsers: " + deleteAllUsers + " version="
17773                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17774                    ? "VERSION_CODE_HIGHEST" : versionCode));
17775        }
17776        // Queue up an async operation since the package deletion may take a little while.
17777        mHandler.post(new Runnable() {
17778            public void run() {
17779                mHandler.removeCallbacks(this);
17780                int returnCode;
17781                if (!deleteAllUsers) {
17782                    returnCode = deletePackageX(internalPackageName, versionCode,
17783                            userId, deleteFlags);
17784                } else {
17785                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17786                            internalPackageName, users);
17787                    // If nobody is blocking uninstall, proceed with delete for all users
17788                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17789                        returnCode = deletePackageX(internalPackageName, versionCode,
17790                                userId, deleteFlags);
17791                    } else {
17792                        // Otherwise uninstall individually for users with blockUninstalls=false
17793                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17794                        for (int userId : users) {
17795                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17796                                returnCode = deletePackageX(internalPackageName, versionCode,
17797                                        userId, userFlags);
17798                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17799                                    Slog.w(TAG, "Package delete failed for user " + userId
17800                                            + ", returnCode " + returnCode);
17801                                }
17802                            }
17803                        }
17804                        // The app has only been marked uninstalled for certain users.
17805                        // We still need to report that delete was blocked
17806                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17807                    }
17808                }
17809                try {
17810                    observer.onPackageDeleted(packageName, returnCode, null);
17811                } catch (RemoteException e) {
17812                    Log.i(TAG, "Observer no longer exists.");
17813                } //end catch
17814            } //end run
17815        });
17816    }
17817
17818    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17819        if (pkg.staticSharedLibName != null) {
17820            return pkg.manifestPackageName;
17821        }
17822        return pkg.packageName;
17823    }
17824
17825    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17826        // Handle renamed packages
17827        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17828        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17829
17830        // Is this a static library?
17831        SparseArray<SharedLibraryEntry> versionedLib =
17832                mStaticLibsByDeclaringPackage.get(packageName);
17833        if (versionedLib == null || versionedLib.size() <= 0) {
17834            return packageName;
17835        }
17836
17837        // Figure out which lib versions the caller can see
17838        SparseIntArray versionsCallerCanSee = null;
17839        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17840        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17841                && callingAppId != Process.ROOT_UID) {
17842            versionsCallerCanSee = new SparseIntArray();
17843            String libName = versionedLib.valueAt(0).info.getName();
17844            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17845            if (uidPackages != null) {
17846                for (String uidPackage : uidPackages) {
17847                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17848                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17849                    if (libIdx >= 0) {
17850                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17851                        versionsCallerCanSee.append(libVersion, libVersion);
17852                    }
17853                }
17854            }
17855        }
17856
17857        // Caller can see nothing - done
17858        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17859            return packageName;
17860        }
17861
17862        // Find the version the caller can see and the app version code
17863        SharedLibraryEntry highestVersion = null;
17864        final int versionCount = versionedLib.size();
17865        for (int i = 0; i < versionCount; i++) {
17866            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17867            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17868                    libEntry.info.getVersion()) < 0) {
17869                continue;
17870            }
17871            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
17872            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17873                if (libVersionCode == versionCode) {
17874                    return libEntry.apk;
17875                }
17876            } else if (highestVersion == null) {
17877                highestVersion = libEntry;
17878            } else if (libVersionCode  > highestVersion.info
17879                    .getDeclaringPackage().getVersionCode()) {
17880                highestVersion = libEntry;
17881            }
17882        }
17883
17884        if (highestVersion != null) {
17885            return highestVersion.apk;
17886        }
17887
17888        return packageName;
17889    }
17890
17891    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17892        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17893              || callingUid == Process.SYSTEM_UID) {
17894            return true;
17895        }
17896        final int callingUserId = UserHandle.getUserId(callingUid);
17897        // If the caller installed the pkgName, then allow it to silently uninstall.
17898        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17899            return true;
17900        }
17901
17902        // Allow package verifier to silently uninstall.
17903        if (mRequiredVerifierPackage != null &&
17904                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17905            return true;
17906        }
17907
17908        // Allow package uninstaller to silently uninstall.
17909        if (mRequiredUninstallerPackage != null &&
17910                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17911            return true;
17912        }
17913
17914        // Allow storage manager to silently uninstall.
17915        if (mStorageManagerPackage != null &&
17916                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17917            return true;
17918        }
17919        return false;
17920    }
17921
17922    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17923        int[] result = EMPTY_INT_ARRAY;
17924        for (int userId : userIds) {
17925            if (getBlockUninstallForUser(packageName, userId)) {
17926                result = ArrayUtils.appendInt(result, userId);
17927            }
17928        }
17929        return result;
17930    }
17931
17932    @Override
17933    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17934        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17935    }
17936
17937    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17938        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17939                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17940        try {
17941            if (dpm != null) {
17942                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17943                        /* callingUserOnly =*/ false);
17944                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17945                        : deviceOwnerComponentName.getPackageName();
17946                // Does the package contains the device owner?
17947                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17948                // this check is probably not needed, since DO should be registered as a device
17949                // admin on some user too. (Original bug for this: b/17657954)
17950                if (packageName.equals(deviceOwnerPackageName)) {
17951                    return true;
17952                }
17953                // Does it contain a device admin for any user?
17954                int[] users;
17955                if (userId == UserHandle.USER_ALL) {
17956                    users = sUserManager.getUserIds();
17957                } else {
17958                    users = new int[]{userId};
17959                }
17960                for (int i = 0; i < users.length; ++i) {
17961                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17962                        return true;
17963                    }
17964                }
17965            }
17966        } catch (RemoteException e) {
17967        }
17968        return false;
17969    }
17970
17971    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17972        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17973    }
17974
17975    /**
17976     *  This method is an internal method that could be get invoked either
17977     *  to delete an installed package or to clean up a failed installation.
17978     *  After deleting an installed package, a broadcast is sent to notify any
17979     *  listeners that the package has been removed. For cleaning up a failed
17980     *  installation, the broadcast is not necessary since the package's
17981     *  installation wouldn't have sent the initial broadcast either
17982     *  The key steps in deleting a package are
17983     *  deleting the package information in internal structures like mPackages,
17984     *  deleting the packages base directories through installd
17985     *  updating mSettings to reflect current status
17986     *  persisting settings for later use
17987     *  sending a broadcast if necessary
17988     */
17989    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17990        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17991        final boolean res;
17992
17993        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17994                ? UserHandle.USER_ALL : userId;
17995
17996        if (isPackageDeviceAdmin(packageName, removeUser)) {
17997            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17998            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17999        }
18000
18001        PackageSetting uninstalledPs = null;
18002        PackageParser.Package pkg = null;
18003
18004        // for the uninstall-updates case and restricted profiles, remember the per-
18005        // user handle installed state
18006        int[] allUsers;
18007        synchronized (mPackages) {
18008            uninstalledPs = mSettings.mPackages.get(packageName);
18009            if (uninstalledPs == null) {
18010                Slog.w(TAG, "Not removing non-existent package " + packageName);
18011                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18012            }
18013
18014            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18015                    && uninstalledPs.versionCode != versionCode) {
18016                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18017                        + uninstalledPs.versionCode + " != " + versionCode);
18018                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18019            }
18020
18021            // Static shared libs can be declared by any package, so let us not
18022            // allow removing a package if it provides a lib others depend on.
18023            pkg = mPackages.get(packageName);
18024
18025            allUsers = sUserManager.getUserIds();
18026
18027            if (pkg != null && pkg.staticSharedLibName != null) {
18028                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18029                        pkg.staticSharedLibVersion);
18030                if (libEntry != null) {
18031                    for (int currUserId : allUsers) {
18032                        if (userId != UserHandle.USER_ALL && userId != currUserId) {
18033                            continue;
18034                        }
18035                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18036                                libEntry.info, 0, currUserId);
18037                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18038                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18039                                    + " hosting lib " + libEntry.info.getName() + " version "
18040                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18041                                    + " for user " + currUserId);
18042                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18043                        }
18044                    }
18045                }
18046            }
18047
18048            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18049        }
18050
18051        final int freezeUser;
18052        if (isUpdatedSystemApp(uninstalledPs)
18053                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18054            // We're downgrading a system app, which will apply to all users, so
18055            // freeze them all during the downgrade
18056            freezeUser = UserHandle.USER_ALL;
18057        } else {
18058            freezeUser = removeUser;
18059        }
18060
18061        synchronized (mInstallLock) {
18062            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18063            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18064                    deleteFlags, "deletePackageX")) {
18065                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18066                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18067            }
18068            synchronized (mPackages) {
18069                if (res) {
18070                    if (pkg != null) {
18071                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18072                    }
18073                    updateSequenceNumberLP(packageName, info.removedUsers);
18074                    updateInstantAppInstallerLocked(packageName);
18075                }
18076            }
18077        }
18078
18079        if (res) {
18080            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18081            info.sendPackageRemovedBroadcasts(killApp);
18082            info.sendSystemPackageUpdatedBroadcasts();
18083            info.sendSystemPackageAppearedBroadcasts();
18084        }
18085        // Force a gc here.
18086        Runtime.getRuntime().gc();
18087        // Delete the resources here after sending the broadcast to let
18088        // other processes clean up before deleting resources.
18089        if (info.args != null) {
18090            synchronized (mInstallLock) {
18091                info.args.doPostDeleteLI(true);
18092            }
18093        }
18094
18095        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18096    }
18097
18098    static class PackageRemovedInfo {
18099        final PackageSender packageSender;
18100        String removedPackage;
18101        String installerPackageName;
18102        int uid = -1;
18103        int removedAppId = -1;
18104        int[] origUsers;
18105        int[] removedUsers = null;
18106        int[] broadcastUsers = null;
18107        SparseArray<Integer> installReasons;
18108        boolean isRemovedPackageSystemUpdate = false;
18109        boolean isUpdate;
18110        boolean dataRemoved;
18111        boolean removedForAllUsers;
18112        boolean isStaticSharedLib;
18113        // Clean up resources deleted packages.
18114        InstallArgs args = null;
18115        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18116        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18117
18118        PackageRemovedInfo(PackageSender packageSender) {
18119            this.packageSender = packageSender;
18120        }
18121
18122        void sendPackageRemovedBroadcasts(boolean killApp) {
18123            sendPackageRemovedBroadcastInternal(killApp);
18124            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18125            for (int i = 0; i < childCount; i++) {
18126                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18127                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18128            }
18129        }
18130
18131        void sendSystemPackageUpdatedBroadcasts() {
18132            if (isRemovedPackageSystemUpdate) {
18133                sendSystemPackageUpdatedBroadcastsInternal();
18134                final int childCount = (removedChildPackages != null)
18135                        ? removedChildPackages.size() : 0;
18136                for (int i = 0; i < childCount; i++) {
18137                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18138                    if (childInfo.isRemovedPackageSystemUpdate) {
18139                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18140                    }
18141                }
18142            }
18143        }
18144
18145        void sendSystemPackageAppearedBroadcasts() {
18146            final int packageCount = (appearedChildPackages != null)
18147                    ? appearedChildPackages.size() : 0;
18148            for (int i = 0; i < packageCount; i++) {
18149                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18150                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18151                    true, UserHandle.getAppId(installedInfo.uid),
18152                    installedInfo.newUsers);
18153            }
18154        }
18155
18156        private void sendSystemPackageUpdatedBroadcastsInternal() {
18157            Bundle extras = new Bundle(2);
18158            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18159            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18160            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18161                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18162            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18163                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18164            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18165                null, null, 0, removedPackage, null, null);
18166            if (installerPackageName != null) {
18167                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18168                        removedPackage, extras, 0 /*flags*/,
18169                        installerPackageName, null, null);
18170                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18171                        removedPackage, extras, 0 /*flags*/,
18172                        installerPackageName, null, null);
18173            }
18174        }
18175
18176        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18177            // Don't send static shared library removal broadcasts as these
18178            // libs are visible only the the apps that depend on them an one
18179            // cannot remove the library if it has a dependency.
18180            if (isStaticSharedLib) {
18181                return;
18182            }
18183            Bundle extras = new Bundle(2);
18184            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18185            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18186            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18187            if (isUpdate || isRemovedPackageSystemUpdate) {
18188                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18189            }
18190            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18191            if (removedPackage != null) {
18192                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18193                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18194                if (installerPackageName != null) {
18195                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18196                            removedPackage, extras, 0 /*flags*/,
18197                            installerPackageName, null, broadcastUsers);
18198                }
18199                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18200                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18201                        removedPackage, extras,
18202                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18203                        null, null, broadcastUsers);
18204                }
18205            }
18206            if (removedAppId >= 0) {
18207                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18208                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18209            }
18210        }
18211
18212        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18213            removedUsers = userIds;
18214            if (removedUsers == null) {
18215                broadcastUsers = null;
18216                return;
18217            }
18218
18219            broadcastUsers = EMPTY_INT_ARRAY;
18220            for (int i = userIds.length - 1; i >= 0; --i) {
18221                final int userId = userIds[i];
18222                if (deletedPackageSetting.getInstantApp(userId)) {
18223                    continue;
18224                }
18225                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18226            }
18227        }
18228    }
18229
18230    /*
18231     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18232     * flag is not set, the data directory is removed as well.
18233     * make sure this flag is set for partially installed apps. If not its meaningless to
18234     * delete a partially installed application.
18235     */
18236    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18237            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18238        String packageName = ps.name;
18239        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18240        // Retrieve object to delete permissions for shared user later on
18241        final PackageParser.Package deletedPkg;
18242        final PackageSetting deletedPs;
18243        // reader
18244        synchronized (mPackages) {
18245            deletedPkg = mPackages.get(packageName);
18246            deletedPs = mSettings.mPackages.get(packageName);
18247            if (outInfo != null) {
18248                outInfo.removedPackage = packageName;
18249                outInfo.installerPackageName = ps.installerPackageName;
18250                outInfo.isStaticSharedLib = deletedPkg != null
18251                        && deletedPkg.staticSharedLibName != null;
18252                outInfo.populateUsers(deletedPs == null ? null
18253                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18254            }
18255        }
18256
18257        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18258
18259        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18260            final PackageParser.Package resolvedPkg;
18261            if (deletedPkg != null) {
18262                resolvedPkg = deletedPkg;
18263            } else {
18264                // We don't have a parsed package when it lives on an ejected
18265                // adopted storage device, so fake something together
18266                resolvedPkg = new PackageParser.Package(ps.name);
18267                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18268            }
18269            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18270                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18271            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18272            if (outInfo != null) {
18273                outInfo.dataRemoved = true;
18274            }
18275            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18276        }
18277
18278        int removedAppId = -1;
18279
18280        // writer
18281        synchronized (mPackages) {
18282            boolean installedStateChanged = false;
18283            if (deletedPs != null) {
18284                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18285                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18286                    clearDefaultBrowserIfNeeded(packageName);
18287                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18288                    removedAppId = mSettings.removePackageLPw(packageName);
18289                    if (outInfo != null) {
18290                        outInfo.removedAppId = removedAppId;
18291                    }
18292                    updatePermissionsLPw(deletedPs.name, null, 0);
18293                    if (deletedPs.sharedUser != null) {
18294                        // Remove permissions associated with package. Since runtime
18295                        // permissions are per user we have to kill the removed package
18296                        // or packages running under the shared user of the removed
18297                        // package if revoking the permissions requested only by the removed
18298                        // package is successful and this causes a change in gids.
18299                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18300                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18301                                    userId);
18302                            if (userIdToKill == UserHandle.USER_ALL
18303                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18304                                // If gids changed for this user, kill all affected packages.
18305                                mHandler.post(new Runnable() {
18306                                    @Override
18307                                    public void run() {
18308                                        // This has to happen with no lock held.
18309                                        killApplication(deletedPs.name, deletedPs.appId,
18310                                                KILL_APP_REASON_GIDS_CHANGED);
18311                                    }
18312                                });
18313                                break;
18314                            }
18315                        }
18316                    }
18317                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18318                }
18319                // make sure to preserve per-user disabled state if this removal was just
18320                // a downgrade of a system app to the factory package
18321                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18322                    if (DEBUG_REMOVE) {
18323                        Slog.d(TAG, "Propagating install state across downgrade");
18324                    }
18325                    for (int userId : allUserHandles) {
18326                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18327                        if (DEBUG_REMOVE) {
18328                            Slog.d(TAG, "    user " + userId + " => " + installed);
18329                        }
18330                        if (installed != ps.getInstalled(userId)) {
18331                            installedStateChanged = true;
18332                        }
18333                        ps.setInstalled(installed, userId);
18334                    }
18335                }
18336            }
18337            // can downgrade to reader
18338            if (writeSettings) {
18339                // Save settings now
18340                mSettings.writeLPr();
18341            }
18342            if (installedStateChanged) {
18343                mSettings.writeKernelMappingLPr(ps);
18344            }
18345        }
18346        if (removedAppId != -1) {
18347            // A user ID was deleted here. Go through all users and remove it
18348            // from KeyStore.
18349            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18350        }
18351    }
18352
18353    static boolean locationIsPrivileged(File path) {
18354        try {
18355            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18356                    .getCanonicalPath();
18357            return path.getCanonicalPath().startsWith(privilegedAppDir);
18358        } catch (IOException e) {
18359            Slog.e(TAG, "Unable to access code path " + path);
18360        }
18361        return false;
18362    }
18363
18364    /*
18365     * Tries to delete system package.
18366     */
18367    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18368            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18369            boolean writeSettings) {
18370        if (deletedPs.parentPackageName != null) {
18371            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18372            return false;
18373        }
18374
18375        final boolean applyUserRestrictions
18376                = (allUserHandles != null) && (outInfo.origUsers != null);
18377        final PackageSetting disabledPs;
18378        // Confirm if the system package has been updated
18379        // An updated system app can be deleted. This will also have to restore
18380        // the system pkg from system partition
18381        // reader
18382        synchronized (mPackages) {
18383            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18384        }
18385
18386        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18387                + " disabledPs=" + disabledPs);
18388
18389        if (disabledPs == null) {
18390            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18391            return false;
18392        } else if (DEBUG_REMOVE) {
18393            Slog.d(TAG, "Deleting system pkg from data partition");
18394        }
18395
18396        if (DEBUG_REMOVE) {
18397            if (applyUserRestrictions) {
18398                Slog.d(TAG, "Remembering install states:");
18399                for (int userId : allUserHandles) {
18400                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18401                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18402                }
18403            }
18404        }
18405
18406        // Delete the updated package
18407        outInfo.isRemovedPackageSystemUpdate = true;
18408        if (outInfo.removedChildPackages != null) {
18409            final int childCount = (deletedPs.childPackageNames != null)
18410                    ? deletedPs.childPackageNames.size() : 0;
18411            for (int i = 0; i < childCount; i++) {
18412                String childPackageName = deletedPs.childPackageNames.get(i);
18413                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18414                        .contains(childPackageName)) {
18415                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18416                            childPackageName);
18417                    if (childInfo != null) {
18418                        childInfo.isRemovedPackageSystemUpdate = true;
18419                    }
18420                }
18421            }
18422        }
18423
18424        if (disabledPs.versionCode < deletedPs.versionCode) {
18425            // Delete data for downgrades
18426            flags &= ~PackageManager.DELETE_KEEP_DATA;
18427        } else {
18428            // Preserve data by setting flag
18429            flags |= PackageManager.DELETE_KEEP_DATA;
18430        }
18431
18432        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18433                outInfo, writeSettings, disabledPs.pkg);
18434        if (!ret) {
18435            return false;
18436        }
18437
18438        // writer
18439        synchronized (mPackages) {
18440            // Reinstate the old system package
18441            enableSystemPackageLPw(disabledPs.pkg);
18442            // Remove any native libraries from the upgraded package.
18443            removeNativeBinariesLI(deletedPs);
18444        }
18445
18446        // Install the system package
18447        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18448        int parseFlags = mDefParseFlags
18449                | PackageParser.PARSE_MUST_BE_APK
18450                | PackageParser.PARSE_IS_SYSTEM
18451                | PackageParser.PARSE_IS_SYSTEM_DIR;
18452        if (locationIsPrivileged(disabledPs.codePath)) {
18453            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18454        }
18455
18456        final PackageParser.Package newPkg;
18457        try {
18458            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18459                0 /* currentTime */, null);
18460        } catch (PackageManagerException e) {
18461            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18462                    + e.getMessage());
18463            return false;
18464        }
18465
18466        try {
18467            // update shared libraries for the newly re-installed system package
18468            updateSharedLibrariesLPr(newPkg, null);
18469        } catch (PackageManagerException e) {
18470            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18471        }
18472
18473        prepareAppDataAfterInstallLIF(newPkg);
18474
18475        // writer
18476        synchronized (mPackages) {
18477            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18478
18479            // Propagate the permissions state as we do not want to drop on the floor
18480            // runtime permissions. The update permissions method below will take
18481            // care of removing obsolete permissions and grant install permissions.
18482            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18483            updatePermissionsLPw(newPkg.packageName, newPkg,
18484                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18485
18486            if (applyUserRestrictions) {
18487                boolean installedStateChanged = false;
18488                if (DEBUG_REMOVE) {
18489                    Slog.d(TAG, "Propagating install state across reinstall");
18490                }
18491                for (int userId : allUserHandles) {
18492                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18493                    if (DEBUG_REMOVE) {
18494                        Slog.d(TAG, "    user " + userId + " => " + installed);
18495                    }
18496                    if (installed != ps.getInstalled(userId)) {
18497                        installedStateChanged = true;
18498                    }
18499                    ps.setInstalled(installed, userId);
18500
18501                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18502                }
18503                // Regardless of writeSettings we need to ensure that this restriction
18504                // state propagation is persisted
18505                mSettings.writeAllUsersPackageRestrictionsLPr();
18506                if (installedStateChanged) {
18507                    mSettings.writeKernelMappingLPr(ps);
18508                }
18509            }
18510            // can downgrade to reader here
18511            if (writeSettings) {
18512                mSettings.writeLPr();
18513            }
18514        }
18515        return true;
18516    }
18517
18518    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18519            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18520            PackageRemovedInfo outInfo, boolean writeSettings,
18521            PackageParser.Package replacingPackage) {
18522        synchronized (mPackages) {
18523            if (outInfo != null) {
18524                outInfo.uid = ps.appId;
18525            }
18526
18527            if (outInfo != null && outInfo.removedChildPackages != null) {
18528                final int childCount = (ps.childPackageNames != null)
18529                        ? ps.childPackageNames.size() : 0;
18530                for (int i = 0; i < childCount; i++) {
18531                    String childPackageName = ps.childPackageNames.get(i);
18532                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18533                    if (childPs == null) {
18534                        return false;
18535                    }
18536                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18537                            childPackageName);
18538                    if (childInfo != null) {
18539                        childInfo.uid = childPs.appId;
18540                    }
18541                }
18542            }
18543        }
18544
18545        // Delete package data from internal structures and also remove data if flag is set
18546        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18547
18548        // Delete the child packages data
18549        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18550        for (int i = 0; i < childCount; i++) {
18551            PackageSetting childPs;
18552            synchronized (mPackages) {
18553                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18554            }
18555            if (childPs != null) {
18556                PackageRemovedInfo childOutInfo = (outInfo != null
18557                        && outInfo.removedChildPackages != null)
18558                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18559                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18560                        && (replacingPackage != null
18561                        && !replacingPackage.hasChildPackage(childPs.name))
18562                        ? flags & ~DELETE_KEEP_DATA : flags;
18563                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18564                        deleteFlags, writeSettings);
18565            }
18566        }
18567
18568        // Delete application code and resources only for parent packages
18569        if (ps.parentPackageName == null) {
18570            if (deleteCodeAndResources && (outInfo != null)) {
18571                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18572                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18573                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18574            }
18575        }
18576
18577        return true;
18578    }
18579
18580    @Override
18581    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18582            int userId) {
18583        mContext.enforceCallingOrSelfPermission(
18584                android.Manifest.permission.DELETE_PACKAGES, null);
18585        synchronized (mPackages) {
18586            // Cannot block uninstall of static shared libs as they are
18587            // considered a part of the using app (emulating static linking).
18588            // Also static libs are installed always on internal storage.
18589            PackageParser.Package pkg = mPackages.get(packageName);
18590            if (pkg != null && pkg.staticSharedLibName != null) {
18591                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18592                        + " providing static shared library: " + pkg.staticSharedLibName);
18593                return false;
18594            }
18595            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18596            mSettings.writePackageRestrictionsLPr(userId);
18597        }
18598        return true;
18599    }
18600
18601    @Override
18602    public boolean getBlockUninstallForUser(String packageName, int userId) {
18603        synchronized (mPackages) {
18604            return mSettings.getBlockUninstallLPr(userId, packageName);
18605        }
18606    }
18607
18608    @Override
18609    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18610        int callingUid = Binder.getCallingUid();
18611        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18612            throw new SecurityException(
18613                    "setRequiredForSystemUser can only be run by the system or root");
18614        }
18615        synchronized (mPackages) {
18616            PackageSetting ps = mSettings.mPackages.get(packageName);
18617            if (ps == null) {
18618                Log.w(TAG, "Package doesn't exist: " + packageName);
18619                return false;
18620            }
18621            if (systemUserApp) {
18622                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18623            } else {
18624                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18625            }
18626            mSettings.writeLPr();
18627        }
18628        return true;
18629    }
18630
18631    /*
18632     * This method handles package deletion in general
18633     */
18634    private boolean deletePackageLIF(String packageName, UserHandle user,
18635            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18636            PackageRemovedInfo outInfo, boolean writeSettings,
18637            PackageParser.Package replacingPackage) {
18638        if (packageName == null) {
18639            Slog.w(TAG, "Attempt to delete null packageName.");
18640            return false;
18641        }
18642
18643        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18644
18645        PackageSetting ps;
18646        synchronized (mPackages) {
18647            ps = mSettings.mPackages.get(packageName);
18648            if (ps == null) {
18649                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18650                return false;
18651            }
18652
18653            if (ps.parentPackageName != null && (!isSystemApp(ps)
18654                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18655                if (DEBUG_REMOVE) {
18656                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18657                            + ((user == null) ? UserHandle.USER_ALL : user));
18658                }
18659                final int removedUserId = (user != null) ? user.getIdentifier()
18660                        : UserHandle.USER_ALL;
18661                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18662                    return false;
18663                }
18664                markPackageUninstalledForUserLPw(ps, user);
18665                scheduleWritePackageRestrictionsLocked(user);
18666                return true;
18667            }
18668        }
18669
18670        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18671                && user.getIdentifier() != UserHandle.USER_ALL)) {
18672            // The caller is asking that the package only be deleted for a single
18673            // user.  To do this, we just mark its uninstalled state and delete
18674            // its data. If this is a system app, we only allow this to happen if
18675            // they have set the special DELETE_SYSTEM_APP which requests different
18676            // semantics than normal for uninstalling system apps.
18677            markPackageUninstalledForUserLPw(ps, user);
18678
18679            if (!isSystemApp(ps)) {
18680                // Do not uninstall the APK if an app should be cached
18681                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18682                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18683                    // Other user still have this package installed, so all
18684                    // we need to do is clear this user's data and save that
18685                    // it is uninstalled.
18686                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18687                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18688                        return false;
18689                    }
18690                    scheduleWritePackageRestrictionsLocked(user);
18691                    return true;
18692                } else {
18693                    // We need to set it back to 'installed' so the uninstall
18694                    // broadcasts will be sent correctly.
18695                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18696                    ps.setInstalled(true, user.getIdentifier());
18697                    mSettings.writeKernelMappingLPr(ps);
18698                }
18699            } else {
18700                // This is a system app, so we assume that the
18701                // other users still have this package installed, so all
18702                // we need to do is clear this user's data and save that
18703                // it is uninstalled.
18704                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18705                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18706                    return false;
18707                }
18708                scheduleWritePackageRestrictionsLocked(user);
18709                return true;
18710            }
18711        }
18712
18713        // If we are deleting a composite package for all users, keep track
18714        // of result for each child.
18715        if (ps.childPackageNames != null && outInfo != null) {
18716            synchronized (mPackages) {
18717                final int childCount = ps.childPackageNames.size();
18718                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18719                for (int i = 0; i < childCount; i++) {
18720                    String childPackageName = ps.childPackageNames.get(i);
18721                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18722                    childInfo.removedPackage = childPackageName;
18723                    childInfo.installerPackageName = ps.installerPackageName;
18724                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18725                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18726                    if (childPs != null) {
18727                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18728                    }
18729                }
18730            }
18731        }
18732
18733        boolean ret = false;
18734        if (isSystemApp(ps)) {
18735            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18736            // When an updated system application is deleted we delete the existing resources
18737            // as well and fall back to existing code in system partition
18738            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18739        } else {
18740            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18741            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18742                    outInfo, writeSettings, replacingPackage);
18743        }
18744
18745        // Take a note whether we deleted the package for all users
18746        if (outInfo != null) {
18747            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18748            if (outInfo.removedChildPackages != null) {
18749                synchronized (mPackages) {
18750                    final int childCount = outInfo.removedChildPackages.size();
18751                    for (int i = 0; i < childCount; i++) {
18752                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18753                        if (childInfo != null) {
18754                            childInfo.removedForAllUsers = mPackages.get(
18755                                    childInfo.removedPackage) == null;
18756                        }
18757                    }
18758                }
18759            }
18760            // If we uninstalled an update to a system app there may be some
18761            // child packages that appeared as they are declared in the system
18762            // app but were not declared in the update.
18763            if (isSystemApp(ps)) {
18764                synchronized (mPackages) {
18765                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18766                    final int childCount = (updatedPs.childPackageNames != null)
18767                            ? updatedPs.childPackageNames.size() : 0;
18768                    for (int i = 0; i < childCount; i++) {
18769                        String childPackageName = updatedPs.childPackageNames.get(i);
18770                        if (outInfo.removedChildPackages == null
18771                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18772                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18773                            if (childPs == null) {
18774                                continue;
18775                            }
18776                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18777                            installRes.name = childPackageName;
18778                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18779                            installRes.pkg = mPackages.get(childPackageName);
18780                            installRes.uid = childPs.pkg.applicationInfo.uid;
18781                            if (outInfo.appearedChildPackages == null) {
18782                                outInfo.appearedChildPackages = new ArrayMap<>();
18783                            }
18784                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18785                        }
18786                    }
18787                }
18788            }
18789        }
18790
18791        return ret;
18792    }
18793
18794    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18795        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18796                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18797        for (int nextUserId : userIds) {
18798            if (DEBUG_REMOVE) {
18799                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18800            }
18801            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18802                    false /*installed*/,
18803                    true /*stopped*/,
18804                    true /*notLaunched*/,
18805                    false /*hidden*/,
18806                    false /*suspended*/,
18807                    false /*instantApp*/,
18808                    null /*lastDisableAppCaller*/,
18809                    null /*enabledComponents*/,
18810                    null /*disabledComponents*/,
18811                    ps.readUserState(nextUserId).domainVerificationStatus,
18812                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18813        }
18814        mSettings.writeKernelMappingLPr(ps);
18815    }
18816
18817    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18818            PackageRemovedInfo outInfo) {
18819        final PackageParser.Package pkg;
18820        synchronized (mPackages) {
18821            pkg = mPackages.get(ps.name);
18822        }
18823
18824        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18825                : new int[] {userId};
18826        for (int nextUserId : userIds) {
18827            if (DEBUG_REMOVE) {
18828                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18829                        + nextUserId);
18830            }
18831
18832            destroyAppDataLIF(pkg, userId,
18833                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18834            destroyAppProfilesLIF(pkg, userId);
18835            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18836            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18837            schedulePackageCleaning(ps.name, nextUserId, false);
18838            synchronized (mPackages) {
18839                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18840                    scheduleWritePackageRestrictionsLocked(nextUserId);
18841                }
18842                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18843            }
18844        }
18845
18846        if (outInfo != null) {
18847            outInfo.removedPackage = ps.name;
18848            outInfo.installerPackageName = ps.installerPackageName;
18849            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18850            outInfo.removedAppId = ps.appId;
18851            outInfo.removedUsers = userIds;
18852            outInfo.broadcastUsers = userIds;
18853        }
18854
18855        return true;
18856    }
18857
18858    private final class ClearStorageConnection implements ServiceConnection {
18859        IMediaContainerService mContainerService;
18860
18861        @Override
18862        public void onServiceConnected(ComponentName name, IBinder service) {
18863            synchronized (this) {
18864                mContainerService = IMediaContainerService.Stub
18865                        .asInterface(Binder.allowBlocking(service));
18866                notifyAll();
18867            }
18868        }
18869
18870        @Override
18871        public void onServiceDisconnected(ComponentName name) {
18872        }
18873    }
18874
18875    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18876        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18877
18878        final boolean mounted;
18879        if (Environment.isExternalStorageEmulated()) {
18880            mounted = true;
18881        } else {
18882            final String status = Environment.getExternalStorageState();
18883
18884            mounted = status.equals(Environment.MEDIA_MOUNTED)
18885                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18886        }
18887
18888        if (!mounted) {
18889            return;
18890        }
18891
18892        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18893        int[] users;
18894        if (userId == UserHandle.USER_ALL) {
18895            users = sUserManager.getUserIds();
18896        } else {
18897            users = new int[] { userId };
18898        }
18899        final ClearStorageConnection conn = new ClearStorageConnection();
18900        if (mContext.bindServiceAsUser(
18901                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18902            try {
18903                for (int curUser : users) {
18904                    long timeout = SystemClock.uptimeMillis() + 5000;
18905                    synchronized (conn) {
18906                        long now;
18907                        while (conn.mContainerService == null &&
18908                                (now = SystemClock.uptimeMillis()) < timeout) {
18909                            try {
18910                                conn.wait(timeout - now);
18911                            } catch (InterruptedException e) {
18912                            }
18913                        }
18914                    }
18915                    if (conn.mContainerService == null) {
18916                        return;
18917                    }
18918
18919                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18920                    clearDirectory(conn.mContainerService,
18921                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18922                    if (allData) {
18923                        clearDirectory(conn.mContainerService,
18924                                userEnv.buildExternalStorageAppDataDirs(packageName));
18925                        clearDirectory(conn.mContainerService,
18926                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18927                    }
18928                }
18929            } finally {
18930                mContext.unbindService(conn);
18931            }
18932        }
18933    }
18934
18935    @Override
18936    public void clearApplicationProfileData(String packageName) {
18937        enforceSystemOrRoot("Only the system can clear all profile data");
18938
18939        final PackageParser.Package pkg;
18940        synchronized (mPackages) {
18941            pkg = mPackages.get(packageName);
18942        }
18943
18944        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18945            synchronized (mInstallLock) {
18946                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18947            }
18948        }
18949    }
18950
18951    @Override
18952    public void clearApplicationUserData(final String packageName,
18953            final IPackageDataObserver observer, final int userId) {
18954        mContext.enforceCallingOrSelfPermission(
18955                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18956
18957        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18958                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18959
18960        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18961            throw new SecurityException("Cannot clear data for a protected package: "
18962                    + packageName);
18963        }
18964        // Queue up an async operation since the package deletion may take a little while.
18965        mHandler.post(new Runnable() {
18966            public void run() {
18967                mHandler.removeCallbacks(this);
18968                final boolean succeeded;
18969                try (PackageFreezer freezer = freezePackage(packageName,
18970                        "clearApplicationUserData")) {
18971                    synchronized (mInstallLock) {
18972                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18973                    }
18974                    clearExternalStorageDataSync(packageName, userId, true);
18975                    synchronized (mPackages) {
18976                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18977                                packageName, userId);
18978                    }
18979                }
18980                if (succeeded) {
18981                    // invoke DeviceStorageMonitor's update method to clear any notifications
18982                    DeviceStorageMonitorInternal dsm = LocalServices
18983                            .getService(DeviceStorageMonitorInternal.class);
18984                    if (dsm != null) {
18985                        dsm.checkMemory();
18986                    }
18987                }
18988                if(observer != null) {
18989                    try {
18990                        observer.onRemoveCompleted(packageName, succeeded);
18991                    } catch (RemoteException e) {
18992                        Log.i(TAG, "Observer no longer exists.");
18993                    }
18994                } //end if observer
18995            } //end run
18996        });
18997    }
18998
18999    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19000        if (packageName == null) {
19001            Slog.w(TAG, "Attempt to delete null packageName.");
19002            return false;
19003        }
19004
19005        // Try finding details about the requested package
19006        PackageParser.Package pkg;
19007        synchronized (mPackages) {
19008            pkg = mPackages.get(packageName);
19009            if (pkg == null) {
19010                final PackageSetting ps = mSettings.mPackages.get(packageName);
19011                if (ps != null) {
19012                    pkg = ps.pkg;
19013                }
19014            }
19015
19016            if (pkg == null) {
19017                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19018                return false;
19019            }
19020
19021            PackageSetting ps = (PackageSetting) pkg.mExtras;
19022            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19023        }
19024
19025        clearAppDataLIF(pkg, userId,
19026                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19027
19028        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19029        removeKeystoreDataIfNeeded(userId, appId);
19030
19031        UserManagerInternal umInternal = getUserManagerInternal();
19032        final int flags;
19033        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19034            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19035        } else if (umInternal.isUserRunning(userId)) {
19036            flags = StorageManager.FLAG_STORAGE_DE;
19037        } else {
19038            flags = 0;
19039        }
19040        prepareAppDataContentsLIF(pkg, userId, flags);
19041
19042        return true;
19043    }
19044
19045    /**
19046     * Reverts user permission state changes (permissions and flags) in
19047     * all packages for a given user.
19048     *
19049     * @param userId The device user for which to do a reset.
19050     */
19051    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19052        final int packageCount = mPackages.size();
19053        for (int i = 0; i < packageCount; i++) {
19054            PackageParser.Package pkg = mPackages.valueAt(i);
19055            PackageSetting ps = (PackageSetting) pkg.mExtras;
19056            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19057        }
19058    }
19059
19060    private void resetNetworkPolicies(int userId) {
19061        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19062    }
19063
19064    /**
19065     * Reverts user permission state changes (permissions and flags).
19066     *
19067     * @param ps The package for which to reset.
19068     * @param userId The device user for which to do a reset.
19069     */
19070    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19071            final PackageSetting ps, final int userId) {
19072        if (ps.pkg == null) {
19073            return;
19074        }
19075
19076        // These are flags that can change base on user actions.
19077        final int userSettableMask = FLAG_PERMISSION_USER_SET
19078                | FLAG_PERMISSION_USER_FIXED
19079                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19080                | FLAG_PERMISSION_REVIEW_REQUIRED;
19081
19082        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19083                | FLAG_PERMISSION_POLICY_FIXED;
19084
19085        boolean writeInstallPermissions = false;
19086        boolean writeRuntimePermissions = false;
19087
19088        final int permissionCount = ps.pkg.requestedPermissions.size();
19089        for (int i = 0; i < permissionCount; i++) {
19090            String permission = ps.pkg.requestedPermissions.get(i);
19091
19092            BasePermission bp = mSettings.mPermissions.get(permission);
19093            if (bp == null) {
19094                continue;
19095            }
19096
19097            // If shared user we just reset the state to which only this app contributed.
19098            if (ps.sharedUser != null) {
19099                boolean used = false;
19100                final int packageCount = ps.sharedUser.packages.size();
19101                for (int j = 0; j < packageCount; j++) {
19102                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19103                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19104                            && pkg.pkg.requestedPermissions.contains(permission)) {
19105                        used = true;
19106                        break;
19107                    }
19108                }
19109                if (used) {
19110                    continue;
19111                }
19112            }
19113
19114            PermissionsState permissionsState = ps.getPermissionsState();
19115
19116            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19117
19118            // Always clear the user settable flags.
19119            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19120                    bp.name) != null;
19121            // If permission review is enabled and this is a legacy app, mark the
19122            // permission as requiring a review as this is the initial state.
19123            int flags = 0;
19124            if (mPermissionReviewRequired
19125                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19126                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19127            }
19128            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19129                if (hasInstallState) {
19130                    writeInstallPermissions = true;
19131                } else {
19132                    writeRuntimePermissions = true;
19133                }
19134            }
19135
19136            // Below is only runtime permission handling.
19137            if (!bp.isRuntime()) {
19138                continue;
19139            }
19140
19141            // Never clobber system or policy.
19142            if ((oldFlags & policyOrSystemFlags) != 0) {
19143                continue;
19144            }
19145
19146            // If this permission was granted by default, make sure it is.
19147            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19148                if (permissionsState.grantRuntimePermission(bp, userId)
19149                        != PERMISSION_OPERATION_FAILURE) {
19150                    writeRuntimePermissions = true;
19151                }
19152            // If permission review is enabled the permissions for a legacy apps
19153            // are represented as constantly granted runtime ones, so don't revoke.
19154            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19155                // Otherwise, reset the permission.
19156                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19157                switch (revokeResult) {
19158                    case PERMISSION_OPERATION_SUCCESS:
19159                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19160                        writeRuntimePermissions = true;
19161                        final int appId = ps.appId;
19162                        mHandler.post(new Runnable() {
19163                            @Override
19164                            public void run() {
19165                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19166                            }
19167                        });
19168                    } break;
19169                }
19170            }
19171        }
19172
19173        // Synchronously write as we are taking permissions away.
19174        if (writeRuntimePermissions) {
19175            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19176        }
19177
19178        // Synchronously write as we are taking permissions away.
19179        if (writeInstallPermissions) {
19180            mSettings.writeLPr();
19181        }
19182    }
19183
19184    /**
19185     * Remove entries from the keystore daemon. Will only remove it if the
19186     * {@code appId} is valid.
19187     */
19188    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19189        if (appId < 0) {
19190            return;
19191        }
19192
19193        final KeyStore keyStore = KeyStore.getInstance();
19194        if (keyStore != null) {
19195            if (userId == UserHandle.USER_ALL) {
19196                for (final int individual : sUserManager.getUserIds()) {
19197                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19198                }
19199            } else {
19200                keyStore.clearUid(UserHandle.getUid(userId, appId));
19201            }
19202        } else {
19203            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19204        }
19205    }
19206
19207    @Override
19208    public void deleteApplicationCacheFiles(final String packageName,
19209            final IPackageDataObserver observer) {
19210        final int userId = UserHandle.getCallingUserId();
19211        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19212    }
19213
19214    @Override
19215    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19216            final IPackageDataObserver observer) {
19217        mContext.enforceCallingOrSelfPermission(
19218                android.Manifest.permission.DELETE_CACHE_FILES, null);
19219        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19220                /* requireFullPermission= */ true, /* checkShell= */ false,
19221                "delete application cache files");
19222
19223        final PackageParser.Package pkg;
19224        synchronized (mPackages) {
19225            pkg = mPackages.get(packageName);
19226        }
19227
19228        // Queue up an async operation since the package deletion may take a little while.
19229        mHandler.post(new Runnable() {
19230            public void run() {
19231                synchronized (mInstallLock) {
19232                    final int flags = StorageManager.FLAG_STORAGE_DE
19233                            | StorageManager.FLAG_STORAGE_CE;
19234                    // We're only clearing cache files, so we don't care if the
19235                    // app is unfrozen and still able to run
19236                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19237                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19238                }
19239                clearExternalStorageDataSync(packageName, userId, false);
19240                if (observer != null) {
19241                    try {
19242                        observer.onRemoveCompleted(packageName, true);
19243                    } catch (RemoteException e) {
19244                        Log.i(TAG, "Observer no longer exists.");
19245                    }
19246                }
19247            }
19248        });
19249    }
19250
19251    @Override
19252    public void getPackageSizeInfo(final String packageName, int userHandle,
19253            final IPackageStatsObserver observer) {
19254        throw new UnsupportedOperationException(
19255                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19256    }
19257
19258    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19259        final PackageSetting ps;
19260        synchronized (mPackages) {
19261            ps = mSettings.mPackages.get(packageName);
19262            if (ps == null) {
19263                Slog.w(TAG, "Failed to find settings for " + packageName);
19264                return false;
19265            }
19266        }
19267
19268        final String[] packageNames = { packageName };
19269        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19270        final String[] codePaths = { ps.codePathString };
19271
19272        try {
19273            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19274                    ps.appId, ceDataInodes, codePaths, stats);
19275
19276            // For now, ignore code size of packages on system partition
19277            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19278                stats.codeSize = 0;
19279            }
19280
19281            // External clients expect these to be tracked separately
19282            stats.dataSize -= stats.cacheSize;
19283
19284        } catch (InstallerException e) {
19285            Slog.w(TAG, String.valueOf(e));
19286            return false;
19287        }
19288
19289        return true;
19290    }
19291
19292    private int getUidTargetSdkVersionLockedLPr(int uid) {
19293        Object obj = mSettings.getUserIdLPr(uid);
19294        if (obj instanceof SharedUserSetting) {
19295            final SharedUserSetting sus = (SharedUserSetting) obj;
19296            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19297            final Iterator<PackageSetting> it = sus.packages.iterator();
19298            while (it.hasNext()) {
19299                final PackageSetting ps = it.next();
19300                if (ps.pkg != null) {
19301                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19302                    if (v < vers) vers = v;
19303                }
19304            }
19305            return vers;
19306        } else if (obj instanceof PackageSetting) {
19307            final PackageSetting ps = (PackageSetting) obj;
19308            if (ps.pkg != null) {
19309                return ps.pkg.applicationInfo.targetSdkVersion;
19310            }
19311        }
19312        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19313    }
19314
19315    @Override
19316    public void addPreferredActivity(IntentFilter filter, int match,
19317            ComponentName[] set, ComponentName activity, int userId) {
19318        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19319                "Adding preferred");
19320    }
19321
19322    private void addPreferredActivityInternal(IntentFilter filter, int match,
19323            ComponentName[] set, ComponentName activity, boolean always, int userId,
19324            String opname) {
19325        // writer
19326        int callingUid = Binder.getCallingUid();
19327        enforceCrossUserPermission(callingUid, userId,
19328                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19329        if (filter.countActions() == 0) {
19330            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19331            return;
19332        }
19333        synchronized (mPackages) {
19334            if (mContext.checkCallingOrSelfPermission(
19335                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19336                    != PackageManager.PERMISSION_GRANTED) {
19337                if (getUidTargetSdkVersionLockedLPr(callingUid)
19338                        < Build.VERSION_CODES.FROYO) {
19339                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19340                            + callingUid);
19341                    return;
19342                }
19343                mContext.enforceCallingOrSelfPermission(
19344                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19345            }
19346
19347            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19348            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19349                    + userId + ":");
19350            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19351            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19352            scheduleWritePackageRestrictionsLocked(userId);
19353            postPreferredActivityChangedBroadcast(userId);
19354        }
19355    }
19356
19357    private void postPreferredActivityChangedBroadcast(int userId) {
19358        mHandler.post(() -> {
19359            final IActivityManager am = ActivityManager.getService();
19360            if (am == null) {
19361                return;
19362            }
19363
19364            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19365            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19366            try {
19367                am.broadcastIntent(null, intent, null, null,
19368                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19369                        null, false, false, userId);
19370            } catch (RemoteException e) {
19371            }
19372        });
19373    }
19374
19375    @Override
19376    public void replacePreferredActivity(IntentFilter filter, int match,
19377            ComponentName[] set, ComponentName activity, int userId) {
19378        if (filter.countActions() != 1) {
19379            throw new IllegalArgumentException(
19380                    "replacePreferredActivity expects filter to have only 1 action.");
19381        }
19382        if (filter.countDataAuthorities() != 0
19383                || filter.countDataPaths() != 0
19384                || filter.countDataSchemes() > 1
19385                || filter.countDataTypes() != 0) {
19386            throw new IllegalArgumentException(
19387                    "replacePreferredActivity expects filter to have no data authorities, " +
19388                    "paths, or types; and at most one scheme.");
19389        }
19390
19391        final int callingUid = Binder.getCallingUid();
19392        enforceCrossUserPermission(callingUid, userId,
19393                true /* requireFullPermission */, false /* checkShell */,
19394                "replace preferred activity");
19395        synchronized (mPackages) {
19396            if (mContext.checkCallingOrSelfPermission(
19397                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19398                    != PackageManager.PERMISSION_GRANTED) {
19399                if (getUidTargetSdkVersionLockedLPr(callingUid)
19400                        < Build.VERSION_CODES.FROYO) {
19401                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19402                            + Binder.getCallingUid());
19403                    return;
19404                }
19405                mContext.enforceCallingOrSelfPermission(
19406                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19407            }
19408
19409            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19410            if (pir != null) {
19411                // Get all of the existing entries that exactly match this filter.
19412                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19413                if (existing != null && existing.size() == 1) {
19414                    PreferredActivity cur = existing.get(0);
19415                    if (DEBUG_PREFERRED) {
19416                        Slog.i(TAG, "Checking replace of preferred:");
19417                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19418                        if (!cur.mPref.mAlways) {
19419                            Slog.i(TAG, "  -- CUR; not mAlways!");
19420                        } else {
19421                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19422                            Slog.i(TAG, "  -- CUR: mSet="
19423                                    + Arrays.toString(cur.mPref.mSetComponents));
19424                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19425                            Slog.i(TAG, "  -- NEW: mMatch="
19426                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19427                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19428                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19429                        }
19430                    }
19431                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19432                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19433                            && cur.mPref.sameSet(set)) {
19434                        // Setting the preferred activity to what it happens to be already
19435                        if (DEBUG_PREFERRED) {
19436                            Slog.i(TAG, "Replacing with same preferred activity "
19437                                    + cur.mPref.mShortComponent + " for user "
19438                                    + userId + ":");
19439                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19440                        }
19441                        return;
19442                    }
19443                }
19444
19445                if (existing != null) {
19446                    if (DEBUG_PREFERRED) {
19447                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19448                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19449                    }
19450                    for (int i = 0; i < existing.size(); i++) {
19451                        PreferredActivity pa = existing.get(i);
19452                        if (DEBUG_PREFERRED) {
19453                            Slog.i(TAG, "Removing existing preferred activity "
19454                                    + pa.mPref.mComponent + ":");
19455                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19456                        }
19457                        pir.removeFilter(pa);
19458                    }
19459                }
19460            }
19461            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19462                    "Replacing preferred");
19463        }
19464    }
19465
19466    @Override
19467    public void clearPackagePreferredActivities(String packageName) {
19468        final int uid = Binder.getCallingUid();
19469        // writer
19470        synchronized (mPackages) {
19471            PackageParser.Package pkg = mPackages.get(packageName);
19472            if (pkg == null || pkg.applicationInfo.uid != uid) {
19473                if (mContext.checkCallingOrSelfPermission(
19474                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19475                        != PackageManager.PERMISSION_GRANTED) {
19476                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19477                            < Build.VERSION_CODES.FROYO) {
19478                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19479                                + Binder.getCallingUid());
19480                        return;
19481                    }
19482                    mContext.enforceCallingOrSelfPermission(
19483                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19484                }
19485            }
19486
19487            int user = UserHandle.getCallingUserId();
19488            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19489                scheduleWritePackageRestrictionsLocked(user);
19490            }
19491        }
19492    }
19493
19494    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19495    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19496        ArrayList<PreferredActivity> removed = null;
19497        boolean changed = false;
19498        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19499            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19500            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19501            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19502                continue;
19503            }
19504            Iterator<PreferredActivity> it = pir.filterIterator();
19505            while (it.hasNext()) {
19506                PreferredActivity pa = it.next();
19507                // Mark entry for removal only if it matches the package name
19508                // and the entry is of type "always".
19509                if (packageName == null ||
19510                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19511                                && pa.mPref.mAlways)) {
19512                    if (removed == null) {
19513                        removed = new ArrayList<PreferredActivity>();
19514                    }
19515                    removed.add(pa);
19516                }
19517            }
19518            if (removed != null) {
19519                for (int j=0; j<removed.size(); j++) {
19520                    PreferredActivity pa = removed.get(j);
19521                    pir.removeFilter(pa);
19522                }
19523                changed = true;
19524            }
19525        }
19526        if (changed) {
19527            postPreferredActivityChangedBroadcast(userId);
19528        }
19529        return changed;
19530    }
19531
19532    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19533    private void clearIntentFilterVerificationsLPw(int userId) {
19534        final int packageCount = mPackages.size();
19535        for (int i = 0; i < packageCount; i++) {
19536            PackageParser.Package pkg = mPackages.valueAt(i);
19537            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19538        }
19539    }
19540
19541    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19542    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19543        if (userId == UserHandle.USER_ALL) {
19544            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19545                    sUserManager.getUserIds())) {
19546                for (int oneUserId : sUserManager.getUserIds()) {
19547                    scheduleWritePackageRestrictionsLocked(oneUserId);
19548                }
19549            }
19550        } else {
19551            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19552                scheduleWritePackageRestrictionsLocked(userId);
19553            }
19554        }
19555    }
19556
19557    /** Clears state for all users, and touches intent filter verification policy */
19558    void clearDefaultBrowserIfNeeded(String packageName) {
19559        for (int oneUserId : sUserManager.getUserIds()) {
19560            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19561        }
19562    }
19563
19564    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19565        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19566        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19567            if (packageName.equals(defaultBrowserPackageName)) {
19568                setDefaultBrowserPackageName(null, userId);
19569            }
19570        }
19571    }
19572
19573    @Override
19574    public void resetApplicationPreferences(int userId) {
19575        mContext.enforceCallingOrSelfPermission(
19576                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19577        final long identity = Binder.clearCallingIdentity();
19578        // writer
19579        try {
19580            synchronized (mPackages) {
19581                clearPackagePreferredActivitiesLPw(null, userId);
19582                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19583                // TODO: We have to reset the default SMS and Phone. This requires
19584                // significant refactoring to keep all default apps in the package
19585                // manager (cleaner but more work) or have the services provide
19586                // callbacks to the package manager to request a default app reset.
19587                applyFactoryDefaultBrowserLPw(userId);
19588                clearIntentFilterVerificationsLPw(userId);
19589                primeDomainVerificationsLPw(userId);
19590                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19591                scheduleWritePackageRestrictionsLocked(userId);
19592            }
19593            resetNetworkPolicies(userId);
19594        } finally {
19595            Binder.restoreCallingIdentity(identity);
19596        }
19597    }
19598
19599    @Override
19600    public int getPreferredActivities(List<IntentFilter> outFilters,
19601            List<ComponentName> outActivities, String packageName) {
19602
19603        int num = 0;
19604        final int userId = UserHandle.getCallingUserId();
19605        // reader
19606        synchronized (mPackages) {
19607            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19608            if (pir != null) {
19609                final Iterator<PreferredActivity> it = pir.filterIterator();
19610                while (it.hasNext()) {
19611                    final PreferredActivity pa = it.next();
19612                    if (packageName == null
19613                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19614                                    && pa.mPref.mAlways)) {
19615                        if (outFilters != null) {
19616                            outFilters.add(new IntentFilter(pa));
19617                        }
19618                        if (outActivities != null) {
19619                            outActivities.add(pa.mPref.mComponent);
19620                        }
19621                    }
19622                }
19623            }
19624        }
19625
19626        return num;
19627    }
19628
19629    @Override
19630    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19631            int userId) {
19632        int callingUid = Binder.getCallingUid();
19633        if (callingUid != Process.SYSTEM_UID) {
19634            throw new SecurityException(
19635                    "addPersistentPreferredActivity can only be run by the system");
19636        }
19637        if (filter.countActions() == 0) {
19638            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19639            return;
19640        }
19641        synchronized (mPackages) {
19642            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19643                    ":");
19644            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19645            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19646                    new PersistentPreferredActivity(filter, activity));
19647            scheduleWritePackageRestrictionsLocked(userId);
19648            postPreferredActivityChangedBroadcast(userId);
19649        }
19650    }
19651
19652    @Override
19653    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19654        int callingUid = Binder.getCallingUid();
19655        if (callingUid != Process.SYSTEM_UID) {
19656            throw new SecurityException(
19657                    "clearPackagePersistentPreferredActivities can only be run by the system");
19658        }
19659        ArrayList<PersistentPreferredActivity> removed = null;
19660        boolean changed = false;
19661        synchronized (mPackages) {
19662            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19663                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19664                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19665                        .valueAt(i);
19666                if (userId != thisUserId) {
19667                    continue;
19668                }
19669                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19670                while (it.hasNext()) {
19671                    PersistentPreferredActivity ppa = it.next();
19672                    // Mark entry for removal only if it matches the package name.
19673                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19674                        if (removed == null) {
19675                            removed = new ArrayList<PersistentPreferredActivity>();
19676                        }
19677                        removed.add(ppa);
19678                    }
19679                }
19680                if (removed != null) {
19681                    for (int j=0; j<removed.size(); j++) {
19682                        PersistentPreferredActivity ppa = removed.get(j);
19683                        ppir.removeFilter(ppa);
19684                    }
19685                    changed = true;
19686                }
19687            }
19688
19689            if (changed) {
19690                scheduleWritePackageRestrictionsLocked(userId);
19691                postPreferredActivityChangedBroadcast(userId);
19692            }
19693        }
19694    }
19695
19696    /**
19697     * Common machinery for picking apart a restored XML blob and passing
19698     * it to a caller-supplied functor to be applied to the running system.
19699     */
19700    private void restoreFromXml(XmlPullParser parser, int userId,
19701            String expectedStartTag, BlobXmlRestorer functor)
19702            throws IOException, XmlPullParserException {
19703        int type;
19704        while ((type = parser.next()) != XmlPullParser.START_TAG
19705                && type != XmlPullParser.END_DOCUMENT) {
19706        }
19707        if (type != XmlPullParser.START_TAG) {
19708            // oops didn't find a start tag?!
19709            if (DEBUG_BACKUP) {
19710                Slog.e(TAG, "Didn't find start tag during restore");
19711            }
19712            return;
19713        }
19714Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19715        // this is supposed to be TAG_PREFERRED_BACKUP
19716        if (!expectedStartTag.equals(parser.getName())) {
19717            if (DEBUG_BACKUP) {
19718                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19719            }
19720            return;
19721        }
19722
19723        // skip interfering stuff, then we're aligned with the backing implementation
19724        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19725Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19726        functor.apply(parser, userId);
19727    }
19728
19729    private interface BlobXmlRestorer {
19730        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19731    }
19732
19733    /**
19734     * Non-Binder method, support for the backup/restore mechanism: write the
19735     * full set of preferred activities in its canonical XML format.  Returns the
19736     * XML output as a byte array, or null if there is none.
19737     */
19738    @Override
19739    public byte[] getPreferredActivityBackup(int userId) {
19740        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19741            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19742        }
19743
19744        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19745        try {
19746            final XmlSerializer serializer = new FastXmlSerializer();
19747            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19748            serializer.startDocument(null, true);
19749            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19750
19751            synchronized (mPackages) {
19752                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19753            }
19754
19755            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19756            serializer.endDocument();
19757            serializer.flush();
19758        } catch (Exception e) {
19759            if (DEBUG_BACKUP) {
19760                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19761            }
19762            return null;
19763        }
19764
19765        return dataStream.toByteArray();
19766    }
19767
19768    @Override
19769    public void restorePreferredActivities(byte[] backup, int userId) {
19770        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19771            throw new SecurityException("Only the system may call restorePreferredActivities()");
19772        }
19773
19774        try {
19775            final XmlPullParser parser = Xml.newPullParser();
19776            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19777            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19778                    new BlobXmlRestorer() {
19779                        @Override
19780                        public void apply(XmlPullParser parser, int userId)
19781                                throws XmlPullParserException, IOException {
19782                            synchronized (mPackages) {
19783                                mSettings.readPreferredActivitiesLPw(parser, userId);
19784                            }
19785                        }
19786                    } );
19787        } catch (Exception e) {
19788            if (DEBUG_BACKUP) {
19789                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19790            }
19791        }
19792    }
19793
19794    /**
19795     * Non-Binder method, support for the backup/restore mechanism: write the
19796     * default browser (etc) settings in its canonical XML format.  Returns the default
19797     * browser XML representation as a byte array, or null if there is none.
19798     */
19799    @Override
19800    public byte[] getDefaultAppsBackup(int userId) {
19801        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19802            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19803        }
19804
19805        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19806        try {
19807            final XmlSerializer serializer = new FastXmlSerializer();
19808            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19809            serializer.startDocument(null, true);
19810            serializer.startTag(null, TAG_DEFAULT_APPS);
19811
19812            synchronized (mPackages) {
19813                mSettings.writeDefaultAppsLPr(serializer, userId);
19814            }
19815
19816            serializer.endTag(null, TAG_DEFAULT_APPS);
19817            serializer.endDocument();
19818            serializer.flush();
19819        } catch (Exception e) {
19820            if (DEBUG_BACKUP) {
19821                Slog.e(TAG, "Unable to write default apps for backup", e);
19822            }
19823            return null;
19824        }
19825
19826        return dataStream.toByteArray();
19827    }
19828
19829    @Override
19830    public void restoreDefaultApps(byte[] backup, int userId) {
19831        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19832            throw new SecurityException("Only the system may call restoreDefaultApps()");
19833        }
19834
19835        try {
19836            final XmlPullParser parser = Xml.newPullParser();
19837            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19838            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19839                    new BlobXmlRestorer() {
19840                        @Override
19841                        public void apply(XmlPullParser parser, int userId)
19842                                throws XmlPullParserException, IOException {
19843                            synchronized (mPackages) {
19844                                mSettings.readDefaultAppsLPw(parser, userId);
19845                            }
19846                        }
19847                    } );
19848        } catch (Exception e) {
19849            if (DEBUG_BACKUP) {
19850                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19851            }
19852        }
19853    }
19854
19855    @Override
19856    public byte[] getIntentFilterVerificationBackup(int userId) {
19857        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19858            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19859        }
19860
19861        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19862        try {
19863            final XmlSerializer serializer = new FastXmlSerializer();
19864            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19865            serializer.startDocument(null, true);
19866            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19867
19868            synchronized (mPackages) {
19869                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19870            }
19871
19872            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19873            serializer.endDocument();
19874            serializer.flush();
19875        } catch (Exception e) {
19876            if (DEBUG_BACKUP) {
19877                Slog.e(TAG, "Unable to write default apps for backup", e);
19878            }
19879            return null;
19880        }
19881
19882        return dataStream.toByteArray();
19883    }
19884
19885    @Override
19886    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19887        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19888            throw new SecurityException("Only the system may call restorePreferredActivities()");
19889        }
19890
19891        try {
19892            final XmlPullParser parser = Xml.newPullParser();
19893            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19894            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19895                    new BlobXmlRestorer() {
19896                        @Override
19897                        public void apply(XmlPullParser parser, int userId)
19898                                throws XmlPullParserException, IOException {
19899                            synchronized (mPackages) {
19900                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19901                                mSettings.writeLPr();
19902                            }
19903                        }
19904                    } );
19905        } catch (Exception e) {
19906            if (DEBUG_BACKUP) {
19907                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19908            }
19909        }
19910    }
19911
19912    @Override
19913    public byte[] getPermissionGrantBackup(int userId) {
19914        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19915            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19916        }
19917
19918        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19919        try {
19920            final XmlSerializer serializer = new FastXmlSerializer();
19921            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19922            serializer.startDocument(null, true);
19923            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19924
19925            synchronized (mPackages) {
19926                serializeRuntimePermissionGrantsLPr(serializer, userId);
19927            }
19928
19929            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19930            serializer.endDocument();
19931            serializer.flush();
19932        } catch (Exception e) {
19933            if (DEBUG_BACKUP) {
19934                Slog.e(TAG, "Unable to write default apps for backup", e);
19935            }
19936            return null;
19937        }
19938
19939        return dataStream.toByteArray();
19940    }
19941
19942    @Override
19943    public void restorePermissionGrants(byte[] backup, int userId) {
19944        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19945            throw new SecurityException("Only the system may call restorePermissionGrants()");
19946        }
19947
19948        try {
19949            final XmlPullParser parser = Xml.newPullParser();
19950            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19951            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19952                    new BlobXmlRestorer() {
19953                        @Override
19954                        public void apply(XmlPullParser parser, int userId)
19955                                throws XmlPullParserException, IOException {
19956                            synchronized (mPackages) {
19957                                processRestoredPermissionGrantsLPr(parser, userId);
19958                            }
19959                        }
19960                    } );
19961        } catch (Exception e) {
19962            if (DEBUG_BACKUP) {
19963                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19964            }
19965        }
19966    }
19967
19968    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19969            throws IOException {
19970        serializer.startTag(null, TAG_ALL_GRANTS);
19971
19972        final int N = mSettings.mPackages.size();
19973        for (int i = 0; i < N; i++) {
19974            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19975            boolean pkgGrantsKnown = false;
19976
19977            PermissionsState packagePerms = ps.getPermissionsState();
19978
19979            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19980                final int grantFlags = state.getFlags();
19981                // only look at grants that are not system/policy fixed
19982                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19983                    final boolean isGranted = state.isGranted();
19984                    // And only back up the user-twiddled state bits
19985                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19986                        final String packageName = mSettings.mPackages.keyAt(i);
19987                        if (!pkgGrantsKnown) {
19988                            serializer.startTag(null, TAG_GRANT);
19989                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19990                            pkgGrantsKnown = true;
19991                        }
19992
19993                        final boolean userSet =
19994                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19995                        final boolean userFixed =
19996                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19997                        final boolean revoke =
19998                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19999
20000                        serializer.startTag(null, TAG_PERMISSION);
20001                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20002                        if (isGranted) {
20003                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20004                        }
20005                        if (userSet) {
20006                            serializer.attribute(null, ATTR_USER_SET, "true");
20007                        }
20008                        if (userFixed) {
20009                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20010                        }
20011                        if (revoke) {
20012                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20013                        }
20014                        serializer.endTag(null, TAG_PERMISSION);
20015                    }
20016                }
20017            }
20018
20019            if (pkgGrantsKnown) {
20020                serializer.endTag(null, TAG_GRANT);
20021            }
20022        }
20023
20024        serializer.endTag(null, TAG_ALL_GRANTS);
20025    }
20026
20027    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20028            throws XmlPullParserException, IOException {
20029        String pkgName = null;
20030        int outerDepth = parser.getDepth();
20031        int type;
20032        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20033                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20034            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20035                continue;
20036            }
20037
20038            final String tagName = parser.getName();
20039            if (tagName.equals(TAG_GRANT)) {
20040                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20041                if (DEBUG_BACKUP) {
20042                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20043                }
20044            } else if (tagName.equals(TAG_PERMISSION)) {
20045
20046                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20047                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20048
20049                int newFlagSet = 0;
20050                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20051                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20052                }
20053                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20054                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20055                }
20056                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20057                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20058                }
20059                if (DEBUG_BACKUP) {
20060                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20061                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20062                }
20063                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20064                if (ps != null) {
20065                    // Already installed so we apply the grant immediately
20066                    if (DEBUG_BACKUP) {
20067                        Slog.v(TAG, "        + already installed; applying");
20068                    }
20069                    PermissionsState perms = ps.getPermissionsState();
20070                    BasePermission bp = mSettings.mPermissions.get(permName);
20071                    if (bp != null) {
20072                        if (isGranted) {
20073                            perms.grantRuntimePermission(bp, userId);
20074                        }
20075                        if (newFlagSet != 0) {
20076                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20077                        }
20078                    }
20079                } else {
20080                    // Need to wait for post-restore install to apply the grant
20081                    if (DEBUG_BACKUP) {
20082                        Slog.v(TAG, "        - not yet installed; saving for later");
20083                    }
20084                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20085                            isGranted, newFlagSet, userId);
20086                }
20087            } else {
20088                PackageManagerService.reportSettingsProblem(Log.WARN,
20089                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20090                XmlUtils.skipCurrentTag(parser);
20091            }
20092        }
20093
20094        scheduleWriteSettingsLocked();
20095        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20096    }
20097
20098    @Override
20099    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20100            int sourceUserId, int targetUserId, int flags) {
20101        mContext.enforceCallingOrSelfPermission(
20102                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20103        int callingUid = Binder.getCallingUid();
20104        enforceOwnerRights(ownerPackage, callingUid);
20105        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20106        if (intentFilter.countActions() == 0) {
20107            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20108            return;
20109        }
20110        synchronized (mPackages) {
20111            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20112                    ownerPackage, targetUserId, flags);
20113            CrossProfileIntentResolver resolver =
20114                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20115            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20116            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20117            if (existing != null) {
20118                int size = existing.size();
20119                for (int i = 0; i < size; i++) {
20120                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20121                        return;
20122                    }
20123                }
20124            }
20125            resolver.addFilter(newFilter);
20126            scheduleWritePackageRestrictionsLocked(sourceUserId);
20127        }
20128    }
20129
20130    @Override
20131    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20132        mContext.enforceCallingOrSelfPermission(
20133                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20134        int callingUid = Binder.getCallingUid();
20135        enforceOwnerRights(ownerPackage, callingUid);
20136        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20137        synchronized (mPackages) {
20138            CrossProfileIntentResolver resolver =
20139                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20140            ArraySet<CrossProfileIntentFilter> set =
20141                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20142            for (CrossProfileIntentFilter filter : set) {
20143                if (filter.getOwnerPackage().equals(ownerPackage)) {
20144                    resolver.removeFilter(filter);
20145                }
20146            }
20147            scheduleWritePackageRestrictionsLocked(sourceUserId);
20148        }
20149    }
20150
20151    // Enforcing that callingUid is owning pkg on userId
20152    private void enforceOwnerRights(String pkg, int callingUid) {
20153        // The system owns everything.
20154        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20155            return;
20156        }
20157        int callingUserId = UserHandle.getUserId(callingUid);
20158        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20159        if (pi == null) {
20160            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20161                    + callingUserId);
20162        }
20163        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20164            throw new SecurityException("Calling uid " + callingUid
20165                    + " does not own package " + pkg);
20166        }
20167    }
20168
20169    @Override
20170    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20171        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20172    }
20173
20174    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20175        UserManagerService ums = UserManagerService.getInstance();
20176        if (ums != null) {
20177            final UserInfo parent = ums.getProfileParent(userId);
20178            final int launcherUid = (parent != null) ? parent.id : userId;
20179            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20180            if (launcherComponent != null) {
20181                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20182                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20183                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20184                        .setPackage(launcherComponent.getPackageName());
20185                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20186            }
20187        }
20188    }
20189
20190    /**
20191     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20192     * then reports the most likely home activity or null if there are more than one.
20193     */
20194    private ComponentName getDefaultHomeActivity(int userId) {
20195        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20196        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20197        if (cn != null) {
20198            return cn;
20199        }
20200
20201        // Find the launcher with the highest priority and return that component if there are no
20202        // other home activity with the same priority.
20203        int lastPriority = Integer.MIN_VALUE;
20204        ComponentName lastComponent = null;
20205        final int size = allHomeCandidates.size();
20206        for (int i = 0; i < size; i++) {
20207            final ResolveInfo ri = allHomeCandidates.get(i);
20208            if (ri.priority > lastPriority) {
20209                lastComponent = ri.activityInfo.getComponentName();
20210                lastPriority = ri.priority;
20211            } else if (ri.priority == lastPriority) {
20212                // Two components found with same priority.
20213                lastComponent = null;
20214            }
20215        }
20216        return lastComponent;
20217    }
20218
20219    private Intent getHomeIntent() {
20220        Intent intent = new Intent(Intent.ACTION_MAIN);
20221        intent.addCategory(Intent.CATEGORY_HOME);
20222        intent.addCategory(Intent.CATEGORY_DEFAULT);
20223        return intent;
20224    }
20225
20226    private IntentFilter getHomeFilter() {
20227        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20228        filter.addCategory(Intent.CATEGORY_HOME);
20229        filter.addCategory(Intent.CATEGORY_DEFAULT);
20230        return filter;
20231    }
20232
20233    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20234            int userId) {
20235        Intent intent  = getHomeIntent();
20236        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20237                PackageManager.GET_META_DATA, userId);
20238        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20239                true, false, false, userId);
20240
20241        allHomeCandidates.clear();
20242        if (list != null) {
20243            for (ResolveInfo ri : list) {
20244                allHomeCandidates.add(ri);
20245            }
20246        }
20247        return (preferred == null || preferred.activityInfo == null)
20248                ? null
20249                : new ComponentName(preferred.activityInfo.packageName,
20250                        preferred.activityInfo.name);
20251    }
20252
20253    @Override
20254    public void setHomeActivity(ComponentName comp, int userId) {
20255        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20256        getHomeActivitiesAsUser(homeActivities, userId);
20257
20258        boolean found = false;
20259
20260        final int size = homeActivities.size();
20261        final ComponentName[] set = new ComponentName[size];
20262        for (int i = 0; i < size; i++) {
20263            final ResolveInfo candidate = homeActivities.get(i);
20264            final ActivityInfo info = candidate.activityInfo;
20265            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20266            set[i] = activityName;
20267            if (!found && activityName.equals(comp)) {
20268                found = true;
20269            }
20270        }
20271        if (!found) {
20272            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20273                    + userId);
20274        }
20275        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20276                set, comp, userId);
20277    }
20278
20279    private @Nullable String getSetupWizardPackageName() {
20280        final Intent intent = new Intent(Intent.ACTION_MAIN);
20281        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20282
20283        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20284                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20285                        | MATCH_DISABLED_COMPONENTS,
20286                UserHandle.myUserId());
20287        if (matches.size() == 1) {
20288            return matches.get(0).getComponentInfo().packageName;
20289        } else {
20290            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20291                    + ": matches=" + matches);
20292            return null;
20293        }
20294    }
20295
20296    private @Nullable String getStorageManagerPackageName() {
20297        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20298
20299        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20300                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20301                        | MATCH_DISABLED_COMPONENTS,
20302                UserHandle.myUserId());
20303        if (matches.size() == 1) {
20304            return matches.get(0).getComponentInfo().packageName;
20305        } else {
20306            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20307                    + matches.size() + ": matches=" + matches);
20308            return null;
20309        }
20310    }
20311
20312    @Override
20313    public void setApplicationEnabledSetting(String appPackageName,
20314            int newState, int flags, int userId, String callingPackage) {
20315        if (!sUserManager.exists(userId)) return;
20316        if (callingPackage == null) {
20317            callingPackage = Integer.toString(Binder.getCallingUid());
20318        }
20319        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20320    }
20321
20322    @Override
20323    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20324        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20325        synchronized (mPackages) {
20326            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20327            if (pkgSetting != null) {
20328                pkgSetting.setUpdateAvailable(updateAvailable);
20329            }
20330        }
20331    }
20332
20333    @Override
20334    public void setComponentEnabledSetting(ComponentName componentName,
20335            int newState, int flags, int userId) {
20336        if (!sUserManager.exists(userId)) return;
20337        setEnabledSetting(componentName.getPackageName(),
20338                componentName.getClassName(), newState, flags, userId, null);
20339    }
20340
20341    private void setEnabledSetting(final String packageName, String className, int newState,
20342            final int flags, int userId, String callingPackage) {
20343        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20344              || newState == COMPONENT_ENABLED_STATE_ENABLED
20345              || newState == COMPONENT_ENABLED_STATE_DISABLED
20346              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20347              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20348            throw new IllegalArgumentException("Invalid new component state: "
20349                    + newState);
20350        }
20351        PackageSetting pkgSetting;
20352        final int uid = Binder.getCallingUid();
20353        final int permission;
20354        if (uid == Process.SYSTEM_UID) {
20355            permission = PackageManager.PERMISSION_GRANTED;
20356        } else {
20357            permission = mContext.checkCallingOrSelfPermission(
20358                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20359        }
20360        enforceCrossUserPermission(uid, userId,
20361                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20362        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20363        boolean sendNow = false;
20364        boolean isApp = (className == null);
20365        String componentName = isApp ? packageName : className;
20366        int packageUid = -1;
20367        ArrayList<String> components;
20368
20369        // writer
20370        synchronized (mPackages) {
20371            pkgSetting = mSettings.mPackages.get(packageName);
20372            if (pkgSetting == null) {
20373                if (className == null) {
20374                    throw new IllegalArgumentException("Unknown package: " + packageName);
20375                }
20376                throw new IllegalArgumentException(
20377                        "Unknown component: " + packageName + "/" + className);
20378            }
20379        }
20380
20381        // Limit who can change which apps
20382        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20383            // Don't allow apps that don't have permission to modify other apps
20384            if (!allowedByPermission) {
20385                throw new SecurityException(
20386                        "Permission Denial: attempt to change component state from pid="
20387                        + Binder.getCallingPid()
20388                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20389            }
20390            // Don't allow changing protected packages.
20391            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20392                throw new SecurityException("Cannot disable a protected package: " + packageName);
20393            }
20394        }
20395
20396        synchronized (mPackages) {
20397            if (uid == Process.SHELL_UID
20398                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20399                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20400                // unless it is a test package.
20401                int oldState = pkgSetting.getEnabled(userId);
20402                if (className == null
20403                    &&
20404                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20405                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20406                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20407                    &&
20408                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20409                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20410                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20411                    // ok
20412                } else {
20413                    throw new SecurityException(
20414                            "Shell cannot change component state for " + packageName + "/"
20415                            + className + " to " + newState);
20416                }
20417            }
20418            if (className == null) {
20419                // We're dealing with an application/package level state change
20420                if (pkgSetting.getEnabled(userId) == newState) {
20421                    // Nothing to do
20422                    return;
20423                }
20424                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20425                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20426                    // Don't care about who enables an app.
20427                    callingPackage = null;
20428                }
20429                pkgSetting.setEnabled(newState, userId, callingPackage);
20430                // pkgSetting.pkg.mSetEnabled = newState;
20431            } else {
20432                // We're dealing with a component level state change
20433                // First, verify that this is a valid class name.
20434                PackageParser.Package pkg = pkgSetting.pkg;
20435                if (pkg == null || !pkg.hasComponentClassName(className)) {
20436                    if (pkg != null &&
20437                            pkg.applicationInfo.targetSdkVersion >=
20438                                    Build.VERSION_CODES.JELLY_BEAN) {
20439                        throw new IllegalArgumentException("Component class " + className
20440                                + " does not exist in " + packageName);
20441                    } else {
20442                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20443                                + className + " does not exist in " + packageName);
20444                    }
20445                }
20446                switch (newState) {
20447                case COMPONENT_ENABLED_STATE_ENABLED:
20448                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20449                        return;
20450                    }
20451                    break;
20452                case COMPONENT_ENABLED_STATE_DISABLED:
20453                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20454                        return;
20455                    }
20456                    break;
20457                case COMPONENT_ENABLED_STATE_DEFAULT:
20458                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20459                        return;
20460                    }
20461                    break;
20462                default:
20463                    Slog.e(TAG, "Invalid new component state: " + newState);
20464                    return;
20465                }
20466            }
20467            scheduleWritePackageRestrictionsLocked(userId);
20468            updateSequenceNumberLP(packageName, new int[] { userId });
20469            final long callingId = Binder.clearCallingIdentity();
20470            try {
20471                updateInstantAppInstallerLocked(packageName);
20472            } finally {
20473                Binder.restoreCallingIdentity(callingId);
20474            }
20475            components = mPendingBroadcasts.get(userId, packageName);
20476            final boolean newPackage = components == null;
20477            if (newPackage) {
20478                components = new ArrayList<String>();
20479            }
20480            if (!components.contains(componentName)) {
20481                components.add(componentName);
20482            }
20483            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20484                sendNow = true;
20485                // Purge entry from pending broadcast list if another one exists already
20486                // since we are sending one right away.
20487                mPendingBroadcasts.remove(userId, packageName);
20488            } else {
20489                if (newPackage) {
20490                    mPendingBroadcasts.put(userId, packageName, components);
20491                }
20492                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20493                    // Schedule a message
20494                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20495                }
20496            }
20497        }
20498
20499        long callingId = Binder.clearCallingIdentity();
20500        try {
20501            if (sendNow) {
20502                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20503                sendPackageChangedBroadcast(packageName,
20504                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20505            }
20506        } finally {
20507            Binder.restoreCallingIdentity(callingId);
20508        }
20509    }
20510
20511    @Override
20512    public void flushPackageRestrictionsAsUser(int userId) {
20513        if (!sUserManager.exists(userId)) {
20514            return;
20515        }
20516        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20517                false /* checkShell */, "flushPackageRestrictions");
20518        synchronized (mPackages) {
20519            mSettings.writePackageRestrictionsLPr(userId);
20520            mDirtyUsers.remove(userId);
20521            if (mDirtyUsers.isEmpty()) {
20522                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20523            }
20524        }
20525    }
20526
20527    private void sendPackageChangedBroadcast(String packageName,
20528            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20529        if (DEBUG_INSTALL)
20530            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20531                    + componentNames);
20532        Bundle extras = new Bundle(4);
20533        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20534        String nameList[] = new String[componentNames.size()];
20535        componentNames.toArray(nameList);
20536        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20537        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20538        extras.putInt(Intent.EXTRA_UID, packageUid);
20539        // If this is not reporting a change of the overall package, then only send it
20540        // to registered receivers.  We don't want to launch a swath of apps for every
20541        // little component state change.
20542        final int flags = !componentNames.contains(packageName)
20543                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20544        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20545                new int[] {UserHandle.getUserId(packageUid)});
20546    }
20547
20548    @Override
20549    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20550        if (!sUserManager.exists(userId)) return;
20551        final int uid = Binder.getCallingUid();
20552        final int permission = mContext.checkCallingOrSelfPermission(
20553                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20554        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20555        enforceCrossUserPermission(uid, userId,
20556                true /* requireFullPermission */, true /* checkShell */, "stop package");
20557        // writer
20558        synchronized (mPackages) {
20559            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20560                    allowedByPermission, uid, userId)) {
20561                scheduleWritePackageRestrictionsLocked(userId);
20562            }
20563        }
20564    }
20565
20566    @Override
20567    public String getInstallerPackageName(String packageName) {
20568        // reader
20569        synchronized (mPackages) {
20570            return mSettings.getInstallerPackageNameLPr(packageName);
20571        }
20572    }
20573
20574    public boolean isOrphaned(String packageName) {
20575        // reader
20576        synchronized (mPackages) {
20577            return mSettings.isOrphaned(packageName);
20578        }
20579    }
20580
20581    @Override
20582    public int getApplicationEnabledSetting(String packageName, int userId) {
20583        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20584        int uid = Binder.getCallingUid();
20585        enforceCrossUserPermission(uid, userId,
20586                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20587        // reader
20588        synchronized (mPackages) {
20589            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20590        }
20591    }
20592
20593    @Override
20594    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20595        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20596        int uid = Binder.getCallingUid();
20597        enforceCrossUserPermission(uid, userId,
20598                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20599        // reader
20600        synchronized (mPackages) {
20601            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20602        }
20603    }
20604
20605    @Override
20606    public void enterSafeMode() {
20607        enforceSystemOrRoot("Only the system can request entering safe mode");
20608
20609        if (!mSystemReady) {
20610            mSafeMode = true;
20611        }
20612    }
20613
20614    @Override
20615    public void systemReady() {
20616        mSystemReady = true;
20617        final ContentResolver resolver = mContext.getContentResolver();
20618        ContentObserver co = new ContentObserver(mHandler) {
20619            @Override
20620            public void onChange(boolean selfChange) {
20621                mEphemeralAppsDisabled =
20622                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20623                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20624            }
20625        };
20626        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20627                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20628                false, co, UserHandle.USER_SYSTEM);
20629        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20630                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20631        co.onChange(true);
20632
20633        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20634        // disabled after already being started.
20635        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20636                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20637
20638        // Read the compatibilty setting when the system is ready.
20639        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20640                mContext.getContentResolver(),
20641                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20642        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20643        if (DEBUG_SETTINGS) {
20644            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20645        }
20646
20647        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20648
20649        synchronized (mPackages) {
20650            // Verify that all of the preferred activity components actually
20651            // exist.  It is possible for applications to be updated and at
20652            // that point remove a previously declared activity component that
20653            // had been set as a preferred activity.  We try to clean this up
20654            // the next time we encounter that preferred activity, but it is
20655            // possible for the user flow to never be able to return to that
20656            // situation so here we do a sanity check to make sure we haven't
20657            // left any junk around.
20658            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20659            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20660                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20661                removed.clear();
20662                for (PreferredActivity pa : pir.filterSet()) {
20663                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20664                        removed.add(pa);
20665                    }
20666                }
20667                if (removed.size() > 0) {
20668                    for (int r=0; r<removed.size(); r++) {
20669                        PreferredActivity pa = removed.get(r);
20670                        Slog.w(TAG, "Removing dangling preferred activity: "
20671                                + pa.mPref.mComponent);
20672                        pir.removeFilter(pa);
20673                    }
20674                    mSettings.writePackageRestrictionsLPr(
20675                            mSettings.mPreferredActivities.keyAt(i));
20676                }
20677            }
20678
20679            for (int userId : UserManagerService.getInstance().getUserIds()) {
20680                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20681                    grantPermissionsUserIds = ArrayUtils.appendInt(
20682                            grantPermissionsUserIds, userId);
20683                }
20684            }
20685        }
20686        sUserManager.systemReady();
20687
20688        // If we upgraded grant all default permissions before kicking off.
20689        for (int userId : grantPermissionsUserIds) {
20690            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20691        }
20692
20693        // If we did not grant default permissions, we preload from this the
20694        // default permission exceptions lazily to ensure we don't hit the
20695        // disk on a new user creation.
20696        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20697            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20698        }
20699
20700        // Kick off any messages waiting for system ready
20701        if (mPostSystemReadyMessages != null) {
20702            for (Message msg : mPostSystemReadyMessages) {
20703                msg.sendToTarget();
20704            }
20705            mPostSystemReadyMessages = null;
20706        }
20707
20708        // Watch for external volumes that come and go over time
20709        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20710        storage.registerListener(mStorageListener);
20711
20712        mInstallerService.systemReady();
20713        mPackageDexOptimizer.systemReady();
20714
20715        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20716                StorageManagerInternal.class);
20717        StorageManagerInternal.addExternalStoragePolicy(
20718                new StorageManagerInternal.ExternalStorageMountPolicy() {
20719            @Override
20720            public int getMountMode(int uid, String packageName) {
20721                if (Process.isIsolated(uid)) {
20722                    return Zygote.MOUNT_EXTERNAL_NONE;
20723                }
20724                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20725                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20726                }
20727                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20728                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20729                }
20730                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20731                    return Zygote.MOUNT_EXTERNAL_READ;
20732                }
20733                return Zygote.MOUNT_EXTERNAL_WRITE;
20734            }
20735
20736            @Override
20737            public boolean hasExternalStorage(int uid, String packageName) {
20738                return true;
20739            }
20740        });
20741
20742        // Now that we're mostly running, clean up stale users and apps
20743        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20744        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20745
20746        if (mPrivappPermissionsViolations != null) {
20747            Slog.wtf(TAG,"Signature|privileged permissions not in "
20748                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20749            mPrivappPermissionsViolations = null;
20750        }
20751    }
20752
20753    public void waitForAppDataPrepared() {
20754        if (mPrepareAppDataFuture == null) {
20755            return;
20756        }
20757        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20758        mPrepareAppDataFuture = null;
20759    }
20760
20761    @Override
20762    public boolean isSafeMode() {
20763        return mSafeMode;
20764    }
20765
20766    @Override
20767    public boolean hasSystemUidErrors() {
20768        return mHasSystemUidErrors;
20769    }
20770
20771    static String arrayToString(int[] array) {
20772        StringBuffer buf = new StringBuffer(128);
20773        buf.append('[');
20774        if (array != null) {
20775            for (int i=0; i<array.length; i++) {
20776                if (i > 0) buf.append(", ");
20777                buf.append(array[i]);
20778            }
20779        }
20780        buf.append(']');
20781        return buf.toString();
20782    }
20783
20784    static class DumpState {
20785        public static final int DUMP_LIBS = 1 << 0;
20786        public static final int DUMP_FEATURES = 1 << 1;
20787        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20788        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20789        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20790        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20791        public static final int DUMP_PERMISSIONS = 1 << 6;
20792        public static final int DUMP_PACKAGES = 1 << 7;
20793        public static final int DUMP_SHARED_USERS = 1 << 8;
20794        public static final int DUMP_MESSAGES = 1 << 9;
20795        public static final int DUMP_PROVIDERS = 1 << 10;
20796        public static final int DUMP_VERIFIERS = 1 << 11;
20797        public static final int DUMP_PREFERRED = 1 << 12;
20798        public static final int DUMP_PREFERRED_XML = 1 << 13;
20799        public static final int DUMP_KEYSETS = 1 << 14;
20800        public static final int DUMP_VERSION = 1 << 15;
20801        public static final int DUMP_INSTALLS = 1 << 16;
20802        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20803        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20804        public static final int DUMP_FROZEN = 1 << 19;
20805        public static final int DUMP_DEXOPT = 1 << 20;
20806        public static final int DUMP_COMPILER_STATS = 1 << 21;
20807        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20808        public static final int DUMP_CHANGES = 1 << 23;
20809
20810        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20811
20812        private int mTypes;
20813
20814        private int mOptions;
20815
20816        private boolean mTitlePrinted;
20817
20818        private SharedUserSetting mSharedUser;
20819
20820        public boolean isDumping(int type) {
20821            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20822                return true;
20823            }
20824
20825            return (mTypes & type) != 0;
20826        }
20827
20828        public void setDump(int type) {
20829            mTypes |= type;
20830        }
20831
20832        public boolean isOptionEnabled(int option) {
20833            return (mOptions & option) != 0;
20834        }
20835
20836        public void setOptionEnabled(int option) {
20837            mOptions |= option;
20838        }
20839
20840        public boolean onTitlePrinted() {
20841            final boolean printed = mTitlePrinted;
20842            mTitlePrinted = true;
20843            return printed;
20844        }
20845
20846        public boolean getTitlePrinted() {
20847            return mTitlePrinted;
20848        }
20849
20850        public void setTitlePrinted(boolean enabled) {
20851            mTitlePrinted = enabled;
20852        }
20853
20854        public SharedUserSetting getSharedUser() {
20855            return mSharedUser;
20856        }
20857
20858        public void setSharedUser(SharedUserSetting user) {
20859            mSharedUser = user;
20860        }
20861    }
20862
20863    @Override
20864    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20865            FileDescriptor err, String[] args, ShellCallback callback,
20866            ResultReceiver resultReceiver) {
20867        (new PackageManagerShellCommand(this)).exec(
20868                this, in, out, err, args, callback, resultReceiver);
20869    }
20870
20871    @Override
20872    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20873        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20874
20875        DumpState dumpState = new DumpState();
20876        boolean fullPreferred = false;
20877        boolean checkin = false;
20878
20879        String packageName = null;
20880        ArraySet<String> permissionNames = null;
20881
20882        int opti = 0;
20883        while (opti < args.length) {
20884            String opt = args[opti];
20885            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20886                break;
20887            }
20888            opti++;
20889
20890            if ("-a".equals(opt)) {
20891                // Right now we only know how to print all.
20892            } else if ("-h".equals(opt)) {
20893                pw.println("Package manager dump options:");
20894                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20895                pw.println("    --checkin: dump for a checkin");
20896                pw.println("    -f: print details of intent filters");
20897                pw.println("    -h: print this help");
20898                pw.println("  cmd may be one of:");
20899                pw.println("    l[ibraries]: list known shared libraries");
20900                pw.println("    f[eatures]: list device features");
20901                pw.println("    k[eysets]: print known keysets");
20902                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20903                pw.println("    perm[issions]: dump permissions");
20904                pw.println("    permission [name ...]: dump declaration and use of given permission");
20905                pw.println("    pref[erred]: print preferred package settings");
20906                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20907                pw.println("    prov[iders]: dump content providers");
20908                pw.println("    p[ackages]: dump installed packages");
20909                pw.println("    s[hared-users]: dump shared user IDs");
20910                pw.println("    m[essages]: print collected runtime messages");
20911                pw.println("    v[erifiers]: print package verifier info");
20912                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20913                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20914                pw.println("    version: print database version info");
20915                pw.println("    write: write current settings now");
20916                pw.println("    installs: details about install sessions");
20917                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20918                pw.println("    dexopt: dump dexopt state");
20919                pw.println("    compiler-stats: dump compiler statistics");
20920                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20921                pw.println("    <package.name>: info about given package");
20922                return;
20923            } else if ("--checkin".equals(opt)) {
20924                checkin = true;
20925            } else if ("-f".equals(opt)) {
20926                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20927            } else if ("--proto".equals(opt)) {
20928                dumpProto(fd);
20929                return;
20930            } else {
20931                pw.println("Unknown argument: " + opt + "; use -h for help");
20932            }
20933        }
20934
20935        // Is the caller requesting to dump a particular piece of data?
20936        if (opti < args.length) {
20937            String cmd = args[opti];
20938            opti++;
20939            // Is this a package name?
20940            if ("android".equals(cmd) || cmd.contains(".")) {
20941                packageName = cmd;
20942                // When dumping a single package, we always dump all of its
20943                // filter information since the amount of data will be reasonable.
20944                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20945            } else if ("check-permission".equals(cmd)) {
20946                if (opti >= args.length) {
20947                    pw.println("Error: check-permission missing permission argument");
20948                    return;
20949                }
20950                String perm = args[opti];
20951                opti++;
20952                if (opti >= args.length) {
20953                    pw.println("Error: check-permission missing package argument");
20954                    return;
20955                }
20956
20957                String pkg = args[opti];
20958                opti++;
20959                int user = UserHandle.getUserId(Binder.getCallingUid());
20960                if (opti < args.length) {
20961                    try {
20962                        user = Integer.parseInt(args[opti]);
20963                    } catch (NumberFormatException e) {
20964                        pw.println("Error: check-permission user argument is not a number: "
20965                                + args[opti]);
20966                        return;
20967                    }
20968                }
20969
20970                // Normalize package name to handle renamed packages and static libs
20971                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20972
20973                pw.println(checkPermission(perm, pkg, user));
20974                return;
20975            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20976                dumpState.setDump(DumpState.DUMP_LIBS);
20977            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20978                dumpState.setDump(DumpState.DUMP_FEATURES);
20979            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20980                if (opti >= args.length) {
20981                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20982                            | DumpState.DUMP_SERVICE_RESOLVERS
20983                            | DumpState.DUMP_RECEIVER_RESOLVERS
20984                            | DumpState.DUMP_CONTENT_RESOLVERS);
20985                } else {
20986                    while (opti < args.length) {
20987                        String name = args[opti];
20988                        if ("a".equals(name) || "activity".equals(name)) {
20989                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20990                        } else if ("s".equals(name) || "service".equals(name)) {
20991                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20992                        } else if ("r".equals(name) || "receiver".equals(name)) {
20993                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20994                        } else if ("c".equals(name) || "content".equals(name)) {
20995                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20996                        } else {
20997                            pw.println("Error: unknown resolver table type: " + name);
20998                            return;
20999                        }
21000                        opti++;
21001                    }
21002                }
21003            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21004                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21005            } else if ("permission".equals(cmd)) {
21006                if (opti >= args.length) {
21007                    pw.println("Error: permission requires permission name");
21008                    return;
21009                }
21010                permissionNames = new ArraySet<>();
21011                while (opti < args.length) {
21012                    permissionNames.add(args[opti]);
21013                    opti++;
21014                }
21015                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21016                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21017            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21018                dumpState.setDump(DumpState.DUMP_PREFERRED);
21019            } else if ("preferred-xml".equals(cmd)) {
21020                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21021                if (opti < args.length && "--full".equals(args[opti])) {
21022                    fullPreferred = true;
21023                    opti++;
21024                }
21025            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21026                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21027            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21028                dumpState.setDump(DumpState.DUMP_PACKAGES);
21029            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21030                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21031            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21032                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21033            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21034                dumpState.setDump(DumpState.DUMP_MESSAGES);
21035            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21036                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21037            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21038                    || "intent-filter-verifiers".equals(cmd)) {
21039                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21040            } else if ("version".equals(cmd)) {
21041                dumpState.setDump(DumpState.DUMP_VERSION);
21042            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21043                dumpState.setDump(DumpState.DUMP_KEYSETS);
21044            } else if ("installs".equals(cmd)) {
21045                dumpState.setDump(DumpState.DUMP_INSTALLS);
21046            } else if ("frozen".equals(cmd)) {
21047                dumpState.setDump(DumpState.DUMP_FROZEN);
21048            } else if ("dexopt".equals(cmd)) {
21049                dumpState.setDump(DumpState.DUMP_DEXOPT);
21050            } else if ("compiler-stats".equals(cmd)) {
21051                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21052            } else if ("enabled-overlays".equals(cmd)) {
21053                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21054            } else if ("changes".equals(cmd)) {
21055                dumpState.setDump(DumpState.DUMP_CHANGES);
21056            } else if ("write".equals(cmd)) {
21057                synchronized (mPackages) {
21058                    mSettings.writeLPr();
21059                    pw.println("Settings written.");
21060                    return;
21061                }
21062            }
21063        }
21064
21065        if (checkin) {
21066            pw.println("vers,1");
21067        }
21068
21069        // reader
21070        synchronized (mPackages) {
21071            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21072                if (!checkin) {
21073                    if (dumpState.onTitlePrinted())
21074                        pw.println();
21075                    pw.println("Database versions:");
21076                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21077                }
21078            }
21079
21080            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21081                if (!checkin) {
21082                    if (dumpState.onTitlePrinted())
21083                        pw.println();
21084                    pw.println("Verifiers:");
21085                    pw.print("  Required: ");
21086                    pw.print(mRequiredVerifierPackage);
21087                    pw.print(" (uid=");
21088                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21089                            UserHandle.USER_SYSTEM));
21090                    pw.println(")");
21091                } else if (mRequiredVerifierPackage != null) {
21092                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21093                    pw.print(",");
21094                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21095                            UserHandle.USER_SYSTEM));
21096                }
21097            }
21098
21099            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21100                    packageName == null) {
21101                if (mIntentFilterVerifierComponent != null) {
21102                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21103                    if (!checkin) {
21104                        if (dumpState.onTitlePrinted())
21105                            pw.println();
21106                        pw.println("Intent Filter Verifier:");
21107                        pw.print("  Using: ");
21108                        pw.print(verifierPackageName);
21109                        pw.print(" (uid=");
21110                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21111                                UserHandle.USER_SYSTEM));
21112                        pw.println(")");
21113                    } else if (verifierPackageName != null) {
21114                        pw.print("ifv,"); pw.print(verifierPackageName);
21115                        pw.print(",");
21116                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21117                                UserHandle.USER_SYSTEM));
21118                    }
21119                } else {
21120                    pw.println();
21121                    pw.println("No Intent Filter Verifier available!");
21122                }
21123            }
21124
21125            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21126                boolean printedHeader = false;
21127                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21128                while (it.hasNext()) {
21129                    String libName = it.next();
21130                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21131                    if (versionedLib == null) {
21132                        continue;
21133                    }
21134                    final int versionCount = versionedLib.size();
21135                    for (int i = 0; i < versionCount; i++) {
21136                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21137                        if (!checkin) {
21138                            if (!printedHeader) {
21139                                if (dumpState.onTitlePrinted())
21140                                    pw.println();
21141                                pw.println("Libraries:");
21142                                printedHeader = true;
21143                            }
21144                            pw.print("  ");
21145                        } else {
21146                            pw.print("lib,");
21147                        }
21148                        pw.print(libEntry.info.getName());
21149                        if (libEntry.info.isStatic()) {
21150                            pw.print(" version=" + libEntry.info.getVersion());
21151                        }
21152                        if (!checkin) {
21153                            pw.print(" -> ");
21154                        }
21155                        if (libEntry.path != null) {
21156                            pw.print(" (jar) ");
21157                            pw.print(libEntry.path);
21158                        } else {
21159                            pw.print(" (apk) ");
21160                            pw.print(libEntry.apk);
21161                        }
21162                        pw.println();
21163                    }
21164                }
21165            }
21166
21167            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21168                if (dumpState.onTitlePrinted())
21169                    pw.println();
21170                if (!checkin) {
21171                    pw.println("Features:");
21172                }
21173
21174                synchronized (mAvailableFeatures) {
21175                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21176                        if (checkin) {
21177                            pw.print("feat,");
21178                            pw.print(feat.name);
21179                            pw.print(",");
21180                            pw.println(feat.version);
21181                        } else {
21182                            pw.print("  ");
21183                            pw.print(feat.name);
21184                            if (feat.version > 0) {
21185                                pw.print(" version=");
21186                                pw.print(feat.version);
21187                            }
21188                            pw.println();
21189                        }
21190                    }
21191                }
21192            }
21193
21194            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21195                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21196                        : "Activity Resolver Table:", "  ", packageName,
21197                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21198                    dumpState.setTitlePrinted(true);
21199                }
21200            }
21201            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21202                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21203                        : "Receiver Resolver Table:", "  ", packageName,
21204                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21205                    dumpState.setTitlePrinted(true);
21206                }
21207            }
21208            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21209                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21210                        : "Service Resolver Table:", "  ", packageName,
21211                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21212                    dumpState.setTitlePrinted(true);
21213                }
21214            }
21215            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21216                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21217                        : "Provider Resolver Table:", "  ", packageName,
21218                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21219                    dumpState.setTitlePrinted(true);
21220                }
21221            }
21222
21223            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21224                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21225                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21226                    int user = mSettings.mPreferredActivities.keyAt(i);
21227                    if (pir.dump(pw,
21228                            dumpState.getTitlePrinted()
21229                                ? "\nPreferred Activities User " + user + ":"
21230                                : "Preferred Activities User " + user + ":", "  ",
21231                            packageName, true, false)) {
21232                        dumpState.setTitlePrinted(true);
21233                    }
21234                }
21235            }
21236
21237            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21238                pw.flush();
21239                FileOutputStream fout = new FileOutputStream(fd);
21240                BufferedOutputStream str = new BufferedOutputStream(fout);
21241                XmlSerializer serializer = new FastXmlSerializer();
21242                try {
21243                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21244                    serializer.startDocument(null, true);
21245                    serializer.setFeature(
21246                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21247                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21248                    serializer.endDocument();
21249                    serializer.flush();
21250                } catch (IllegalArgumentException e) {
21251                    pw.println("Failed writing: " + e);
21252                } catch (IllegalStateException e) {
21253                    pw.println("Failed writing: " + e);
21254                } catch (IOException e) {
21255                    pw.println("Failed writing: " + e);
21256                }
21257            }
21258
21259            if (!checkin
21260                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21261                    && packageName == null) {
21262                pw.println();
21263                int count = mSettings.mPackages.size();
21264                if (count == 0) {
21265                    pw.println("No applications!");
21266                    pw.println();
21267                } else {
21268                    final String prefix = "  ";
21269                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21270                    if (allPackageSettings.size() == 0) {
21271                        pw.println("No domain preferred apps!");
21272                        pw.println();
21273                    } else {
21274                        pw.println("App verification status:");
21275                        pw.println();
21276                        count = 0;
21277                        for (PackageSetting ps : allPackageSettings) {
21278                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21279                            if (ivi == null || ivi.getPackageName() == null) continue;
21280                            pw.println(prefix + "Package: " + ivi.getPackageName());
21281                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21282                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21283                            pw.println();
21284                            count++;
21285                        }
21286                        if (count == 0) {
21287                            pw.println(prefix + "No app verification established.");
21288                            pw.println();
21289                        }
21290                        for (int userId : sUserManager.getUserIds()) {
21291                            pw.println("App linkages for user " + userId + ":");
21292                            pw.println();
21293                            count = 0;
21294                            for (PackageSetting ps : allPackageSettings) {
21295                                final long status = ps.getDomainVerificationStatusForUser(userId);
21296                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21297                                        && !DEBUG_DOMAIN_VERIFICATION) {
21298                                    continue;
21299                                }
21300                                pw.println(prefix + "Package: " + ps.name);
21301                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21302                                String statusStr = IntentFilterVerificationInfo.
21303                                        getStatusStringFromValue(status);
21304                                pw.println(prefix + "Status:  " + statusStr);
21305                                pw.println();
21306                                count++;
21307                            }
21308                            if (count == 0) {
21309                                pw.println(prefix + "No configured app linkages.");
21310                                pw.println();
21311                            }
21312                        }
21313                    }
21314                }
21315            }
21316
21317            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21318                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21319                if (packageName == null && permissionNames == null) {
21320                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21321                        if (iperm == 0) {
21322                            if (dumpState.onTitlePrinted())
21323                                pw.println();
21324                            pw.println("AppOp Permissions:");
21325                        }
21326                        pw.print("  AppOp Permission ");
21327                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21328                        pw.println(":");
21329                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21330                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21331                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21332                        }
21333                    }
21334                }
21335            }
21336
21337            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21338                boolean printedSomething = false;
21339                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21340                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21341                        continue;
21342                    }
21343                    if (!printedSomething) {
21344                        if (dumpState.onTitlePrinted())
21345                            pw.println();
21346                        pw.println("Registered ContentProviders:");
21347                        printedSomething = true;
21348                    }
21349                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21350                    pw.print("    "); pw.println(p.toString());
21351                }
21352                printedSomething = false;
21353                for (Map.Entry<String, PackageParser.Provider> entry :
21354                        mProvidersByAuthority.entrySet()) {
21355                    PackageParser.Provider p = entry.getValue();
21356                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21357                        continue;
21358                    }
21359                    if (!printedSomething) {
21360                        if (dumpState.onTitlePrinted())
21361                            pw.println();
21362                        pw.println("ContentProvider Authorities:");
21363                        printedSomething = true;
21364                    }
21365                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21366                    pw.print("    "); pw.println(p.toString());
21367                    if (p.info != null && p.info.applicationInfo != null) {
21368                        final String appInfo = p.info.applicationInfo.toString();
21369                        pw.print("      applicationInfo="); pw.println(appInfo);
21370                    }
21371                }
21372            }
21373
21374            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21375                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21376            }
21377
21378            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21379                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21380            }
21381
21382            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21383                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21384            }
21385
21386            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21387                if (dumpState.onTitlePrinted()) pw.println();
21388                pw.println("Package Changes:");
21389                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21390                final int K = mChangedPackages.size();
21391                for (int i = 0; i < K; i++) {
21392                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21393                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21394                    final int N = changes.size();
21395                    if (N == 0) {
21396                        pw.print("    "); pw.println("No packages changed");
21397                    } else {
21398                        for (int j = 0; j < N; j++) {
21399                            final String pkgName = changes.valueAt(j);
21400                            final int sequenceNumber = changes.keyAt(j);
21401                            pw.print("    ");
21402                            pw.print("seq=");
21403                            pw.print(sequenceNumber);
21404                            pw.print(", package=");
21405                            pw.println(pkgName);
21406                        }
21407                    }
21408                }
21409            }
21410
21411            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21412                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21413            }
21414
21415            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21416                // XXX should handle packageName != null by dumping only install data that
21417                // the given package is involved with.
21418                if (dumpState.onTitlePrinted()) pw.println();
21419
21420                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21421                ipw.println();
21422                ipw.println("Frozen packages:");
21423                ipw.increaseIndent();
21424                if (mFrozenPackages.size() == 0) {
21425                    ipw.println("(none)");
21426                } else {
21427                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21428                        ipw.println(mFrozenPackages.valueAt(i));
21429                    }
21430                }
21431                ipw.decreaseIndent();
21432            }
21433
21434            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21435                if (dumpState.onTitlePrinted()) pw.println();
21436                dumpDexoptStateLPr(pw, packageName);
21437            }
21438
21439            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21440                if (dumpState.onTitlePrinted()) pw.println();
21441                dumpCompilerStatsLPr(pw, packageName);
21442            }
21443
21444            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21445                if (dumpState.onTitlePrinted()) pw.println();
21446                dumpEnabledOverlaysLPr(pw);
21447            }
21448
21449            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21450                if (dumpState.onTitlePrinted()) pw.println();
21451                mSettings.dumpReadMessagesLPr(pw, dumpState);
21452
21453                pw.println();
21454                pw.println("Package warning messages:");
21455                BufferedReader in = null;
21456                String line = null;
21457                try {
21458                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21459                    while ((line = in.readLine()) != null) {
21460                        if (line.contains("ignored: updated version")) continue;
21461                        pw.println(line);
21462                    }
21463                } catch (IOException ignored) {
21464                } finally {
21465                    IoUtils.closeQuietly(in);
21466                }
21467            }
21468
21469            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21470                BufferedReader in = null;
21471                String line = null;
21472                try {
21473                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21474                    while ((line = in.readLine()) != null) {
21475                        if (line.contains("ignored: updated version")) continue;
21476                        pw.print("msg,");
21477                        pw.println(line);
21478                    }
21479                } catch (IOException ignored) {
21480                } finally {
21481                    IoUtils.closeQuietly(in);
21482                }
21483            }
21484        }
21485
21486        // PackageInstaller should be called outside of mPackages lock
21487        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21488            // XXX should handle packageName != null by dumping only install data that
21489            // the given package is involved with.
21490            if (dumpState.onTitlePrinted()) pw.println();
21491            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21492        }
21493    }
21494
21495    private void dumpProto(FileDescriptor fd) {
21496        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21497
21498        synchronized (mPackages) {
21499            final long requiredVerifierPackageToken =
21500                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21501            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21502            proto.write(
21503                    PackageServiceDumpProto.PackageShortProto.UID,
21504                    getPackageUid(
21505                            mRequiredVerifierPackage,
21506                            MATCH_DEBUG_TRIAGED_MISSING,
21507                            UserHandle.USER_SYSTEM));
21508            proto.end(requiredVerifierPackageToken);
21509
21510            if (mIntentFilterVerifierComponent != null) {
21511                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21512                final long verifierPackageToken =
21513                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21514                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21515                proto.write(
21516                        PackageServiceDumpProto.PackageShortProto.UID,
21517                        getPackageUid(
21518                                verifierPackageName,
21519                                MATCH_DEBUG_TRIAGED_MISSING,
21520                                UserHandle.USER_SYSTEM));
21521                proto.end(verifierPackageToken);
21522            }
21523
21524            dumpSharedLibrariesProto(proto);
21525            dumpFeaturesProto(proto);
21526            mSettings.dumpPackagesProto(proto);
21527            mSettings.dumpSharedUsersProto(proto);
21528            dumpMessagesProto(proto);
21529        }
21530        proto.flush();
21531    }
21532
21533    private void dumpMessagesProto(ProtoOutputStream proto) {
21534        BufferedReader in = null;
21535        String line = null;
21536        try {
21537            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21538            while ((line = in.readLine()) != null) {
21539                if (line.contains("ignored: updated version")) continue;
21540                proto.write(PackageServiceDumpProto.MESSAGES, line);
21541            }
21542        } catch (IOException ignored) {
21543        } finally {
21544            IoUtils.closeQuietly(in);
21545        }
21546    }
21547
21548    private void dumpFeaturesProto(ProtoOutputStream proto) {
21549        synchronized (mAvailableFeatures) {
21550            final int count = mAvailableFeatures.size();
21551            for (int i = 0; i < count; i++) {
21552                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21553                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21554                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21555                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21556                proto.end(featureToken);
21557            }
21558        }
21559    }
21560
21561    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21562        final int count = mSharedLibraries.size();
21563        for (int i = 0; i < count; i++) {
21564            final String libName = mSharedLibraries.keyAt(i);
21565            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21566            if (versionedLib == null) {
21567                continue;
21568            }
21569            final int versionCount = versionedLib.size();
21570            for (int j = 0; j < versionCount; j++) {
21571                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21572                final long sharedLibraryToken =
21573                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21574                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21575                final boolean isJar = (libEntry.path != null);
21576                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21577                if (isJar) {
21578                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21579                } else {
21580                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21581                }
21582                proto.end(sharedLibraryToken);
21583            }
21584        }
21585    }
21586
21587    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21588        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21589        ipw.println();
21590        ipw.println("Dexopt state:");
21591        ipw.increaseIndent();
21592        Collection<PackageParser.Package> packages = null;
21593        if (packageName != null) {
21594            PackageParser.Package targetPackage = mPackages.get(packageName);
21595            if (targetPackage != null) {
21596                packages = Collections.singletonList(targetPackage);
21597            } else {
21598                ipw.println("Unable to find package: " + packageName);
21599                return;
21600            }
21601        } else {
21602            packages = mPackages.values();
21603        }
21604
21605        for (PackageParser.Package pkg : packages) {
21606            ipw.println("[" + pkg.packageName + "]");
21607            ipw.increaseIndent();
21608            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21609            ipw.decreaseIndent();
21610        }
21611    }
21612
21613    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21614        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21615        ipw.println();
21616        ipw.println("Compiler stats:");
21617        ipw.increaseIndent();
21618        Collection<PackageParser.Package> packages = null;
21619        if (packageName != null) {
21620            PackageParser.Package targetPackage = mPackages.get(packageName);
21621            if (targetPackage != null) {
21622                packages = Collections.singletonList(targetPackage);
21623            } else {
21624                ipw.println("Unable to find package: " + packageName);
21625                return;
21626            }
21627        } else {
21628            packages = mPackages.values();
21629        }
21630
21631        for (PackageParser.Package pkg : packages) {
21632            ipw.println("[" + pkg.packageName + "]");
21633            ipw.increaseIndent();
21634
21635            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21636            if (stats == null) {
21637                ipw.println("(No recorded stats)");
21638            } else {
21639                stats.dump(ipw);
21640            }
21641            ipw.decreaseIndent();
21642        }
21643    }
21644
21645    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21646        pw.println("Enabled overlay paths:");
21647        final int N = mEnabledOverlayPaths.size();
21648        for (int i = 0; i < N; i++) {
21649            final int userId = mEnabledOverlayPaths.keyAt(i);
21650            pw.println(String.format("    User %d:", userId));
21651            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21652                mEnabledOverlayPaths.valueAt(i);
21653            final int M = userSpecificOverlays.size();
21654            for (int j = 0; j < M; j++) {
21655                final String targetPackageName = userSpecificOverlays.keyAt(j);
21656                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21657                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21658            }
21659        }
21660    }
21661
21662    private String dumpDomainString(String packageName) {
21663        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21664                .getList();
21665        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21666
21667        ArraySet<String> result = new ArraySet<>();
21668        if (iviList.size() > 0) {
21669            for (IntentFilterVerificationInfo ivi : iviList) {
21670                for (String host : ivi.getDomains()) {
21671                    result.add(host);
21672                }
21673            }
21674        }
21675        if (filters != null && filters.size() > 0) {
21676            for (IntentFilter filter : filters) {
21677                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21678                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21679                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21680                    result.addAll(filter.getHostsList());
21681                }
21682            }
21683        }
21684
21685        StringBuilder sb = new StringBuilder(result.size() * 16);
21686        for (String domain : result) {
21687            if (sb.length() > 0) sb.append(" ");
21688            sb.append(domain);
21689        }
21690        return sb.toString();
21691    }
21692
21693    // ------- apps on sdcard specific code -------
21694    static final boolean DEBUG_SD_INSTALL = false;
21695
21696    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21697
21698    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21699
21700    private boolean mMediaMounted = false;
21701
21702    static String getEncryptKey() {
21703        try {
21704            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21705                    SD_ENCRYPTION_KEYSTORE_NAME);
21706            if (sdEncKey == null) {
21707                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21708                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21709                if (sdEncKey == null) {
21710                    Slog.e(TAG, "Failed to create encryption keys");
21711                    return null;
21712                }
21713            }
21714            return sdEncKey;
21715        } catch (NoSuchAlgorithmException nsae) {
21716            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21717            return null;
21718        } catch (IOException ioe) {
21719            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21720            return null;
21721        }
21722    }
21723
21724    /*
21725     * Update media status on PackageManager.
21726     */
21727    @Override
21728    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21729        int callingUid = Binder.getCallingUid();
21730        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21731            throw new SecurityException("Media status can only be updated by the system");
21732        }
21733        // reader; this apparently protects mMediaMounted, but should probably
21734        // be a different lock in that case.
21735        synchronized (mPackages) {
21736            Log.i(TAG, "Updating external media status from "
21737                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21738                    + (mediaStatus ? "mounted" : "unmounted"));
21739            if (DEBUG_SD_INSTALL)
21740                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21741                        + ", mMediaMounted=" + mMediaMounted);
21742            if (mediaStatus == mMediaMounted) {
21743                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21744                        : 0, -1);
21745                mHandler.sendMessage(msg);
21746                return;
21747            }
21748            mMediaMounted = mediaStatus;
21749        }
21750        // Queue up an async operation since the package installation may take a
21751        // little while.
21752        mHandler.post(new Runnable() {
21753            public void run() {
21754                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21755            }
21756        });
21757    }
21758
21759    /**
21760     * Called by StorageManagerService when the initial ASECs to scan are available.
21761     * Should block until all the ASEC containers are finished being scanned.
21762     */
21763    public void scanAvailableAsecs() {
21764        updateExternalMediaStatusInner(true, false, false);
21765    }
21766
21767    /*
21768     * Collect information of applications on external media, map them against
21769     * existing containers and update information based on current mount status.
21770     * Please note that we always have to report status if reportStatus has been
21771     * set to true especially when unloading packages.
21772     */
21773    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21774            boolean externalStorage) {
21775        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21776        int[] uidArr = EmptyArray.INT;
21777
21778        final String[] list = PackageHelper.getSecureContainerList();
21779        if (ArrayUtils.isEmpty(list)) {
21780            Log.i(TAG, "No secure containers found");
21781        } else {
21782            // Process list of secure containers and categorize them
21783            // as active or stale based on their package internal state.
21784
21785            // reader
21786            synchronized (mPackages) {
21787                for (String cid : list) {
21788                    // Leave stages untouched for now; installer service owns them
21789                    if (PackageInstallerService.isStageName(cid)) continue;
21790
21791                    if (DEBUG_SD_INSTALL)
21792                        Log.i(TAG, "Processing container " + cid);
21793                    String pkgName = getAsecPackageName(cid);
21794                    if (pkgName == null) {
21795                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21796                        continue;
21797                    }
21798                    if (DEBUG_SD_INSTALL)
21799                        Log.i(TAG, "Looking for pkg : " + pkgName);
21800
21801                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21802                    if (ps == null) {
21803                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21804                        continue;
21805                    }
21806
21807                    /*
21808                     * Skip packages that are not external if we're unmounting
21809                     * external storage.
21810                     */
21811                    if (externalStorage && !isMounted && !isExternal(ps)) {
21812                        continue;
21813                    }
21814
21815                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21816                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21817                    // The package status is changed only if the code path
21818                    // matches between settings and the container id.
21819                    if (ps.codePathString != null
21820                            && ps.codePathString.startsWith(args.getCodePath())) {
21821                        if (DEBUG_SD_INSTALL) {
21822                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21823                                    + " at code path: " + ps.codePathString);
21824                        }
21825
21826                        // We do have a valid package installed on sdcard
21827                        processCids.put(args, ps.codePathString);
21828                        final int uid = ps.appId;
21829                        if (uid != -1) {
21830                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21831                        }
21832                    } else {
21833                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21834                                + ps.codePathString);
21835                    }
21836                }
21837            }
21838
21839            Arrays.sort(uidArr);
21840        }
21841
21842        // Process packages with valid entries.
21843        if (isMounted) {
21844            if (DEBUG_SD_INSTALL)
21845                Log.i(TAG, "Loading packages");
21846            loadMediaPackages(processCids, uidArr, externalStorage);
21847            startCleaningPackages();
21848            mInstallerService.onSecureContainersAvailable();
21849        } else {
21850            if (DEBUG_SD_INSTALL)
21851                Log.i(TAG, "Unloading packages");
21852            unloadMediaPackages(processCids, uidArr, reportStatus);
21853        }
21854    }
21855
21856    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21857            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21858        final int size = infos.size();
21859        final String[] packageNames = new String[size];
21860        final int[] packageUids = new int[size];
21861        for (int i = 0; i < size; i++) {
21862            final ApplicationInfo info = infos.get(i);
21863            packageNames[i] = info.packageName;
21864            packageUids[i] = info.uid;
21865        }
21866        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21867                finishedReceiver);
21868    }
21869
21870    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21871            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21872        sendResourcesChangedBroadcast(mediaStatus, replacing,
21873                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21874    }
21875
21876    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21877            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21878        int size = pkgList.length;
21879        if (size > 0) {
21880            // Send broadcasts here
21881            Bundle extras = new Bundle();
21882            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21883            if (uidArr != null) {
21884                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21885            }
21886            if (replacing) {
21887                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21888            }
21889            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21890                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21891            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21892        }
21893    }
21894
21895   /*
21896     * Look at potentially valid container ids from processCids If package
21897     * information doesn't match the one on record or package scanning fails,
21898     * the cid is added to list of removeCids. We currently don't delete stale
21899     * containers.
21900     */
21901    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21902            boolean externalStorage) {
21903        ArrayList<String> pkgList = new ArrayList<String>();
21904        Set<AsecInstallArgs> keys = processCids.keySet();
21905
21906        for (AsecInstallArgs args : keys) {
21907            String codePath = processCids.get(args);
21908            if (DEBUG_SD_INSTALL)
21909                Log.i(TAG, "Loading container : " + args.cid);
21910            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21911            try {
21912                // Make sure there are no container errors first.
21913                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21914                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21915                            + " when installing from sdcard");
21916                    continue;
21917                }
21918                // Check code path here.
21919                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21920                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21921                            + " does not match one in settings " + codePath);
21922                    continue;
21923                }
21924                // Parse package
21925                int parseFlags = mDefParseFlags;
21926                if (args.isExternalAsec()) {
21927                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21928                }
21929                if (args.isFwdLocked()) {
21930                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21931                }
21932
21933                synchronized (mInstallLock) {
21934                    PackageParser.Package pkg = null;
21935                    try {
21936                        // Sadly we don't know the package name yet to freeze it
21937                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21938                                SCAN_IGNORE_FROZEN, 0, null);
21939                    } catch (PackageManagerException e) {
21940                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21941                    }
21942                    // Scan the package
21943                    if (pkg != null) {
21944                        /*
21945                         * TODO why is the lock being held? doPostInstall is
21946                         * called in other places without the lock. This needs
21947                         * to be straightened out.
21948                         */
21949                        // writer
21950                        synchronized (mPackages) {
21951                            retCode = PackageManager.INSTALL_SUCCEEDED;
21952                            pkgList.add(pkg.packageName);
21953                            // Post process args
21954                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21955                                    pkg.applicationInfo.uid);
21956                        }
21957                    } else {
21958                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21959                    }
21960                }
21961
21962            } finally {
21963                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21964                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21965                }
21966            }
21967        }
21968        // writer
21969        synchronized (mPackages) {
21970            // If the platform SDK has changed since the last time we booted,
21971            // we need to re-grant app permission to catch any new ones that
21972            // appear. This is really a hack, and means that apps can in some
21973            // cases get permissions that the user didn't initially explicitly
21974            // allow... it would be nice to have some better way to handle
21975            // this situation.
21976            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21977                    : mSettings.getInternalVersion();
21978            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21979                    : StorageManager.UUID_PRIVATE_INTERNAL;
21980
21981            int updateFlags = UPDATE_PERMISSIONS_ALL;
21982            if (ver.sdkVersion != mSdkVersion) {
21983                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21984                        + mSdkVersion + "; regranting permissions for external");
21985                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21986            }
21987            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21988
21989            // Yay, everything is now upgraded
21990            ver.forceCurrent();
21991
21992            // can downgrade to reader
21993            // Persist settings
21994            mSettings.writeLPr();
21995        }
21996        // Send a broadcast to let everyone know we are done processing
21997        if (pkgList.size() > 0) {
21998            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21999        }
22000    }
22001
22002   /*
22003     * Utility method to unload a list of specified containers
22004     */
22005    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22006        // Just unmount all valid containers.
22007        for (AsecInstallArgs arg : cidArgs) {
22008            synchronized (mInstallLock) {
22009                arg.doPostDeleteLI(false);
22010           }
22011       }
22012   }
22013
22014    /*
22015     * Unload packages mounted on external media. This involves deleting package
22016     * data from internal structures, sending broadcasts about disabled packages,
22017     * gc'ing to free up references, unmounting all secure containers
22018     * corresponding to packages on external media, and posting a
22019     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22020     * that we always have to post this message if status has been requested no
22021     * matter what.
22022     */
22023    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22024            final boolean reportStatus) {
22025        if (DEBUG_SD_INSTALL)
22026            Log.i(TAG, "unloading media packages");
22027        ArrayList<String> pkgList = new ArrayList<String>();
22028        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22029        final Set<AsecInstallArgs> keys = processCids.keySet();
22030        for (AsecInstallArgs args : keys) {
22031            String pkgName = args.getPackageName();
22032            if (DEBUG_SD_INSTALL)
22033                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22034            // Delete package internally
22035            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22036            synchronized (mInstallLock) {
22037                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22038                final boolean res;
22039                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22040                        "unloadMediaPackages")) {
22041                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22042                            null);
22043                }
22044                if (res) {
22045                    pkgList.add(pkgName);
22046                } else {
22047                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22048                    failedList.add(args);
22049                }
22050            }
22051        }
22052
22053        // reader
22054        synchronized (mPackages) {
22055            // We didn't update the settings after removing each package;
22056            // write them now for all packages.
22057            mSettings.writeLPr();
22058        }
22059
22060        // We have to absolutely send UPDATED_MEDIA_STATUS only
22061        // after confirming that all the receivers processed the ordered
22062        // broadcast when packages get disabled, force a gc to clean things up.
22063        // and unload all the containers.
22064        if (pkgList.size() > 0) {
22065            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22066                    new IIntentReceiver.Stub() {
22067                public void performReceive(Intent intent, int resultCode, String data,
22068                        Bundle extras, boolean ordered, boolean sticky,
22069                        int sendingUser) throws RemoteException {
22070                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22071                            reportStatus ? 1 : 0, 1, keys);
22072                    mHandler.sendMessage(msg);
22073                }
22074            });
22075        } else {
22076            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22077                    keys);
22078            mHandler.sendMessage(msg);
22079        }
22080    }
22081
22082    private void loadPrivatePackages(final VolumeInfo vol) {
22083        mHandler.post(new Runnable() {
22084            @Override
22085            public void run() {
22086                loadPrivatePackagesInner(vol);
22087            }
22088        });
22089    }
22090
22091    private void loadPrivatePackagesInner(VolumeInfo vol) {
22092        final String volumeUuid = vol.fsUuid;
22093        if (TextUtils.isEmpty(volumeUuid)) {
22094            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22095            return;
22096        }
22097
22098        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22099        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22100        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22101
22102        final VersionInfo ver;
22103        final List<PackageSetting> packages;
22104        synchronized (mPackages) {
22105            ver = mSettings.findOrCreateVersion(volumeUuid);
22106            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22107        }
22108
22109        for (PackageSetting ps : packages) {
22110            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22111            synchronized (mInstallLock) {
22112                final PackageParser.Package pkg;
22113                try {
22114                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22115                    loaded.add(pkg.applicationInfo);
22116
22117                } catch (PackageManagerException e) {
22118                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22119                }
22120
22121                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22122                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22123                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22124                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22125                }
22126            }
22127        }
22128
22129        // Reconcile app data for all started/unlocked users
22130        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22131        final UserManager um = mContext.getSystemService(UserManager.class);
22132        UserManagerInternal umInternal = getUserManagerInternal();
22133        for (UserInfo user : um.getUsers()) {
22134            final int flags;
22135            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22136                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22137            } else if (umInternal.isUserRunning(user.id)) {
22138                flags = StorageManager.FLAG_STORAGE_DE;
22139            } else {
22140                continue;
22141            }
22142
22143            try {
22144                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22145                synchronized (mInstallLock) {
22146                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22147                }
22148            } catch (IllegalStateException e) {
22149                // Device was probably ejected, and we'll process that event momentarily
22150                Slog.w(TAG, "Failed to prepare storage: " + e);
22151            }
22152        }
22153
22154        synchronized (mPackages) {
22155            int updateFlags = UPDATE_PERMISSIONS_ALL;
22156            if (ver.sdkVersion != mSdkVersion) {
22157                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22158                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22159                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22160            }
22161            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22162
22163            // Yay, everything is now upgraded
22164            ver.forceCurrent();
22165
22166            mSettings.writeLPr();
22167        }
22168
22169        for (PackageFreezer freezer : freezers) {
22170            freezer.close();
22171        }
22172
22173        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22174        sendResourcesChangedBroadcast(true, false, loaded, null);
22175    }
22176
22177    private void unloadPrivatePackages(final VolumeInfo vol) {
22178        mHandler.post(new Runnable() {
22179            @Override
22180            public void run() {
22181                unloadPrivatePackagesInner(vol);
22182            }
22183        });
22184    }
22185
22186    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22187        final String volumeUuid = vol.fsUuid;
22188        if (TextUtils.isEmpty(volumeUuid)) {
22189            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22190            return;
22191        }
22192
22193        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22194        synchronized (mInstallLock) {
22195        synchronized (mPackages) {
22196            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22197            for (PackageSetting ps : packages) {
22198                if (ps.pkg == null) continue;
22199
22200                final ApplicationInfo info = ps.pkg.applicationInfo;
22201                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22202                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22203
22204                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22205                        "unloadPrivatePackagesInner")) {
22206                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22207                            false, null)) {
22208                        unloaded.add(info);
22209                    } else {
22210                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22211                    }
22212                }
22213
22214                // Try very hard to release any references to this package
22215                // so we don't risk the system server being killed due to
22216                // open FDs
22217                AttributeCache.instance().removePackage(ps.name);
22218            }
22219
22220            mSettings.writeLPr();
22221        }
22222        }
22223
22224        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22225        sendResourcesChangedBroadcast(false, false, unloaded, null);
22226
22227        // Try very hard to release any references to this path so we don't risk
22228        // the system server being killed due to open FDs
22229        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22230
22231        for (int i = 0; i < 3; i++) {
22232            System.gc();
22233            System.runFinalization();
22234        }
22235    }
22236
22237    private void assertPackageKnown(String volumeUuid, String packageName)
22238            throws PackageManagerException {
22239        synchronized (mPackages) {
22240            // Normalize package name to handle renamed packages
22241            packageName = normalizePackageNameLPr(packageName);
22242
22243            final PackageSetting ps = mSettings.mPackages.get(packageName);
22244            if (ps == null) {
22245                throw new PackageManagerException("Package " + packageName + " is unknown");
22246            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22247                throw new PackageManagerException(
22248                        "Package " + packageName + " found on unknown volume " + volumeUuid
22249                                + "; expected volume " + ps.volumeUuid);
22250            }
22251        }
22252    }
22253
22254    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22255            throws PackageManagerException {
22256        synchronized (mPackages) {
22257            // Normalize package name to handle renamed packages
22258            packageName = normalizePackageNameLPr(packageName);
22259
22260            final PackageSetting ps = mSettings.mPackages.get(packageName);
22261            if (ps == null) {
22262                throw new PackageManagerException("Package " + packageName + " is unknown");
22263            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22264                throw new PackageManagerException(
22265                        "Package " + packageName + " found on unknown volume " + volumeUuid
22266                                + "; expected volume " + ps.volumeUuid);
22267            } else if (!ps.getInstalled(userId)) {
22268                throw new PackageManagerException(
22269                        "Package " + packageName + " not installed for user " + userId);
22270            }
22271        }
22272    }
22273
22274    private List<String> collectAbsoluteCodePaths() {
22275        synchronized (mPackages) {
22276            List<String> codePaths = new ArrayList<>();
22277            final int packageCount = mSettings.mPackages.size();
22278            for (int i = 0; i < packageCount; i++) {
22279                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22280                codePaths.add(ps.codePath.getAbsolutePath());
22281            }
22282            return codePaths;
22283        }
22284    }
22285
22286    /**
22287     * Examine all apps present on given mounted volume, and destroy apps that
22288     * aren't expected, either due to uninstallation or reinstallation on
22289     * another volume.
22290     */
22291    private void reconcileApps(String volumeUuid) {
22292        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22293        List<File> filesToDelete = null;
22294
22295        final File[] files = FileUtils.listFilesOrEmpty(
22296                Environment.getDataAppDirectory(volumeUuid));
22297        for (File file : files) {
22298            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22299                    && !PackageInstallerService.isStageName(file.getName());
22300            if (!isPackage) {
22301                // Ignore entries which are not packages
22302                continue;
22303            }
22304
22305            String absolutePath = file.getAbsolutePath();
22306
22307            boolean pathValid = false;
22308            final int absoluteCodePathCount = absoluteCodePaths.size();
22309            for (int i = 0; i < absoluteCodePathCount; i++) {
22310                String absoluteCodePath = absoluteCodePaths.get(i);
22311                if (absolutePath.startsWith(absoluteCodePath)) {
22312                    pathValid = true;
22313                    break;
22314                }
22315            }
22316
22317            if (!pathValid) {
22318                if (filesToDelete == null) {
22319                    filesToDelete = new ArrayList<>();
22320                }
22321                filesToDelete.add(file);
22322            }
22323        }
22324
22325        if (filesToDelete != null) {
22326            final int fileToDeleteCount = filesToDelete.size();
22327            for (int i = 0; i < fileToDeleteCount; i++) {
22328                File fileToDelete = filesToDelete.get(i);
22329                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22330                synchronized (mInstallLock) {
22331                    removeCodePathLI(fileToDelete);
22332                }
22333            }
22334        }
22335    }
22336
22337    /**
22338     * Reconcile all app data for the given user.
22339     * <p>
22340     * Verifies that directories exist and that ownership and labeling is
22341     * correct for all installed apps on all mounted volumes.
22342     */
22343    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22344        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22345        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22346            final String volumeUuid = vol.getFsUuid();
22347            synchronized (mInstallLock) {
22348                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22349            }
22350        }
22351    }
22352
22353    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22354            boolean migrateAppData) {
22355        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22356    }
22357
22358    /**
22359     * Reconcile all app data on given mounted volume.
22360     * <p>
22361     * Destroys app data that isn't expected, either due to uninstallation or
22362     * reinstallation on another volume.
22363     * <p>
22364     * Verifies that directories exist and that ownership and labeling is
22365     * correct for all installed apps.
22366     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22367     */
22368    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22369            boolean migrateAppData, boolean onlyCoreApps) {
22370        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22371                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22372        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22373
22374        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22375        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22376
22377        // First look for stale data that doesn't belong, and check if things
22378        // have changed since we did our last restorecon
22379        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22380            if (StorageManager.isFileEncryptedNativeOrEmulated()
22381                    && !StorageManager.isUserKeyUnlocked(userId)) {
22382                throw new RuntimeException(
22383                        "Yikes, someone asked us to reconcile CE storage while " + userId
22384                                + " was still locked; this would have caused massive data loss!");
22385            }
22386
22387            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22388            for (File file : files) {
22389                final String packageName = file.getName();
22390                try {
22391                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22392                } catch (PackageManagerException e) {
22393                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22394                    try {
22395                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22396                                StorageManager.FLAG_STORAGE_CE, 0);
22397                    } catch (InstallerException e2) {
22398                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22399                    }
22400                }
22401            }
22402        }
22403        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22404            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22405            for (File file : files) {
22406                final String packageName = file.getName();
22407                try {
22408                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22409                } catch (PackageManagerException e) {
22410                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22411                    try {
22412                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22413                                StorageManager.FLAG_STORAGE_DE, 0);
22414                    } catch (InstallerException e2) {
22415                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22416                    }
22417                }
22418            }
22419        }
22420
22421        // Ensure that data directories are ready to roll for all packages
22422        // installed for this volume and user
22423        final List<PackageSetting> packages;
22424        synchronized (mPackages) {
22425            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22426        }
22427        int preparedCount = 0;
22428        for (PackageSetting ps : packages) {
22429            final String packageName = ps.name;
22430            if (ps.pkg == null) {
22431                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22432                // TODO: might be due to legacy ASEC apps; we should circle back
22433                // and reconcile again once they're scanned
22434                continue;
22435            }
22436            // Skip non-core apps if requested
22437            if (onlyCoreApps && !ps.pkg.coreApp) {
22438                result.add(packageName);
22439                continue;
22440            }
22441
22442            if (ps.getInstalled(userId)) {
22443                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22444                preparedCount++;
22445            }
22446        }
22447
22448        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22449        return result;
22450    }
22451
22452    /**
22453     * Prepare app data for the given app just after it was installed or
22454     * upgraded. This method carefully only touches users that it's installed
22455     * for, and it forces a restorecon to handle any seinfo changes.
22456     * <p>
22457     * Verifies that directories exist and that ownership and labeling is
22458     * correct for all installed apps. If there is an ownership mismatch, it
22459     * will try recovering system apps by wiping data; third-party app data is
22460     * left intact.
22461     * <p>
22462     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22463     */
22464    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22465        final PackageSetting ps;
22466        synchronized (mPackages) {
22467            ps = mSettings.mPackages.get(pkg.packageName);
22468            mSettings.writeKernelMappingLPr(ps);
22469        }
22470
22471        final UserManager um = mContext.getSystemService(UserManager.class);
22472        UserManagerInternal umInternal = getUserManagerInternal();
22473        for (UserInfo user : um.getUsers()) {
22474            final int flags;
22475            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22476                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22477            } else if (umInternal.isUserRunning(user.id)) {
22478                flags = StorageManager.FLAG_STORAGE_DE;
22479            } else {
22480                continue;
22481            }
22482
22483            if (ps.getInstalled(user.id)) {
22484                // TODO: when user data is locked, mark that we're still dirty
22485                prepareAppDataLIF(pkg, user.id, flags);
22486            }
22487        }
22488    }
22489
22490    /**
22491     * Prepare app data for the given app.
22492     * <p>
22493     * Verifies that directories exist and that ownership and labeling is
22494     * correct for all installed apps. If there is an ownership mismatch, this
22495     * will try recovering system apps by wiping data; third-party app data is
22496     * left intact.
22497     */
22498    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22499        if (pkg == null) {
22500            Slog.wtf(TAG, "Package was null!", new Throwable());
22501            return;
22502        }
22503        prepareAppDataLeafLIF(pkg, userId, flags);
22504        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22505        for (int i = 0; i < childCount; i++) {
22506            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22507        }
22508    }
22509
22510    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22511            boolean maybeMigrateAppData) {
22512        prepareAppDataLIF(pkg, userId, flags);
22513
22514        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22515            // We may have just shuffled around app data directories, so
22516            // prepare them one more time
22517            prepareAppDataLIF(pkg, userId, flags);
22518        }
22519    }
22520
22521    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22522        if (DEBUG_APP_DATA) {
22523            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22524                    + Integer.toHexString(flags));
22525        }
22526
22527        final String volumeUuid = pkg.volumeUuid;
22528        final String packageName = pkg.packageName;
22529        final ApplicationInfo app = pkg.applicationInfo;
22530        final int appId = UserHandle.getAppId(app.uid);
22531
22532        Preconditions.checkNotNull(app.seInfo);
22533
22534        long ceDataInode = -1;
22535        try {
22536            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22537                    appId, app.seInfo, app.targetSdkVersion);
22538        } catch (InstallerException e) {
22539            if (app.isSystemApp()) {
22540                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22541                        + ", but trying to recover: " + e);
22542                destroyAppDataLeafLIF(pkg, userId, flags);
22543                try {
22544                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22545                            appId, app.seInfo, app.targetSdkVersion);
22546                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22547                } catch (InstallerException e2) {
22548                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22549                }
22550            } else {
22551                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22552            }
22553        }
22554
22555        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22556            // TODO: mark this structure as dirty so we persist it!
22557            synchronized (mPackages) {
22558                final PackageSetting ps = mSettings.mPackages.get(packageName);
22559                if (ps != null) {
22560                    ps.setCeDataInode(ceDataInode, userId);
22561                }
22562            }
22563        }
22564
22565        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22566    }
22567
22568    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22569        if (pkg == null) {
22570            Slog.wtf(TAG, "Package was null!", new Throwable());
22571            return;
22572        }
22573        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22574        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22575        for (int i = 0; i < childCount; i++) {
22576            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22577        }
22578    }
22579
22580    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22581        final String volumeUuid = pkg.volumeUuid;
22582        final String packageName = pkg.packageName;
22583        final ApplicationInfo app = pkg.applicationInfo;
22584
22585        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22586            // Create a native library symlink only if we have native libraries
22587            // and if the native libraries are 32 bit libraries. We do not provide
22588            // this symlink for 64 bit libraries.
22589            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22590                final String nativeLibPath = app.nativeLibraryDir;
22591                try {
22592                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22593                            nativeLibPath, userId);
22594                } catch (InstallerException e) {
22595                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22596                }
22597            }
22598        }
22599    }
22600
22601    /**
22602     * For system apps on non-FBE devices, this method migrates any existing
22603     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22604     * requested by the app.
22605     */
22606    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22607        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22608                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22609            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22610                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22611            try {
22612                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22613                        storageTarget);
22614            } catch (InstallerException e) {
22615                logCriticalInfo(Log.WARN,
22616                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22617            }
22618            return true;
22619        } else {
22620            return false;
22621        }
22622    }
22623
22624    public PackageFreezer freezePackage(String packageName, String killReason) {
22625        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22626    }
22627
22628    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22629        return new PackageFreezer(packageName, userId, killReason);
22630    }
22631
22632    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22633            String killReason) {
22634        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22635    }
22636
22637    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22638            String killReason) {
22639        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22640            return new PackageFreezer();
22641        } else {
22642            return freezePackage(packageName, userId, killReason);
22643        }
22644    }
22645
22646    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22647            String killReason) {
22648        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22649    }
22650
22651    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22652            String killReason) {
22653        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22654            return new PackageFreezer();
22655        } else {
22656            return freezePackage(packageName, userId, killReason);
22657        }
22658    }
22659
22660    /**
22661     * Class that freezes and kills the given package upon creation, and
22662     * unfreezes it upon closing. This is typically used when doing surgery on
22663     * app code/data to prevent the app from running while you're working.
22664     */
22665    private class PackageFreezer implements AutoCloseable {
22666        private final String mPackageName;
22667        private final PackageFreezer[] mChildren;
22668
22669        private final boolean mWeFroze;
22670
22671        private final AtomicBoolean mClosed = new AtomicBoolean();
22672        private final CloseGuard mCloseGuard = CloseGuard.get();
22673
22674        /**
22675         * Create and return a stub freezer that doesn't actually do anything,
22676         * typically used when someone requested
22677         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22678         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22679         */
22680        public PackageFreezer() {
22681            mPackageName = null;
22682            mChildren = null;
22683            mWeFroze = false;
22684            mCloseGuard.open("close");
22685        }
22686
22687        public PackageFreezer(String packageName, int userId, String killReason) {
22688            synchronized (mPackages) {
22689                mPackageName = packageName;
22690                mWeFroze = mFrozenPackages.add(mPackageName);
22691
22692                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22693                if (ps != null) {
22694                    killApplication(ps.name, ps.appId, userId, killReason);
22695                }
22696
22697                final PackageParser.Package p = mPackages.get(packageName);
22698                if (p != null && p.childPackages != null) {
22699                    final int N = p.childPackages.size();
22700                    mChildren = new PackageFreezer[N];
22701                    for (int i = 0; i < N; i++) {
22702                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22703                                userId, killReason);
22704                    }
22705                } else {
22706                    mChildren = null;
22707                }
22708            }
22709            mCloseGuard.open("close");
22710        }
22711
22712        @Override
22713        protected void finalize() throws Throwable {
22714            try {
22715                mCloseGuard.warnIfOpen();
22716                close();
22717            } finally {
22718                super.finalize();
22719            }
22720        }
22721
22722        @Override
22723        public void close() {
22724            mCloseGuard.close();
22725            if (mClosed.compareAndSet(false, true)) {
22726                synchronized (mPackages) {
22727                    if (mWeFroze) {
22728                        mFrozenPackages.remove(mPackageName);
22729                    }
22730
22731                    if (mChildren != null) {
22732                        for (PackageFreezer freezer : mChildren) {
22733                            freezer.close();
22734                        }
22735                    }
22736                }
22737            }
22738        }
22739    }
22740
22741    /**
22742     * Verify that given package is currently frozen.
22743     */
22744    private void checkPackageFrozen(String packageName) {
22745        synchronized (mPackages) {
22746            if (!mFrozenPackages.contains(packageName)) {
22747                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22748            }
22749        }
22750    }
22751
22752    @Override
22753    public int movePackage(final String packageName, final String volumeUuid) {
22754        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22755
22756        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22757        final int moveId = mNextMoveId.getAndIncrement();
22758        mHandler.post(new Runnable() {
22759            @Override
22760            public void run() {
22761                try {
22762                    movePackageInternal(packageName, volumeUuid, moveId, user);
22763                } catch (PackageManagerException e) {
22764                    Slog.w(TAG, "Failed to move " + packageName, e);
22765                    mMoveCallbacks.notifyStatusChanged(moveId,
22766                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22767                }
22768            }
22769        });
22770        return moveId;
22771    }
22772
22773    private void movePackageInternal(final String packageName, final String volumeUuid,
22774            final int moveId, UserHandle user) throws PackageManagerException {
22775        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22776        final PackageManager pm = mContext.getPackageManager();
22777
22778        final boolean currentAsec;
22779        final String currentVolumeUuid;
22780        final File codeFile;
22781        final String installerPackageName;
22782        final String packageAbiOverride;
22783        final int appId;
22784        final String seinfo;
22785        final String label;
22786        final int targetSdkVersion;
22787        final PackageFreezer freezer;
22788        final int[] installedUserIds;
22789
22790        // reader
22791        synchronized (mPackages) {
22792            final PackageParser.Package pkg = mPackages.get(packageName);
22793            final PackageSetting ps = mSettings.mPackages.get(packageName);
22794            if (pkg == null || ps == null) {
22795                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22796            }
22797
22798            if (pkg.applicationInfo.isSystemApp()) {
22799                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22800                        "Cannot move system application");
22801            }
22802
22803            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22804            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22805                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22806            if (isInternalStorage && !allow3rdPartyOnInternal) {
22807                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22808                        "3rd party apps are not allowed on internal storage");
22809            }
22810
22811            if (pkg.applicationInfo.isExternalAsec()) {
22812                currentAsec = true;
22813                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22814            } else if (pkg.applicationInfo.isForwardLocked()) {
22815                currentAsec = true;
22816                currentVolumeUuid = "forward_locked";
22817            } else {
22818                currentAsec = false;
22819                currentVolumeUuid = ps.volumeUuid;
22820
22821                final File probe = new File(pkg.codePath);
22822                final File probeOat = new File(probe, "oat");
22823                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22824                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22825                            "Move only supported for modern cluster style installs");
22826                }
22827            }
22828
22829            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22830                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22831                        "Package already moved to " + volumeUuid);
22832            }
22833            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22834                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22835                        "Device admin cannot be moved");
22836            }
22837
22838            if (mFrozenPackages.contains(packageName)) {
22839                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22840                        "Failed to move already frozen package");
22841            }
22842
22843            codeFile = new File(pkg.codePath);
22844            installerPackageName = ps.installerPackageName;
22845            packageAbiOverride = ps.cpuAbiOverrideString;
22846            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22847            seinfo = pkg.applicationInfo.seInfo;
22848            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22849            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22850            freezer = freezePackage(packageName, "movePackageInternal");
22851            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22852        }
22853
22854        final Bundle extras = new Bundle();
22855        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22856        extras.putString(Intent.EXTRA_TITLE, label);
22857        mMoveCallbacks.notifyCreated(moveId, extras);
22858
22859        int installFlags;
22860        final boolean moveCompleteApp;
22861        final File measurePath;
22862
22863        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22864            installFlags = INSTALL_INTERNAL;
22865            moveCompleteApp = !currentAsec;
22866            measurePath = Environment.getDataAppDirectory(volumeUuid);
22867        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22868            installFlags = INSTALL_EXTERNAL;
22869            moveCompleteApp = false;
22870            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22871        } else {
22872            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22873            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22874                    || !volume.isMountedWritable()) {
22875                freezer.close();
22876                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22877                        "Move location not mounted private volume");
22878            }
22879
22880            Preconditions.checkState(!currentAsec);
22881
22882            installFlags = INSTALL_INTERNAL;
22883            moveCompleteApp = true;
22884            measurePath = Environment.getDataAppDirectory(volumeUuid);
22885        }
22886
22887        final PackageStats stats = new PackageStats(null, -1);
22888        synchronized (mInstaller) {
22889            for (int userId : installedUserIds) {
22890                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22891                    freezer.close();
22892                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22893                            "Failed to measure package size");
22894                }
22895            }
22896        }
22897
22898        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22899                + stats.dataSize);
22900
22901        final long startFreeBytes = measurePath.getUsableSpace();
22902        final long sizeBytes;
22903        if (moveCompleteApp) {
22904            sizeBytes = stats.codeSize + stats.dataSize;
22905        } else {
22906            sizeBytes = stats.codeSize;
22907        }
22908
22909        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22910            freezer.close();
22911            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22912                    "Not enough free space to move");
22913        }
22914
22915        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22916
22917        final CountDownLatch installedLatch = new CountDownLatch(1);
22918        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22919            @Override
22920            public void onUserActionRequired(Intent intent) throws RemoteException {
22921                throw new IllegalStateException();
22922            }
22923
22924            @Override
22925            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22926                    Bundle extras) throws RemoteException {
22927                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22928                        + PackageManager.installStatusToString(returnCode, msg));
22929
22930                installedLatch.countDown();
22931                freezer.close();
22932
22933                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22934                switch (status) {
22935                    case PackageInstaller.STATUS_SUCCESS:
22936                        mMoveCallbacks.notifyStatusChanged(moveId,
22937                                PackageManager.MOVE_SUCCEEDED);
22938                        break;
22939                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22940                        mMoveCallbacks.notifyStatusChanged(moveId,
22941                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22942                        break;
22943                    default:
22944                        mMoveCallbacks.notifyStatusChanged(moveId,
22945                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22946                        break;
22947                }
22948            }
22949        };
22950
22951        final MoveInfo move;
22952        if (moveCompleteApp) {
22953            // Kick off a thread to report progress estimates
22954            new Thread() {
22955                @Override
22956                public void run() {
22957                    while (true) {
22958                        try {
22959                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22960                                break;
22961                            }
22962                        } catch (InterruptedException ignored) {
22963                        }
22964
22965                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22966                        final int progress = 10 + (int) MathUtils.constrain(
22967                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22968                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22969                    }
22970                }
22971            }.start();
22972
22973            final String dataAppName = codeFile.getName();
22974            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22975                    dataAppName, appId, seinfo, targetSdkVersion);
22976        } else {
22977            move = null;
22978        }
22979
22980        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22981
22982        final Message msg = mHandler.obtainMessage(INIT_COPY);
22983        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22984        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22985                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22986                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22987                PackageManager.INSTALL_REASON_UNKNOWN);
22988        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22989        msg.obj = params;
22990
22991        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22992                System.identityHashCode(msg.obj));
22993        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22994                System.identityHashCode(msg.obj));
22995
22996        mHandler.sendMessage(msg);
22997    }
22998
22999    @Override
23000    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23002
23003        final int realMoveId = mNextMoveId.getAndIncrement();
23004        final Bundle extras = new Bundle();
23005        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23006        mMoveCallbacks.notifyCreated(realMoveId, extras);
23007
23008        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23009            @Override
23010            public void onCreated(int moveId, Bundle extras) {
23011                // Ignored
23012            }
23013
23014            @Override
23015            public void onStatusChanged(int moveId, int status, long estMillis) {
23016                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23017            }
23018        };
23019
23020        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23021        storage.setPrimaryStorageUuid(volumeUuid, callback);
23022        return realMoveId;
23023    }
23024
23025    @Override
23026    public int getMoveStatus(int moveId) {
23027        mContext.enforceCallingOrSelfPermission(
23028                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23029        return mMoveCallbacks.mLastStatus.get(moveId);
23030    }
23031
23032    @Override
23033    public void registerMoveCallback(IPackageMoveObserver callback) {
23034        mContext.enforceCallingOrSelfPermission(
23035                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23036        mMoveCallbacks.register(callback);
23037    }
23038
23039    @Override
23040    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23041        mContext.enforceCallingOrSelfPermission(
23042                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23043        mMoveCallbacks.unregister(callback);
23044    }
23045
23046    @Override
23047    public boolean setInstallLocation(int loc) {
23048        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23049                null);
23050        if (getInstallLocation() == loc) {
23051            return true;
23052        }
23053        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23054                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23055            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23056                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23057            return true;
23058        }
23059        return false;
23060   }
23061
23062    @Override
23063    public int getInstallLocation() {
23064        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23065                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23066                PackageHelper.APP_INSTALL_AUTO);
23067    }
23068
23069    /** Called by UserManagerService */
23070    void cleanUpUser(UserManagerService userManager, int userHandle) {
23071        synchronized (mPackages) {
23072            mDirtyUsers.remove(userHandle);
23073            mUserNeedsBadging.delete(userHandle);
23074            mSettings.removeUserLPw(userHandle);
23075            mPendingBroadcasts.remove(userHandle);
23076            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23077            removeUnusedPackagesLPw(userManager, userHandle);
23078        }
23079    }
23080
23081    /**
23082     * We're removing userHandle and would like to remove any downloaded packages
23083     * that are no longer in use by any other user.
23084     * @param userHandle the user being removed
23085     */
23086    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23087        final boolean DEBUG_CLEAN_APKS = false;
23088        int [] users = userManager.getUserIds();
23089        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23090        while (psit.hasNext()) {
23091            PackageSetting ps = psit.next();
23092            if (ps.pkg == null) {
23093                continue;
23094            }
23095            final String packageName = ps.pkg.packageName;
23096            // Skip over if system app
23097            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23098                continue;
23099            }
23100            if (DEBUG_CLEAN_APKS) {
23101                Slog.i(TAG, "Checking package " + packageName);
23102            }
23103            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23104            if (keep) {
23105                if (DEBUG_CLEAN_APKS) {
23106                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23107                }
23108            } else {
23109                for (int i = 0; i < users.length; i++) {
23110                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23111                        keep = true;
23112                        if (DEBUG_CLEAN_APKS) {
23113                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23114                                    + users[i]);
23115                        }
23116                        break;
23117                    }
23118                }
23119            }
23120            if (!keep) {
23121                if (DEBUG_CLEAN_APKS) {
23122                    Slog.i(TAG, "  Removing package " + packageName);
23123                }
23124                mHandler.post(new Runnable() {
23125                    public void run() {
23126                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23127                                userHandle, 0);
23128                    } //end run
23129                });
23130            }
23131        }
23132    }
23133
23134    /** Called by UserManagerService */
23135    void createNewUser(int userId, String[] disallowedPackages) {
23136        synchronized (mInstallLock) {
23137            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23138        }
23139        synchronized (mPackages) {
23140            scheduleWritePackageRestrictionsLocked(userId);
23141            scheduleWritePackageListLocked(userId);
23142            applyFactoryDefaultBrowserLPw(userId);
23143            primeDomainVerificationsLPw(userId);
23144        }
23145    }
23146
23147    void onNewUserCreated(final int userId) {
23148        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23149        // If permission review for legacy apps is required, we represent
23150        // dagerous permissions for such apps as always granted runtime
23151        // permissions to keep per user flag state whether review is needed.
23152        // Hence, if a new user is added we have to propagate dangerous
23153        // permission grants for these legacy apps.
23154        if (mPermissionReviewRequired) {
23155            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23156                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23157        }
23158    }
23159
23160    @Override
23161    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23162        mContext.enforceCallingOrSelfPermission(
23163                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23164                "Only package verification agents can read the verifier device identity");
23165
23166        synchronized (mPackages) {
23167            return mSettings.getVerifierDeviceIdentityLPw();
23168        }
23169    }
23170
23171    @Override
23172    public void setPermissionEnforced(String permission, boolean enforced) {
23173        // TODO: Now that we no longer change GID for storage, this should to away.
23174        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23175                "setPermissionEnforced");
23176        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23177            synchronized (mPackages) {
23178                if (mSettings.mReadExternalStorageEnforced == null
23179                        || mSettings.mReadExternalStorageEnforced != enforced) {
23180                    mSettings.mReadExternalStorageEnforced = enforced;
23181                    mSettings.writeLPr();
23182                }
23183            }
23184            // kill any non-foreground processes so we restart them and
23185            // grant/revoke the GID.
23186            final IActivityManager am = ActivityManager.getService();
23187            if (am != null) {
23188                final long token = Binder.clearCallingIdentity();
23189                try {
23190                    am.killProcessesBelowForeground("setPermissionEnforcement");
23191                } catch (RemoteException e) {
23192                } finally {
23193                    Binder.restoreCallingIdentity(token);
23194                }
23195            }
23196        } else {
23197            throw new IllegalArgumentException("No selective enforcement for " + permission);
23198        }
23199    }
23200
23201    @Override
23202    @Deprecated
23203    public boolean isPermissionEnforced(String permission) {
23204        return true;
23205    }
23206
23207    @Override
23208    public boolean isStorageLow() {
23209        final long token = Binder.clearCallingIdentity();
23210        try {
23211            final DeviceStorageMonitorInternal
23212                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23213            if (dsm != null) {
23214                return dsm.isMemoryLow();
23215            } else {
23216                return false;
23217            }
23218        } finally {
23219            Binder.restoreCallingIdentity(token);
23220        }
23221    }
23222
23223    @Override
23224    public IPackageInstaller getPackageInstaller() {
23225        return mInstallerService;
23226    }
23227
23228    private boolean userNeedsBadging(int userId) {
23229        int index = mUserNeedsBadging.indexOfKey(userId);
23230        if (index < 0) {
23231            final UserInfo userInfo;
23232            final long token = Binder.clearCallingIdentity();
23233            try {
23234                userInfo = sUserManager.getUserInfo(userId);
23235            } finally {
23236                Binder.restoreCallingIdentity(token);
23237            }
23238            final boolean b;
23239            if (userInfo != null && userInfo.isManagedProfile()) {
23240                b = true;
23241            } else {
23242                b = false;
23243            }
23244            mUserNeedsBadging.put(userId, b);
23245            return b;
23246        }
23247        return mUserNeedsBadging.valueAt(index);
23248    }
23249
23250    @Override
23251    public KeySet getKeySetByAlias(String packageName, String alias) {
23252        if (packageName == null || alias == null) {
23253            return null;
23254        }
23255        synchronized(mPackages) {
23256            final PackageParser.Package pkg = mPackages.get(packageName);
23257            if (pkg == null) {
23258                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23259                throw new IllegalArgumentException("Unknown package: " + packageName);
23260            }
23261            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23262            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23263        }
23264    }
23265
23266    @Override
23267    public KeySet getSigningKeySet(String packageName) {
23268        if (packageName == null) {
23269            return null;
23270        }
23271        synchronized(mPackages) {
23272            final PackageParser.Package pkg = mPackages.get(packageName);
23273            if (pkg == null) {
23274                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23275                throw new IllegalArgumentException("Unknown package: " + packageName);
23276            }
23277            if (pkg.applicationInfo.uid != Binder.getCallingUid()
23278                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
23279                throw new SecurityException("May not access signing KeySet of other apps.");
23280            }
23281            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23282            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23283        }
23284    }
23285
23286    @Override
23287    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23288        if (packageName == null || ks == null) {
23289            return false;
23290        }
23291        synchronized(mPackages) {
23292            final PackageParser.Package pkg = mPackages.get(packageName);
23293            if (pkg == null) {
23294                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23295                throw new IllegalArgumentException("Unknown package: " + packageName);
23296            }
23297            IBinder ksh = ks.getToken();
23298            if (ksh instanceof KeySetHandle) {
23299                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23300                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23301            }
23302            return false;
23303        }
23304    }
23305
23306    @Override
23307    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23308        if (packageName == null || ks == null) {
23309            return false;
23310        }
23311        synchronized(mPackages) {
23312            final PackageParser.Package pkg = mPackages.get(packageName);
23313            if (pkg == null) {
23314                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23315                throw new IllegalArgumentException("Unknown package: " + packageName);
23316            }
23317            IBinder ksh = ks.getToken();
23318            if (ksh instanceof KeySetHandle) {
23319                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23320                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23321            }
23322            return false;
23323        }
23324    }
23325
23326    private void deletePackageIfUnusedLPr(final String packageName) {
23327        PackageSetting ps = mSettings.mPackages.get(packageName);
23328        if (ps == null) {
23329            return;
23330        }
23331        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23332            // TODO Implement atomic delete if package is unused
23333            // It is currently possible that the package will be deleted even if it is installed
23334            // after this method returns.
23335            mHandler.post(new Runnable() {
23336                public void run() {
23337                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23338                            0, PackageManager.DELETE_ALL_USERS);
23339                }
23340            });
23341        }
23342    }
23343
23344    /**
23345     * Check and throw if the given before/after packages would be considered a
23346     * downgrade.
23347     */
23348    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23349            throws PackageManagerException {
23350        if (after.versionCode < before.mVersionCode) {
23351            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23352                    "Update version code " + after.versionCode + " is older than current "
23353                    + before.mVersionCode);
23354        } else if (after.versionCode == before.mVersionCode) {
23355            if (after.baseRevisionCode < before.baseRevisionCode) {
23356                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23357                        "Update base revision code " + after.baseRevisionCode
23358                        + " is older than current " + before.baseRevisionCode);
23359            }
23360
23361            if (!ArrayUtils.isEmpty(after.splitNames)) {
23362                for (int i = 0; i < after.splitNames.length; i++) {
23363                    final String splitName = after.splitNames[i];
23364                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23365                    if (j != -1) {
23366                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23367                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23368                                    "Update split " + splitName + " revision code "
23369                                    + after.splitRevisionCodes[i] + " is older than current "
23370                                    + before.splitRevisionCodes[j]);
23371                        }
23372                    }
23373                }
23374            }
23375        }
23376    }
23377
23378    private static class MoveCallbacks extends Handler {
23379        private static final int MSG_CREATED = 1;
23380        private static final int MSG_STATUS_CHANGED = 2;
23381
23382        private final RemoteCallbackList<IPackageMoveObserver>
23383                mCallbacks = new RemoteCallbackList<>();
23384
23385        private final SparseIntArray mLastStatus = new SparseIntArray();
23386
23387        public MoveCallbacks(Looper looper) {
23388            super(looper);
23389        }
23390
23391        public void register(IPackageMoveObserver callback) {
23392            mCallbacks.register(callback);
23393        }
23394
23395        public void unregister(IPackageMoveObserver callback) {
23396            mCallbacks.unregister(callback);
23397        }
23398
23399        @Override
23400        public void handleMessage(Message msg) {
23401            final SomeArgs args = (SomeArgs) msg.obj;
23402            final int n = mCallbacks.beginBroadcast();
23403            for (int i = 0; i < n; i++) {
23404                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23405                try {
23406                    invokeCallback(callback, msg.what, args);
23407                } catch (RemoteException ignored) {
23408                }
23409            }
23410            mCallbacks.finishBroadcast();
23411            args.recycle();
23412        }
23413
23414        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23415                throws RemoteException {
23416            switch (what) {
23417                case MSG_CREATED: {
23418                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23419                    break;
23420                }
23421                case MSG_STATUS_CHANGED: {
23422                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23423                    break;
23424                }
23425            }
23426        }
23427
23428        private void notifyCreated(int moveId, Bundle extras) {
23429            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23430
23431            final SomeArgs args = SomeArgs.obtain();
23432            args.argi1 = moveId;
23433            args.arg2 = extras;
23434            obtainMessage(MSG_CREATED, args).sendToTarget();
23435        }
23436
23437        private void notifyStatusChanged(int moveId, int status) {
23438            notifyStatusChanged(moveId, status, -1);
23439        }
23440
23441        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23442            Slog.v(TAG, "Move " + moveId + " status " + status);
23443
23444            final SomeArgs args = SomeArgs.obtain();
23445            args.argi1 = moveId;
23446            args.argi2 = status;
23447            args.arg3 = estMillis;
23448            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23449
23450            synchronized (mLastStatus) {
23451                mLastStatus.put(moveId, status);
23452            }
23453        }
23454    }
23455
23456    private final static class OnPermissionChangeListeners extends Handler {
23457        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23458
23459        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23460                new RemoteCallbackList<>();
23461
23462        public OnPermissionChangeListeners(Looper looper) {
23463            super(looper);
23464        }
23465
23466        @Override
23467        public void handleMessage(Message msg) {
23468            switch (msg.what) {
23469                case MSG_ON_PERMISSIONS_CHANGED: {
23470                    final int uid = msg.arg1;
23471                    handleOnPermissionsChanged(uid);
23472                } break;
23473            }
23474        }
23475
23476        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23477            mPermissionListeners.register(listener);
23478
23479        }
23480
23481        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23482            mPermissionListeners.unregister(listener);
23483        }
23484
23485        public void onPermissionsChanged(int uid) {
23486            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23487                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23488            }
23489        }
23490
23491        private void handleOnPermissionsChanged(int uid) {
23492            final int count = mPermissionListeners.beginBroadcast();
23493            try {
23494                for (int i = 0; i < count; i++) {
23495                    IOnPermissionsChangeListener callback = mPermissionListeners
23496                            .getBroadcastItem(i);
23497                    try {
23498                        callback.onPermissionsChanged(uid);
23499                    } catch (RemoteException e) {
23500                        Log.e(TAG, "Permission listener is dead", e);
23501                    }
23502                }
23503            } finally {
23504                mPermissionListeners.finishBroadcast();
23505            }
23506        }
23507    }
23508
23509    private class PackageManagerInternalImpl extends PackageManagerInternal {
23510        @Override
23511        public void setLocationPackagesProvider(PackagesProvider provider) {
23512            synchronized (mPackages) {
23513                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23514            }
23515        }
23516
23517        @Override
23518        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23519            synchronized (mPackages) {
23520                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23521            }
23522        }
23523
23524        @Override
23525        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23526            synchronized (mPackages) {
23527                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23528            }
23529        }
23530
23531        @Override
23532        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23533            synchronized (mPackages) {
23534                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23535            }
23536        }
23537
23538        @Override
23539        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23540            synchronized (mPackages) {
23541                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23542            }
23543        }
23544
23545        @Override
23546        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23547            synchronized (mPackages) {
23548                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23549            }
23550        }
23551
23552        @Override
23553        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23554            synchronized (mPackages) {
23555                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23556                        packageName, userId);
23557            }
23558        }
23559
23560        @Override
23561        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23562            synchronized (mPackages) {
23563                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23564                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23565                        packageName, userId);
23566            }
23567        }
23568
23569        @Override
23570        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23571            synchronized (mPackages) {
23572                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23573                        packageName, userId);
23574            }
23575        }
23576
23577        @Override
23578        public void setKeepUninstalledPackages(final List<String> packageList) {
23579            Preconditions.checkNotNull(packageList);
23580            List<String> removedFromList = null;
23581            synchronized (mPackages) {
23582                if (mKeepUninstalledPackages != null) {
23583                    final int packagesCount = mKeepUninstalledPackages.size();
23584                    for (int i = 0; i < packagesCount; i++) {
23585                        String oldPackage = mKeepUninstalledPackages.get(i);
23586                        if (packageList != null && packageList.contains(oldPackage)) {
23587                            continue;
23588                        }
23589                        if (removedFromList == null) {
23590                            removedFromList = new ArrayList<>();
23591                        }
23592                        removedFromList.add(oldPackage);
23593                    }
23594                }
23595                mKeepUninstalledPackages = new ArrayList<>(packageList);
23596                if (removedFromList != null) {
23597                    final int removedCount = removedFromList.size();
23598                    for (int i = 0; i < removedCount; i++) {
23599                        deletePackageIfUnusedLPr(removedFromList.get(i));
23600                    }
23601                }
23602            }
23603        }
23604
23605        @Override
23606        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23607            synchronized (mPackages) {
23608                // If we do not support permission review, done.
23609                if (!mPermissionReviewRequired) {
23610                    return false;
23611                }
23612
23613                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23614                if (packageSetting == null) {
23615                    return false;
23616                }
23617
23618                // Permission review applies only to apps not supporting the new permission model.
23619                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23620                    return false;
23621                }
23622
23623                // Legacy apps have the permission and get user consent on launch.
23624                PermissionsState permissionsState = packageSetting.getPermissionsState();
23625                return permissionsState.isPermissionReviewRequired(userId);
23626            }
23627        }
23628
23629        @Override
23630        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23631            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23632        }
23633
23634        @Override
23635        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23636                int userId) {
23637            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23638        }
23639
23640        @Override
23641        public void setDeviceAndProfileOwnerPackages(
23642                int deviceOwnerUserId, String deviceOwnerPackage,
23643                SparseArray<String> profileOwnerPackages) {
23644            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23645                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23646        }
23647
23648        @Override
23649        public boolean isPackageDataProtected(int userId, String packageName) {
23650            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23651        }
23652
23653        @Override
23654        public boolean isPackageEphemeral(int userId, String packageName) {
23655            synchronized (mPackages) {
23656                final PackageSetting ps = mSettings.mPackages.get(packageName);
23657                return ps != null ? ps.getInstantApp(userId) : false;
23658            }
23659        }
23660
23661        @Override
23662        public boolean wasPackageEverLaunched(String packageName, int userId) {
23663            synchronized (mPackages) {
23664                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23665            }
23666        }
23667
23668        @Override
23669        public void grantRuntimePermission(String packageName, String name, int userId,
23670                boolean overridePolicy) {
23671            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23672                    overridePolicy);
23673        }
23674
23675        @Override
23676        public void revokeRuntimePermission(String packageName, String name, int userId,
23677                boolean overridePolicy) {
23678            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23679                    overridePolicy);
23680        }
23681
23682        @Override
23683        public String getNameForUid(int uid) {
23684            return PackageManagerService.this.getNameForUid(uid);
23685        }
23686
23687        @Override
23688        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23689                Intent origIntent, String resolvedType, String callingPackage,
23690                Bundle verificationBundle, int userId) {
23691            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23692                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23693                    userId);
23694        }
23695
23696        @Override
23697        public void grantEphemeralAccess(int userId, Intent intent,
23698                int targetAppId, int ephemeralAppId) {
23699            synchronized (mPackages) {
23700                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23701                        targetAppId, ephemeralAppId);
23702            }
23703        }
23704
23705        @Override
23706        public boolean isInstantAppInstallerComponent(ComponentName component) {
23707            synchronized (mPackages) {
23708                return mInstantAppInstallerActivity != null
23709                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23710            }
23711        }
23712
23713        @Override
23714        public void pruneInstantApps() {
23715            synchronized (mPackages) {
23716                mInstantAppRegistry.pruneInstantAppsLPw();
23717            }
23718        }
23719
23720        @Override
23721        public String getSetupWizardPackageName() {
23722            return mSetupWizardPackage;
23723        }
23724
23725        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23726            if (policy != null) {
23727                mExternalSourcesPolicy = policy;
23728            }
23729        }
23730
23731        @Override
23732        public boolean isPackagePersistent(String packageName) {
23733            synchronized (mPackages) {
23734                PackageParser.Package pkg = mPackages.get(packageName);
23735                return pkg != null
23736                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23737                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23738                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23739                        : false;
23740            }
23741        }
23742
23743        @Override
23744        public List<PackageInfo> getOverlayPackages(int userId) {
23745            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23746            synchronized (mPackages) {
23747                for (PackageParser.Package p : mPackages.values()) {
23748                    if (p.mOverlayTarget != null) {
23749                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23750                        if (pkg != null) {
23751                            overlayPackages.add(pkg);
23752                        }
23753                    }
23754                }
23755            }
23756            return overlayPackages;
23757        }
23758
23759        @Override
23760        public List<String> getTargetPackageNames(int userId) {
23761            List<String> targetPackages = new ArrayList<>();
23762            synchronized (mPackages) {
23763                for (PackageParser.Package p : mPackages.values()) {
23764                    if (p.mOverlayTarget == null) {
23765                        targetPackages.add(p.packageName);
23766                    }
23767                }
23768            }
23769            return targetPackages;
23770        }
23771
23772        @Override
23773        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23774                @Nullable List<String> overlayPackageNames) {
23775            synchronized (mPackages) {
23776                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23777                    Slog.e(TAG, "failed to find package " + targetPackageName);
23778                    return false;
23779                }
23780
23781                ArrayList<String> paths = null;
23782                if (overlayPackageNames != null) {
23783                    final int N = overlayPackageNames.size();
23784                    paths = new ArrayList<>(N);
23785                    for (int i = 0; i < N; i++) {
23786                        final String packageName = overlayPackageNames.get(i);
23787                        final PackageParser.Package pkg = mPackages.get(packageName);
23788                        if (pkg == null) {
23789                            Slog.e(TAG, "failed to find package " + packageName);
23790                            return false;
23791                        }
23792                        paths.add(pkg.baseCodePath);
23793                    }
23794                }
23795
23796                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23797                    mEnabledOverlayPaths.get(userId);
23798                if (userSpecificOverlays == null) {
23799                    userSpecificOverlays = new ArrayMap<>();
23800                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23801                }
23802
23803                if (paths != null && paths.size() > 0) {
23804                    userSpecificOverlays.put(targetPackageName, paths);
23805                } else {
23806                    userSpecificOverlays.remove(targetPackageName);
23807                }
23808                return true;
23809            }
23810        }
23811
23812        @Override
23813        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23814                int flags, int userId) {
23815            return resolveIntentInternal(
23816                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
23817        }
23818
23819        @Override
23820        public ResolveInfo resolveService(Intent intent, String resolvedType,
23821                int flags, int userId, int callingUid) {
23822            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23823        }
23824
23825        @Override
23826        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23827            synchronized (mPackages) {
23828                mIsolatedOwners.put(isolatedUid, ownerUid);
23829            }
23830        }
23831
23832        @Override
23833        public void removeIsolatedUid(int isolatedUid) {
23834            synchronized (mPackages) {
23835                mIsolatedOwners.delete(isolatedUid);
23836            }
23837        }
23838
23839        @Override
23840        public int getUidTargetSdkVersion(int uid) {
23841            synchronized (mPackages) {
23842                return getUidTargetSdkVersionLockedLPr(uid);
23843            }
23844        }
23845    }
23846
23847    @Override
23848    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23849        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23850        synchronized (mPackages) {
23851            final long identity = Binder.clearCallingIdentity();
23852            try {
23853                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23854                        packageNames, userId);
23855            } finally {
23856                Binder.restoreCallingIdentity(identity);
23857            }
23858        }
23859    }
23860
23861    @Override
23862    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23863        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23864        synchronized (mPackages) {
23865            final long identity = Binder.clearCallingIdentity();
23866            try {
23867                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23868                        packageNames, userId);
23869            } finally {
23870                Binder.restoreCallingIdentity(identity);
23871            }
23872        }
23873    }
23874
23875    private static void enforceSystemOrPhoneCaller(String tag) {
23876        int callingUid = Binder.getCallingUid();
23877        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23878            throw new SecurityException(
23879                    "Cannot call " + tag + " from UID " + callingUid);
23880        }
23881    }
23882
23883    boolean isHistoricalPackageUsageAvailable() {
23884        return mPackageUsage.isHistoricalPackageUsageAvailable();
23885    }
23886
23887    /**
23888     * Return a <b>copy</b> of the collection of packages known to the package manager.
23889     * @return A copy of the values of mPackages.
23890     */
23891    Collection<PackageParser.Package> getPackages() {
23892        synchronized (mPackages) {
23893            return new ArrayList<>(mPackages.values());
23894        }
23895    }
23896
23897    /**
23898     * Logs process start information (including base APK hash) to the security log.
23899     * @hide
23900     */
23901    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23902            String apkFile, int pid) {
23903        if (!SecurityLog.isLoggingEnabled()) {
23904            return;
23905        }
23906        Bundle data = new Bundle();
23907        data.putLong("startTimestamp", System.currentTimeMillis());
23908        data.putString("processName", processName);
23909        data.putInt("uid", uid);
23910        data.putString("seinfo", seinfo);
23911        data.putString("apkFile", apkFile);
23912        data.putInt("pid", pid);
23913        Message msg = mProcessLoggingHandler.obtainMessage(
23914                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23915        msg.setData(data);
23916        mProcessLoggingHandler.sendMessage(msg);
23917    }
23918
23919    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23920        return mCompilerStats.getPackageStats(pkgName);
23921    }
23922
23923    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23924        return getOrCreateCompilerPackageStats(pkg.packageName);
23925    }
23926
23927    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23928        return mCompilerStats.getOrCreatePackageStats(pkgName);
23929    }
23930
23931    public void deleteCompilerPackageStats(String pkgName) {
23932        mCompilerStats.deletePackageStats(pkgName);
23933    }
23934
23935    @Override
23936    public int getInstallReason(String packageName, int userId) {
23937        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23938                true /* requireFullPermission */, false /* checkShell */,
23939                "get install reason");
23940        synchronized (mPackages) {
23941            final PackageSetting ps = mSettings.mPackages.get(packageName);
23942            if (ps != null) {
23943                return ps.getInstallReason(userId);
23944            }
23945        }
23946        return PackageManager.INSTALL_REASON_UNKNOWN;
23947    }
23948
23949    @Override
23950    public boolean canRequestPackageInstalls(String packageName, int userId) {
23951        return canRequestPackageInstallsInternal(packageName, 0, userId,
23952                true /* throwIfPermNotDeclared*/);
23953    }
23954
23955    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23956            boolean throwIfPermNotDeclared) {
23957        int callingUid = Binder.getCallingUid();
23958        int uid = getPackageUid(packageName, 0, userId);
23959        if (callingUid != uid && callingUid != Process.ROOT_UID
23960                && callingUid != Process.SYSTEM_UID) {
23961            throw new SecurityException(
23962                    "Caller uid " + callingUid + " does not own package " + packageName);
23963        }
23964        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23965        if (info == null) {
23966            return false;
23967        }
23968        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23969            return false;
23970        }
23971        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23972        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23973        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23974            if (throwIfPermNotDeclared) {
23975                throw new SecurityException("Need to declare " + appOpPermission
23976                        + " to call this api");
23977            } else {
23978                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23979                return false;
23980            }
23981        }
23982        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23983            return false;
23984        }
23985        if (mExternalSourcesPolicy != null) {
23986            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23987            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23988                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23989            }
23990        }
23991        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23992    }
23993
23994    @Override
23995    public ComponentName getInstantAppResolverSettingsComponent() {
23996        return mInstantAppResolverSettingsComponent;
23997    }
23998
23999    @Override
24000    public ComponentName getInstantAppInstallerComponent() {
24001        return mInstantAppInstallerActivity == null
24002                ? null : mInstantAppInstallerActivity.getComponentName();
24003    }
24004
24005    @Override
24006    public String getInstantAppAndroidId(String packageName, int userId) {
24007        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24008                "getInstantAppAndroidId");
24009        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24010                true /* requireFullPermission */, false /* checkShell */,
24011                "getInstantAppAndroidId");
24012        // Make sure the target is an Instant App.
24013        if (!isInstantApp(packageName, userId)) {
24014            return null;
24015        }
24016        synchronized (mPackages) {
24017            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24018        }
24019    }
24020}
24021
24022interface PackageSender {
24023    void sendPackageBroadcast(final String action, final String pkg,
24024        final Bundle extras, final int flags, final String targetPkg,
24025        final IIntentReceiver finishedReceiver, final int[] userIds);
24026    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24027        int appId, int... userIds);
24028}
24029