PackageManagerService.java revision 7c8addfef09c118c5052c9a9e9f8f83a61044870
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.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_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_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.pm.dex.DexoptOptions;
287import com.android.server.pm.dex.PackageDexUsage;
288import com.android.server.storage.DeviceStorageMonitorInternal;
289
290import dalvik.system.CloseGuard;
291import dalvik.system.DexFile;
292import dalvik.system.VMRuntime;
293
294import libcore.io.IoUtils;
295import libcore.io.Streams;
296import libcore.util.EmptyArray;
297
298import org.xmlpull.v1.XmlPullParser;
299import org.xmlpull.v1.XmlPullParserException;
300import org.xmlpull.v1.XmlSerializer;
301
302import java.io.BufferedOutputStream;
303import java.io.BufferedReader;
304import java.io.ByteArrayInputStream;
305import java.io.ByteArrayOutputStream;
306import java.io.File;
307import java.io.FileDescriptor;
308import java.io.FileInputStream;
309import java.io.FileOutputStream;
310import java.io.FileReader;
311import java.io.FilenameFilter;
312import java.io.IOException;
313import java.io.InputStream;
314import java.io.OutputStream;
315import java.io.PrintWriter;
316import java.lang.annotation.Retention;
317import java.lang.annotation.RetentionPolicy;
318import java.nio.charset.StandardCharsets;
319import java.security.DigestInputStream;
320import java.security.MessageDigest;
321import java.security.NoSuchAlgorithmException;
322import java.security.PublicKey;
323import java.security.SecureRandom;
324import java.security.cert.Certificate;
325import java.security.cert.CertificateEncodingException;
326import java.security.cert.CertificateException;
327import java.text.SimpleDateFormat;
328import java.util.ArrayList;
329import java.util.Arrays;
330import java.util.Collection;
331import java.util.Collections;
332import java.util.Comparator;
333import java.util.Date;
334import java.util.HashMap;
335import java.util.HashSet;
336import java.util.Iterator;
337import java.util.List;
338import java.util.Map;
339import java.util.Objects;
340import java.util.Set;
341import java.util.concurrent.CountDownLatch;
342import java.util.concurrent.Future;
343import java.util.concurrent.TimeUnit;
344import java.util.concurrent.atomic.AtomicBoolean;
345import java.util.concurrent.atomic.AtomicInteger;
346import java.util.zip.GZIPInputStream;
347
348/**
349 * Keep track of all those APKs everywhere.
350 * <p>
351 * Internally there are two important locks:
352 * <ul>
353 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
354 * and other related state. It is a fine-grained lock that should only be held
355 * momentarily, as it's one of the most contended locks in the system.
356 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
357 * operations typically involve heavy lifting of application data on disk. Since
358 * {@code installd} is single-threaded, and it's operations can often be slow,
359 * this lock should never be acquired while already holding {@link #mPackages}.
360 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
361 * holding {@link #mInstallLock}.
362 * </ul>
363 * Many internal methods rely on the caller to hold the appropriate locks, and
364 * this contract is expressed through method name suffixes:
365 * <ul>
366 * <li>fooLI(): the caller must hold {@link #mInstallLock}
367 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
368 * being modified must be frozen
369 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
370 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
371 * </ul>
372 * <p>
373 * Because this class is very central to the platform's security; please run all
374 * CTS and unit tests whenever making modifications:
375 *
376 * <pre>
377 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
378 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
379 * </pre>
380 */
381public class PackageManagerService extends IPackageManager.Stub
382        implements PackageSender {
383    static final String TAG = "PackageManager";
384    static final boolean DEBUG_SETTINGS = false;
385    static final boolean DEBUG_PREFERRED = false;
386    static final boolean DEBUG_UPGRADE = false;
387    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
388    private static final boolean DEBUG_BACKUP = false;
389    private static final boolean DEBUG_INSTALL = false;
390    private static final boolean DEBUG_REMOVE = false;
391    private static final boolean DEBUG_BROADCASTS = false;
392    private static final boolean DEBUG_SHOW_INFO = false;
393    private static final boolean DEBUG_PACKAGE_INFO = false;
394    private static final boolean DEBUG_INTENT_MATCHING = false;
395    private static final boolean DEBUG_PACKAGE_SCANNING = false;
396    private static final boolean DEBUG_VERIFY = false;
397    private static final boolean DEBUG_FILTERS = false;
398    private static final boolean DEBUG_PERMISSIONS = false;
399    private static final boolean DEBUG_SHARED_LIBRARIES = false;
400    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
401
402    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
403    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
404    // user, but by default initialize to this.
405    public static final boolean DEBUG_DEXOPT = false;
406
407    private static final boolean DEBUG_ABI_SELECTION = false;
408    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
409    private static final boolean DEBUG_TRIAGED_MISSING = false;
410    private static final boolean DEBUG_APP_DATA = false;
411
412    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
413    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
414
415    private static final boolean HIDE_EPHEMERAL_APIS = false;
416
417    private static final boolean ENABLE_FREE_CACHE_V2 =
418            SystemProperties.getBoolean("fw.free_cache_v2", true);
419
420    private static final int RADIO_UID = Process.PHONE_UID;
421    private static final int LOG_UID = Process.LOG_UID;
422    private static final int NFC_UID = Process.NFC_UID;
423    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
424    private static final int SHELL_UID = Process.SHELL_UID;
425
426    // Cap the size of permission trees that 3rd party apps can define
427    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
428
429    // Suffix used during package installation when copying/moving
430    // package apks to install directory.
431    private static final String INSTALL_PACKAGE_SUFFIX = "-";
432
433    static final int SCAN_NO_DEX = 1<<1;
434    static final int SCAN_FORCE_DEX = 1<<2;
435    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
436    static final int SCAN_NEW_INSTALL = 1<<4;
437    static final int SCAN_UPDATE_TIME = 1<<5;
438    static final int SCAN_BOOTING = 1<<6;
439    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
440    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
441    static final int SCAN_REPLACING = 1<<9;
442    static final int SCAN_REQUIRE_KNOWN = 1<<10;
443    static final int SCAN_MOVE = 1<<11;
444    static final int SCAN_INITIAL = 1<<12;
445    static final int SCAN_CHECK_ONLY = 1<<13;
446    static final int SCAN_DONT_KILL_APP = 1<<14;
447    static final int SCAN_IGNORE_FROZEN = 1<<15;
448    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
449    static final int SCAN_AS_INSTANT_APP = 1<<17;
450    static final int SCAN_AS_FULL_APP = 1<<18;
451    /** Should not be with the scan flags */
452    static final int FLAGS_REMOVE_CHATTY = 1<<31;
453
454    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
455    /** Extension of the compressed packages */
456    private final static String COMPRESSED_EXTENSION = ".gz";
457
458    private static final int[] EMPTY_INT_ARRAY = new int[0];
459
460    private static final int TYPE_UNKNOWN = 0;
461    private static final int TYPE_ACTIVITY = 1;
462    private static final int TYPE_RECEIVER = 2;
463    private static final int TYPE_SERVICE = 3;
464    private static final int TYPE_PROVIDER = 4;
465    @IntDef(prefix = { "TYPE_" }, value = {
466            TYPE_UNKNOWN,
467            TYPE_ACTIVITY,
468            TYPE_RECEIVER,
469            TYPE_SERVICE,
470            TYPE_PROVIDER,
471    })
472    @Retention(RetentionPolicy.SOURCE)
473    public @interface ComponentType {}
474
475    /**
476     * Timeout (in milliseconds) after which the watchdog should declare that
477     * our handler thread is wedged.  The usual default for such things is one
478     * minute but we sometimes do very lengthy I/O operations on this thread,
479     * such as installing multi-gigabyte applications, so ours needs to be longer.
480     */
481    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
482
483    /**
484     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
485     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
486     * settings entry if available, otherwise we use the hardcoded default.  If it's been
487     * more than this long since the last fstrim, we force one during the boot sequence.
488     *
489     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
490     * one gets run at the next available charging+idle time.  This final mandatory
491     * no-fstrim check kicks in only of the other scheduling criteria is never met.
492     */
493    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
494
495    /**
496     * Whether verification is enabled by default.
497     */
498    private static final boolean DEFAULT_VERIFY_ENABLE = true;
499
500    /**
501     * The default maximum time to wait for the verification agent to return in
502     * milliseconds.
503     */
504    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
505
506    /**
507     * The default response for package verification timeout.
508     *
509     * This can be either PackageManager.VERIFICATION_ALLOW or
510     * PackageManager.VERIFICATION_REJECT.
511     */
512    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
513
514    static final String PLATFORM_PACKAGE_NAME = "android";
515
516    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
517
518    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
519            DEFAULT_CONTAINER_PACKAGE,
520            "com.android.defcontainer.DefaultContainerService");
521
522    private static final String KILL_APP_REASON_GIDS_CHANGED =
523            "permission grant or revoke changed gids";
524
525    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
526            "permissions revoked";
527
528    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
529
530    private static final String PACKAGE_SCHEME = "package";
531
532    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
533
534    /** Permission grant: not grant the permission. */
535    private static final int GRANT_DENIED = 1;
536
537    /** Permission grant: grant the permission as an install permission. */
538    private static final int GRANT_INSTALL = 2;
539
540    /** Permission grant: grant the permission as a runtime one. */
541    private static final int GRANT_RUNTIME = 3;
542
543    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
544    private static final int GRANT_UPGRADE = 4;
545
546    /** Canonical intent used to identify what counts as a "web browser" app */
547    private static final Intent sBrowserIntent;
548    static {
549        sBrowserIntent = new Intent();
550        sBrowserIntent.setAction(Intent.ACTION_VIEW);
551        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
552        sBrowserIntent.setData(Uri.parse("http:"));
553    }
554
555    /**
556     * The set of all protected actions [i.e. those actions for which a high priority
557     * intent filter is disallowed].
558     */
559    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
560    static {
561        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
562        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
563        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
564        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
565    }
566
567    // Compilation reasons.
568    public static final int REASON_FIRST_BOOT = 0;
569    public static final int REASON_BOOT = 1;
570    public static final int REASON_INSTALL = 2;
571    public static final int REASON_BACKGROUND_DEXOPT = 3;
572    public static final int REASON_AB_OTA = 4;
573    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
574
575    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
576
577    /** All dangerous permission names in the same order as the events in MetricsEvent */
578    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
579            Manifest.permission.READ_CALENDAR,
580            Manifest.permission.WRITE_CALENDAR,
581            Manifest.permission.CAMERA,
582            Manifest.permission.READ_CONTACTS,
583            Manifest.permission.WRITE_CONTACTS,
584            Manifest.permission.GET_ACCOUNTS,
585            Manifest.permission.ACCESS_FINE_LOCATION,
586            Manifest.permission.ACCESS_COARSE_LOCATION,
587            Manifest.permission.RECORD_AUDIO,
588            Manifest.permission.READ_PHONE_STATE,
589            Manifest.permission.CALL_PHONE,
590            Manifest.permission.READ_CALL_LOG,
591            Manifest.permission.WRITE_CALL_LOG,
592            Manifest.permission.ADD_VOICEMAIL,
593            Manifest.permission.USE_SIP,
594            Manifest.permission.PROCESS_OUTGOING_CALLS,
595            Manifest.permission.READ_CELL_BROADCASTS,
596            Manifest.permission.BODY_SENSORS,
597            Manifest.permission.SEND_SMS,
598            Manifest.permission.RECEIVE_SMS,
599            Manifest.permission.READ_SMS,
600            Manifest.permission.RECEIVE_WAP_PUSH,
601            Manifest.permission.RECEIVE_MMS,
602            Manifest.permission.READ_EXTERNAL_STORAGE,
603            Manifest.permission.WRITE_EXTERNAL_STORAGE,
604            Manifest.permission.READ_PHONE_NUMBERS,
605            Manifest.permission.ANSWER_PHONE_CALLS);
606
607
608    /**
609     * Version number for the package parser cache. Increment this whenever the format or
610     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
611     */
612    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
613
614    /**
615     * Whether the package parser cache is enabled.
616     */
617    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
618
619    final ServiceThread mHandlerThread;
620
621    final PackageHandler mHandler;
622
623    private final ProcessLoggingHandler mProcessLoggingHandler;
624
625    /**
626     * Messages for {@link #mHandler} that need to wait for system ready before
627     * being dispatched.
628     */
629    private ArrayList<Message> mPostSystemReadyMessages;
630
631    final int mSdkVersion = Build.VERSION.SDK_INT;
632
633    final Context mContext;
634    final boolean mFactoryTest;
635    final boolean mOnlyCore;
636    final DisplayMetrics mMetrics;
637    final int mDefParseFlags;
638    final String[] mSeparateProcesses;
639    final boolean mIsUpgrade;
640    final boolean mIsPreNUpgrade;
641    final boolean mIsPreNMR1Upgrade;
642
643    // Have we told the Activity Manager to whitelist the default container service by uid yet?
644    @GuardedBy("mPackages")
645    boolean mDefaultContainerWhitelisted = false;
646
647    @GuardedBy("mPackages")
648    private boolean mDexOptDialogShown;
649
650    /** The location for ASEC container files on internal storage. */
651    final String mAsecInternalPath;
652
653    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
654    // LOCK HELD.  Can be called with mInstallLock held.
655    @GuardedBy("mInstallLock")
656    final Installer mInstaller;
657
658    /** Directory where installed third-party apps stored */
659    final File mAppInstallDir;
660
661    /**
662     * Directory to which applications installed internally have their
663     * 32 bit native libraries copied.
664     */
665    private File mAppLib32InstallDir;
666
667    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
668    // apps.
669    final File mDrmAppPrivateInstallDir;
670
671    // ----------------------------------------------------------------
672
673    // Lock for state used when installing and doing other long running
674    // operations.  Methods that must be called with this lock held have
675    // the suffix "LI".
676    final Object mInstallLock = new Object();
677
678    // ----------------------------------------------------------------
679
680    // Keys are String (package name), values are Package.  This also serves
681    // as the lock for the global state.  Methods that must be called with
682    // this lock held have the prefix "LP".
683    @GuardedBy("mPackages")
684    final ArrayMap<String, PackageParser.Package> mPackages =
685            new ArrayMap<String, PackageParser.Package>();
686
687    final ArrayMap<String, Set<String>> mKnownCodebase =
688            new ArrayMap<String, Set<String>>();
689
690    // Keys are isolated uids and values are the uid of the application
691    // that created the isolated proccess.
692    @GuardedBy("mPackages")
693    final SparseIntArray mIsolatedOwners = new SparseIntArray();
694
695    /**
696     * Tracks new system packages [received in an OTA] that we expect to
697     * find updated user-installed versions. Keys are package name, values
698     * are package location.
699     */
700    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
701    /**
702     * Tracks high priority intent filters for protected actions. During boot, certain
703     * filter actions are protected and should never be allowed to have a high priority
704     * intent filter for them. However, there is one, and only one exception -- the
705     * setup wizard. It must be able to define a high priority intent filter for these
706     * actions to ensure there are no escapes from the wizard. We need to delay processing
707     * of these during boot as we need to look at all of the system packages in order
708     * to know which component is the setup wizard.
709     */
710    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
711    /**
712     * Whether or not processing protected filters should be deferred.
713     */
714    private boolean mDeferProtectedFilters = true;
715
716    /**
717     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
718     */
719    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
720    /**
721     * Whether or not system app permissions should be promoted from install to runtime.
722     */
723    boolean mPromoteSystemApps;
724
725    @GuardedBy("mPackages")
726    final Settings mSettings;
727
728    /**
729     * Set of package names that are currently "frozen", which means active
730     * surgery is being done on the code/data for that package. The platform
731     * will refuse to launch frozen packages to avoid race conditions.
732     *
733     * @see PackageFreezer
734     */
735    @GuardedBy("mPackages")
736    final ArraySet<String> mFrozenPackages = new ArraySet<>();
737
738    final ProtectedPackages mProtectedPackages;
739
740    @GuardedBy("mLoadedVolumes")
741    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
742
743    boolean mFirstBoot;
744
745    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
746
747    // System configuration read by SystemConfig.
748    final int[] mGlobalGids;
749    final SparseArray<ArraySet<String>> mSystemPermissions;
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    // If mac_permissions.xml was found for seinfo labeling.
754    boolean mFoundPolicyFile;
755
756    private final InstantAppRegistry mInstantAppRegistry;
757
758    @GuardedBy("mPackages")
759    int mChangedPackagesSequenceNumber;
760    /**
761     * List of changed [installed, removed or updated] packages.
762     * mapping from user id -> sequence number -> package name
763     */
764    @GuardedBy("mPackages")
765    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
766    /**
767     * The sequence number of the last change to a package.
768     * mapping from user id -> package name -> sequence number
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
801                String targetPackageName, String targetPath) {
802            if ("android".equals(targetPackageName)) {
803                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
804                // native AssetManager.
805                return null;
806            }
807            List<PackageParser.Package> overlayPackages =
808                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
809            if (overlayPackages == null || overlayPackages.isEmpty()) {
810                return null;
811            }
812            List<String> overlayPathList = null;
813            for (PackageParser.Package overlayPackage : overlayPackages) {
814                if (targetPath == null) {
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                    continue;
820                }
821
822                try {
823                    // Creates idmaps for system to parse correctly the Android manifest of the
824                    // target package.
825                    //
826                    // OverlayManagerService will update each of them with a correct gid from its
827                    // target package app id.
828                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
829                            UserHandle.getSharedAppGid(
830                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
831                    if (overlayPathList == null) {
832                        overlayPathList = new ArrayList<String>();
833                    }
834                    overlayPathList.add(overlayPackage.baseCodePath);
835                } catch (InstallerException e) {
836                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
837                            overlayPackage.baseCodePath);
838                }
839            }
840            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
841        }
842
843        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
844            synchronized (mPackages) {
845                return getStaticOverlayPathsLocked(
846                        mPackages.values(), targetPackageName, targetPath);
847            }
848        }
849
850        @Override public final String[] getOverlayApks(String targetPackageName) {
851            return getStaticOverlayPaths(targetPackageName, null);
852        }
853
854        @Override public final String[] getOverlayPaths(String targetPackageName,
855                String targetPath) {
856            return getStaticOverlayPaths(targetPackageName, targetPath);
857        }
858    };
859
860    class ParallelPackageParserCallback extends PackageParserCallback {
861        List<PackageParser.Package> mOverlayPackages = null;
862
863        void findStaticOverlayPackages() {
864            synchronized (mPackages) {
865                for (PackageParser.Package p : mPackages.values()) {
866                    if (p.mIsStaticOverlay) {
867                        if (mOverlayPackages == null) {
868                            mOverlayPackages = new ArrayList<PackageParser.Package>();
869                        }
870                        mOverlayPackages.add(p);
871                    }
872                }
873            }
874        }
875
876        @Override
877        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
878            // We can trust mOverlayPackages without holding mPackages because package uninstall
879            // can't happen while running parallel parsing.
880            // Moreover holding mPackages on each parsing thread causes dead-lock.
881            return mOverlayPackages == null ? null :
882                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
883        }
884    }
885
886    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
887    final ParallelPackageParserCallback mParallelPackageParserCallback =
888            new ParallelPackageParserCallback();
889
890    public static final class SharedLibraryEntry {
891        public final @Nullable String path;
892        public final @Nullable String apk;
893        public final @NonNull SharedLibraryInfo info;
894
895        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
896                String declaringPackageName, int declaringPackageVersionCode) {
897            path = _path;
898            apk = _apk;
899            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
900                    declaringPackageName, declaringPackageVersionCode), null);
901        }
902    }
903
904    // Currently known shared libraries.
905    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
906    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
907            new ArrayMap<>();
908
909    // All available activities, for your resolving pleasure.
910    final ActivityIntentResolver mActivities =
911            new ActivityIntentResolver();
912
913    // All available receivers, for your resolving pleasure.
914    final ActivityIntentResolver mReceivers =
915            new ActivityIntentResolver();
916
917    // All available services, for your resolving pleasure.
918    final ServiceIntentResolver mServices = new ServiceIntentResolver();
919
920    // All available providers, for your resolving pleasure.
921    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
922
923    // Mapping from provider base names (first directory in content URI codePath)
924    // to the provider information.
925    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
926            new ArrayMap<String, PackageParser.Provider>();
927
928    // Mapping from instrumentation class names to info about them.
929    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
930            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
931
932    // Mapping from permission names to info about them.
933    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
934            new ArrayMap<String, PackageParser.PermissionGroup>();
935
936    // Packages whose data we have transfered into another package, thus
937    // should no longer exist.
938    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
939
940    // Broadcast actions that are only available to the system.
941    @GuardedBy("mProtectedBroadcasts")
942    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
943
944    /** List of packages waiting for verification. */
945    final SparseArray<PackageVerificationState> mPendingVerification
946            = new SparseArray<PackageVerificationState>();
947
948    /** Set of packages associated with each app op permission. */
949    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
950
951    final PackageInstallerService mInstallerService;
952
953    private final PackageDexOptimizer mPackageDexOptimizer;
954    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
955    // is used by other apps).
956    private final DexManager mDexManager;
957
958    private AtomicInteger mNextMoveId = new AtomicInteger();
959    private final MoveCallbacks mMoveCallbacks;
960
961    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
962
963    // Cache of users who need badging.
964    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
965
966    /** Token for keys in mPendingVerification. */
967    private int mPendingVerificationToken = 0;
968
969    volatile boolean mSystemReady;
970    volatile boolean mSafeMode;
971    volatile boolean mHasSystemUidErrors;
972    private volatile boolean mEphemeralAppsDisabled;
973
974    ApplicationInfo mAndroidApplication;
975    final ActivityInfo mResolveActivity = new ActivityInfo();
976    final ResolveInfo mResolveInfo = new ResolveInfo();
977    ComponentName mResolveComponentName;
978    PackageParser.Package mPlatformPackage;
979    ComponentName mCustomResolverComponentName;
980
981    boolean mResolverReplaced = false;
982
983    private final @Nullable ComponentName mIntentFilterVerifierComponent;
984    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
985
986    private int mIntentFilterVerificationToken = 0;
987
988    /** The service connection to the ephemeral resolver */
989    final EphemeralResolverConnection mInstantAppResolverConnection;
990    /** Component used to show resolver settings for Instant Apps */
991    final ComponentName mInstantAppResolverSettingsComponent;
992
993    /** Activity used to install instant applications */
994    ActivityInfo mInstantAppInstallerActivity;
995    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
996
997    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
998            = new SparseArray<IntentFilterVerificationState>();
999
1000    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1001
1002    // List of packages names to keep cached, even if they are uninstalled for all users
1003    private List<String> mKeepUninstalledPackages;
1004
1005    private UserManagerInternal mUserManagerInternal;
1006
1007    private DeviceIdleController.LocalService mDeviceIdleController;
1008
1009    private File mCacheDir;
1010
1011    private ArraySet<String> mPrivappPermissionsViolations;
1012
1013    private Future<?> mPrepareAppDataFuture;
1014
1015    private static class IFVerificationParams {
1016        PackageParser.Package pkg;
1017        boolean replacing;
1018        int userId;
1019        int verifierUid;
1020
1021        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1022                int _userId, int _verifierUid) {
1023            pkg = _pkg;
1024            replacing = _replacing;
1025            userId = _userId;
1026            replacing = _replacing;
1027            verifierUid = _verifierUid;
1028        }
1029    }
1030
1031    private interface IntentFilterVerifier<T extends IntentFilter> {
1032        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1033                                               T filter, String packageName);
1034        void startVerifications(int userId);
1035        void receiveVerificationResponse(int verificationId);
1036    }
1037
1038    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1039        private Context mContext;
1040        private ComponentName mIntentFilterVerifierComponent;
1041        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1042
1043        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1044            mContext = context;
1045            mIntentFilterVerifierComponent = verifierComponent;
1046        }
1047
1048        private String getDefaultScheme() {
1049            return IntentFilter.SCHEME_HTTPS;
1050        }
1051
1052        @Override
1053        public void startVerifications(int userId) {
1054            // Launch verifications requests
1055            int count = mCurrentIntentFilterVerifications.size();
1056            for (int n=0; n<count; n++) {
1057                int verificationId = mCurrentIntentFilterVerifications.get(n);
1058                final IntentFilterVerificationState ivs =
1059                        mIntentFilterVerificationStates.get(verificationId);
1060
1061                String packageName = ivs.getPackageName();
1062
1063                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1064                final int filterCount = filters.size();
1065                ArraySet<String> domainsSet = new ArraySet<>();
1066                for (int m=0; m<filterCount; m++) {
1067                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1068                    domainsSet.addAll(filter.getHostsList());
1069                }
1070                synchronized (mPackages) {
1071                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1072                            packageName, domainsSet) != null) {
1073                        scheduleWriteSettingsLocked();
1074                    }
1075                }
1076                sendVerificationRequest(verificationId, ivs);
1077            }
1078            mCurrentIntentFilterVerifications.clear();
1079        }
1080
1081        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1082            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1085                    verificationId);
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1088                    getDefaultScheme());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1091                    ivs.getHostsString());
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1094                    ivs.getPackageName());
1095            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1096            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1097
1098            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1099            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1100                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1101                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1102
1103            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1104            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1105                    "Sending IntentFilter verification broadcast");
1106        }
1107
1108        public void receiveVerificationResponse(int verificationId) {
1109            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1110
1111            final boolean verified = ivs.isVerified();
1112
1113            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1114            final int count = filters.size();
1115            if (DEBUG_DOMAIN_VERIFICATION) {
1116                Slog.i(TAG, "Received verification response " + verificationId
1117                        + " for " + count + " filters, verified=" + verified);
1118            }
1119            for (int n=0; n<count; n++) {
1120                PackageParser.ActivityIntentInfo filter = filters.get(n);
1121                filter.setVerified(verified);
1122
1123                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1124                        + " verified with result:" + verified + " and hosts:"
1125                        + ivs.getHostsString());
1126            }
1127
1128            mIntentFilterVerificationStates.remove(verificationId);
1129
1130            final String packageName = ivs.getPackageName();
1131            IntentFilterVerificationInfo ivi = null;
1132
1133            synchronized (mPackages) {
1134                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1135            }
1136            if (ivi == null) {
1137                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1138                        + verificationId + " packageName:" + packageName);
1139                return;
1140            }
1141            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1142                    "Updating IntentFilterVerificationInfo for package " + packageName
1143                            +" verificationId:" + verificationId);
1144
1145            synchronized (mPackages) {
1146                if (verified) {
1147                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1148                } else {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1150                }
1151                scheduleWriteSettingsLocked();
1152
1153                final int userId = ivs.getUserId();
1154                if (userId != UserHandle.USER_ALL) {
1155                    final int userStatus =
1156                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1157
1158                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1159                    boolean needUpdate = false;
1160
1161                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1162                    // already been set by the User thru the Disambiguation dialog
1163                    switch (userStatus) {
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                            } else {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1169                            }
1170                            needUpdate = true;
1171                            break;
1172
1173                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1174                            if (verified) {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1176                                needUpdate = true;
1177                            }
1178                            break;
1179
1180                        default:
1181                            // Nothing to do
1182                    }
1183
1184                    if (needUpdate) {
1185                        mSettings.updateIntentFilterVerificationStatusLPw(
1186                                packageName, updatedStatus, userId);
1187                        scheduleWritePackageRestrictionsLocked(userId);
1188                    }
1189                }
1190            }
1191        }
1192
1193        @Override
1194        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1195                    ActivityIntentInfo filter, String packageName) {
1196            if (!hasValidDomains(filter)) {
1197                return false;
1198            }
1199            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1200            if (ivs == null) {
1201                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1202                        packageName);
1203            }
1204            if (DEBUG_DOMAIN_VERIFICATION) {
1205                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1206            }
1207            ivs.addFilter(filter);
1208            return true;
1209        }
1210
1211        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1212                int userId, int verificationId, String packageName) {
1213            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1214                    verifierUid, userId, packageName);
1215            ivs.setPendingState();
1216            synchronized (mPackages) {
1217                mIntentFilterVerificationStates.append(verificationId, ivs);
1218                mCurrentIntentFilterVerifications.add(verificationId);
1219            }
1220            return ivs;
1221        }
1222    }
1223
1224    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1225        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1226                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1227                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1228    }
1229
1230    // Set of pending broadcasts for aggregating enable/disable of components.
1231    static class PendingPackageBroadcasts {
1232        // for each user id, a map of <package name -> components within that package>
1233        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1234
1235        public PendingPackageBroadcasts() {
1236            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1237        }
1238
1239        public ArrayList<String> get(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1241            return packages.get(packageName);
1242        }
1243
1244        public void put(int userId, String packageName, ArrayList<String> components) {
1245            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1246            packages.put(packageName, components);
1247        }
1248
1249        public void remove(int userId, String packageName) {
1250            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1251            if (packages != null) {
1252                packages.remove(packageName);
1253            }
1254        }
1255
1256        public void remove(int userId) {
1257            mUidMap.remove(userId);
1258        }
1259
1260        public int userIdCount() {
1261            return mUidMap.size();
1262        }
1263
1264        public int userIdAt(int n) {
1265            return mUidMap.keyAt(n);
1266        }
1267
1268        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1269            return mUidMap.get(userId);
1270        }
1271
1272        public int size() {
1273            // total number of pending broadcast entries across all userIds
1274            int num = 0;
1275            for (int i = 0; i< mUidMap.size(); i++) {
1276                num += mUidMap.valueAt(i).size();
1277            }
1278            return num;
1279        }
1280
1281        public void clear() {
1282            mUidMap.clear();
1283        }
1284
1285        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1286            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1287            if (map == null) {
1288                map = new ArrayMap<String, ArrayList<String>>();
1289                mUidMap.put(userId, map);
1290            }
1291            return map;
1292        }
1293    }
1294    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1295
1296    // Service Connection to remote media container service to copy
1297    // package uri's from external media onto secure containers
1298    // or internal storage.
1299    private IMediaContainerService mContainerService = null;
1300
1301    static final int SEND_PENDING_BROADCAST = 1;
1302    static final int MCS_BOUND = 3;
1303    static final int END_COPY = 4;
1304    static final int INIT_COPY = 5;
1305    static final int MCS_UNBIND = 6;
1306    static final int START_CLEANING_PACKAGE = 7;
1307    static final int FIND_INSTALL_LOC = 8;
1308    static final int POST_INSTALL = 9;
1309    static final int MCS_RECONNECT = 10;
1310    static final int MCS_GIVE_UP = 11;
1311    static final int UPDATED_MEDIA_STATUS = 12;
1312    static final int WRITE_SETTINGS = 13;
1313    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1314    static final int PACKAGE_VERIFIED = 15;
1315    static final int CHECK_PENDING_VERIFICATION = 16;
1316    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1317    static final int INTENT_FILTER_VERIFIED = 18;
1318    static final int WRITE_PACKAGE_LIST = 19;
1319    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1320
1321    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1322
1323    // Delay time in millisecs
1324    static final int BROADCAST_DELAY = 10 * 1000;
1325
1326    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1327            2 * 60 * 60 * 1000L; /* two hours */
1328
1329    static UserManagerService sUserManager;
1330
1331    // Stores a list of users whose package restrictions file needs to be updated
1332    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1333
1334    final private DefaultContainerConnection mDefContainerConn =
1335            new DefaultContainerConnection();
1336    class DefaultContainerConnection implements ServiceConnection {
1337        public void onServiceConnected(ComponentName name, IBinder service) {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1339            final IMediaContainerService imcs = IMediaContainerService.Stub
1340                    .asInterface(Binder.allowBlocking(service));
1341            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1342        }
1343
1344        public void onServiceDisconnected(ComponentName name) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1346        }
1347    }
1348
1349    // Recordkeeping of restore-after-install operations that are currently in flight
1350    // between the Package Manager and the Backup Manager
1351    static class PostInstallData {
1352        public InstallArgs args;
1353        public PackageInstalledInfo res;
1354
1355        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1356            args = _a;
1357            res = _r;
1358        }
1359    }
1360
1361    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1362    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1363
1364    // XML tags for backup/restore of various bits of state
1365    private static final String TAG_PREFERRED_BACKUP = "pa";
1366    private static final String TAG_DEFAULT_APPS = "da";
1367    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1368
1369    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1370    private static final String TAG_ALL_GRANTS = "rt-grants";
1371    private static final String TAG_GRANT = "grant";
1372    private static final String ATTR_PACKAGE_NAME = "pkg";
1373
1374    private static final String TAG_PERMISSION = "perm";
1375    private static final String ATTR_PERMISSION_NAME = "name";
1376    private static final String ATTR_IS_GRANTED = "g";
1377    private static final String ATTR_USER_SET = "set";
1378    private static final String ATTR_USER_FIXED = "fixed";
1379    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1380
1381    // System/policy permission grants are not backed up
1382    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1383            FLAG_PERMISSION_POLICY_FIXED
1384            | FLAG_PERMISSION_SYSTEM_FIXED
1385            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1386
1387    // And we back up these user-adjusted states
1388    private static final int USER_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_USER_SET
1390            | FLAG_PERMISSION_USER_FIXED
1391            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1392
1393    final @Nullable String mRequiredVerifierPackage;
1394    final @NonNull String mRequiredInstallerPackage;
1395    final @NonNull String mRequiredUninstallerPackage;
1396    final @Nullable String mSetupWizardPackage;
1397    final @Nullable String mStorageManagerPackage;
1398    final @NonNull String mServicesSystemSharedLibraryPackageName;
1399    final @NonNull String mSharedSystemSharedLibraryPackageName;
1400
1401    final boolean mPermissionReviewRequired;
1402
1403    private final PackageUsage mPackageUsage = new PackageUsage();
1404    private final CompilerStats mCompilerStats = new CompilerStats();
1405
1406    class PackageHandler extends Handler {
1407        private boolean mBound = false;
1408        final ArrayList<HandlerParams> mPendingInstalls =
1409            new ArrayList<HandlerParams>();
1410
1411        private boolean connectToService() {
1412            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1413                    " DefaultContainerService");
1414            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1416            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1417                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1418                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419                mBound = true;
1420                return true;
1421            }
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423            return false;
1424        }
1425
1426        private void disconnectService() {
1427            mContainerService = null;
1428            mBound = false;
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1430            mContext.unbindService(mDefContainerConn);
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432        }
1433
1434        PackageHandler(Looper looper) {
1435            super(looper);
1436        }
1437
1438        public void handleMessage(Message msg) {
1439            try {
1440                doHandleMessage(msg);
1441            } finally {
1442                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1443            }
1444        }
1445
1446        void doHandleMessage(Message msg) {
1447            switch (msg.what) {
1448                case INIT_COPY: {
1449                    HandlerParams params = (HandlerParams) msg.obj;
1450                    int idx = mPendingInstalls.size();
1451                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1452                    // If a bind was already initiated we dont really
1453                    // need to do anything. The pending install
1454                    // will be processed later on.
1455                    if (!mBound) {
1456                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                System.identityHashCode(mHandler));
1458                        // If this is the only one pending we might
1459                        // have to bind to the service again.
1460                        if (!connectToService()) {
1461                            Slog.e(TAG, "Failed to bind to media container service");
1462                            params.serviceError();
1463                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                    System.identityHashCode(mHandler));
1465                            if (params.traceMethod != null) {
1466                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1467                                        params.traceCookie);
1468                            }
1469                            return;
1470                        } else {
1471                            // Once we bind to the service, the first
1472                            // pending request will be processed.
1473                            mPendingInstalls.add(idx, params);
1474                        }
1475                    } else {
1476                        mPendingInstalls.add(idx, params);
1477                        // Already bound to the service. Just make
1478                        // sure we trigger off processing the first request.
1479                        if (idx == 0) {
1480                            mHandler.sendEmptyMessage(MCS_BOUND);
1481                        }
1482                    }
1483                    break;
1484                }
1485                case MCS_BOUND: {
1486                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1487                    if (msg.obj != null) {
1488                        mContainerService = (IMediaContainerService) msg.obj;
1489                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1490                                System.identityHashCode(mHandler));
1491                    }
1492                    if (mContainerService == null) {
1493                        if (!mBound) {
1494                            // Something seriously wrong since we are not bound and we are not
1495                            // waiting for connection. Bail out.
1496                            Slog.e(TAG, "Cannot bind to media container service");
1497                            for (HandlerParams params : mPendingInstalls) {
1498                                // Indicate service bind error
1499                                params.serviceError();
1500                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                        System.identityHashCode(params));
1502                                if (params.traceMethod != null) {
1503                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1504                                            params.traceMethod, params.traceCookie);
1505                                }
1506                                return;
1507                            }
1508                            mPendingInstalls.clear();
1509                        } else {
1510                            Slog.w(TAG, "Waiting to connect to media container service");
1511                        }
1512                    } else if (mPendingInstalls.size() > 0) {
1513                        HandlerParams params = mPendingInstalls.get(0);
1514                        if (params != null) {
1515                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1516                                    System.identityHashCode(params));
1517                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1518                            if (params.startCopy()) {
1519                                // We are done...  look for more work or to
1520                                // go idle.
1521                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1522                                        "Checking for more work or unbind...");
1523                                // Delete pending install
1524                                if (mPendingInstalls.size() > 0) {
1525                                    mPendingInstalls.remove(0);
1526                                }
1527                                if (mPendingInstalls.size() == 0) {
1528                                    if (mBound) {
1529                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1530                                                "Posting delayed MCS_UNBIND");
1531                                        removeMessages(MCS_UNBIND);
1532                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1533                                        // Unbind after a little delay, to avoid
1534                                        // continual thrashing.
1535                                        sendMessageDelayed(ubmsg, 10000);
1536                                    }
1537                                } else {
1538                                    // There are more pending requests in queue.
1539                                    // Just post MCS_BOUND message to trigger processing
1540                                    // of next pending install.
1541                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1542                                            "Posting MCS_BOUND for next work");
1543                                    mHandler.sendEmptyMessage(MCS_BOUND);
1544                                }
1545                            }
1546                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1547                        }
1548                    } else {
1549                        // Should never happen ideally.
1550                        Slog.w(TAG, "Empty queue");
1551                    }
1552                    break;
1553                }
1554                case MCS_RECONNECT: {
1555                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1556                    if (mPendingInstalls.size() > 0) {
1557                        if (mBound) {
1558                            disconnectService();
1559                        }
1560                        if (!connectToService()) {
1561                            Slog.e(TAG, "Failed to bind to media container service");
1562                            for (HandlerParams params : mPendingInstalls) {
1563                                // Indicate service bind error
1564                                params.serviceError();
1565                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1566                                        System.identityHashCode(params));
1567                            }
1568                            mPendingInstalls.clear();
1569                        }
1570                    }
1571                    break;
1572                }
1573                case MCS_UNBIND: {
1574                    // If there is no actual work left, then time to unbind.
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1576
1577                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1578                        if (mBound) {
1579                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1580
1581                            disconnectService();
1582                        }
1583                    } else if (mPendingInstalls.size() > 0) {
1584                        // There are more pending requests in queue.
1585                        // Just post MCS_BOUND message to trigger processing
1586                        // of next pending install.
1587                        mHandler.sendEmptyMessage(MCS_BOUND);
1588                    }
1589
1590                    break;
1591                }
1592                case MCS_GIVE_UP: {
1593                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1594                    HandlerParams params = mPendingInstalls.remove(0);
1595                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1596                            System.identityHashCode(params));
1597                    break;
1598                }
1599                case SEND_PENDING_BROADCAST: {
1600                    String packages[];
1601                    ArrayList<String> components[];
1602                    int size = 0;
1603                    int uids[];
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1605                    synchronized (mPackages) {
1606                        if (mPendingBroadcasts == null) {
1607                            return;
1608                        }
1609                        size = mPendingBroadcasts.size();
1610                        if (size <= 0) {
1611                            // Nothing to be done. Just return
1612                            return;
1613                        }
1614                        packages = new String[size];
1615                        components = new ArrayList[size];
1616                        uids = new int[size];
1617                        int i = 0;  // filling out the above arrays
1618
1619                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1620                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1621                            Iterator<Map.Entry<String, ArrayList<String>>> it
1622                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1623                                            .entrySet().iterator();
1624                            while (it.hasNext() && i < size) {
1625                                Map.Entry<String, ArrayList<String>> ent = it.next();
1626                                packages[i] = ent.getKey();
1627                                components[i] = ent.getValue();
1628                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1629                                uids[i] = (ps != null)
1630                                        ? UserHandle.getUid(packageUserId, ps.appId)
1631                                        : -1;
1632                                i++;
1633                            }
1634                        }
1635                        size = i;
1636                        mPendingBroadcasts.clear();
1637                    }
1638                    // Send broadcasts
1639                    for (int i = 0; i < size; i++) {
1640                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1641                    }
1642                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1643                    break;
1644                }
1645                case START_CLEANING_PACKAGE: {
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1647                    final String packageName = (String)msg.obj;
1648                    final int userId = msg.arg1;
1649                    final boolean andCode = msg.arg2 != 0;
1650                    synchronized (mPackages) {
1651                        if (userId == UserHandle.USER_ALL) {
1652                            int[] users = sUserManager.getUserIds();
1653                            for (int user : users) {
1654                                mSettings.addPackageToCleanLPw(
1655                                        new PackageCleanItem(user, packageName, andCode));
1656                            }
1657                        } else {
1658                            mSettings.addPackageToCleanLPw(
1659                                    new PackageCleanItem(userId, packageName, andCode));
1660                        }
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                    startCleaningPackages();
1664                } break;
1665                case POST_INSTALL: {
1666                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1667
1668                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1669                    final boolean didRestore = (msg.arg2 != 0);
1670                    mRunningInstalls.delete(msg.arg1);
1671
1672                    if (data != null) {
1673                        InstallArgs args = data.args;
1674                        PackageInstalledInfo parentRes = data.res;
1675
1676                        final boolean grantPermissions = (args.installFlags
1677                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1678                        final boolean killApp = (args.installFlags
1679                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1680                        final String[] grantedPermissions = args.installGrantPermissions;
1681
1682                        // Handle the parent package
1683                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1684                                grantedPermissions, didRestore, args.installerPackageName,
1685                                args.observer);
1686
1687                        // Handle the child packages
1688                        final int childCount = (parentRes.addedChildPackages != null)
1689                                ? parentRes.addedChildPackages.size() : 0;
1690                        for (int i = 0; i < childCount; i++) {
1691                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1692                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1693                                    grantedPermissions, false, args.installerPackageName,
1694                                    args.observer);
1695                        }
1696
1697                        // Log tracing if needed
1698                        if (args.traceMethod != null) {
1699                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1700                                    args.traceCookie);
1701                        }
1702                    } else {
1703                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1704                    }
1705
1706                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1707                } break;
1708                case UPDATED_MEDIA_STATUS: {
1709                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1710                    boolean reportStatus = msg.arg1 == 1;
1711                    boolean doGc = msg.arg2 == 1;
1712                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1713                    if (doGc) {
1714                        // Force a gc to clear up stale containers.
1715                        Runtime.getRuntime().gc();
1716                    }
1717                    if (msg.obj != null) {
1718                        @SuppressWarnings("unchecked")
1719                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1720                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1721                        // Unload containers
1722                        unloadAllContainers(args);
1723                    }
1724                    if (reportStatus) {
1725                        try {
1726                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1727                                    "Invoking StorageManagerService call back");
1728                            PackageHelper.getStorageManager().finishMediaUpdate();
1729                        } catch (RemoteException e) {
1730                            Log.e(TAG, "StorageManagerService not running?");
1731                        }
1732                    }
1733                } break;
1734                case WRITE_SETTINGS: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_SETTINGS);
1738                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1739                        mSettings.writeLPr();
1740                        mDirtyUsers.clear();
1741                    }
1742                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1743                } break;
1744                case WRITE_PACKAGE_RESTRICTIONS: {
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1746                    synchronized (mPackages) {
1747                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1748                        for (int userId : mDirtyUsers) {
1749                            mSettings.writePackageRestrictionsLPr(userId);
1750                        }
1751                        mDirtyUsers.clear();
1752                    }
1753                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1754                } break;
1755                case WRITE_PACKAGE_LIST: {
1756                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1757                    synchronized (mPackages) {
1758                        removeMessages(WRITE_PACKAGE_LIST);
1759                        mSettings.writePackageListLPr(msg.arg1);
1760                    }
1761                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1762                } break;
1763                case CHECK_PENDING_VERIFICATION: {
1764                    final int verificationId = msg.arg1;
1765                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1766
1767                    if ((state != null) && !state.timeoutExtended()) {
1768                        final InstallArgs args = state.getInstallArgs();
1769                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1770
1771                        Slog.i(TAG, "Verification timed out for " + originUri);
1772                        mPendingVerification.remove(verificationId);
1773
1774                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1775
1776                        final UserHandle user = args.getUser();
1777                        if (getDefaultVerificationResponse(user)
1778                                == PackageManager.VERIFICATION_ALLOW) {
1779                            Slog.i(TAG, "Continuing with installation of " + originUri);
1780                            state.setVerifierResponse(Binder.getCallingUid(),
1781                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1782                            broadcastPackageVerified(verificationId, originUri,
1783                                    PackageManager.VERIFICATION_ALLOW, user);
1784                            try {
1785                                ret = args.copyApk(mContainerService, true);
1786                            } catch (RemoteException e) {
1787                                Slog.e(TAG, "Could not contact the ContainerService");
1788                            }
1789                        } else {
1790                            broadcastPackageVerified(verificationId, originUri,
1791                                    PackageManager.VERIFICATION_REJECT, user);
1792                        }
1793
1794                        Trace.asyncTraceEnd(
1795                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1796
1797                        processPendingInstall(args, ret);
1798                        mHandler.sendEmptyMessage(MCS_UNBIND);
1799                    }
1800                    break;
1801                }
1802                case PACKAGE_VERIFIED: {
1803                    final int verificationId = msg.arg1;
1804
1805                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1806                    if (state == null) {
1807                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1808                        break;
1809                    }
1810
1811                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1812
1813                    state.setVerifierResponse(response.callerUid, response.code);
1814
1815                    if (state.isVerificationComplete()) {
1816                        mPendingVerification.remove(verificationId);
1817
1818                        final InstallArgs args = state.getInstallArgs();
1819                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1820
1821                        int ret;
1822                        if (state.isInstallAllowed()) {
1823                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1824                            broadcastPackageVerified(verificationId, originUri,
1825                                    response.code, state.getInstallArgs().getUser());
1826                            try {
1827                                ret = args.copyApk(mContainerService, true);
1828                            } catch (RemoteException e) {
1829                                Slog.e(TAG, "Could not contact the ContainerService");
1830                            }
1831                        } else {
1832                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1833                        }
1834
1835                        Trace.asyncTraceEnd(
1836                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1837
1838                        processPendingInstall(args, ret);
1839                        mHandler.sendEmptyMessage(MCS_UNBIND);
1840                    }
1841
1842                    break;
1843                }
1844                case START_INTENT_FILTER_VERIFICATIONS: {
1845                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1846                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1847                            params.replacing, params.pkg);
1848                    break;
1849                }
1850                case INTENT_FILTER_VERIFIED: {
1851                    final int verificationId = msg.arg1;
1852
1853                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1854                            verificationId);
1855                    if (state == null) {
1856                        Slog.w(TAG, "Invalid IntentFilter verification token "
1857                                + verificationId + " received");
1858                        break;
1859                    }
1860
1861                    final int userId = state.getUserId();
1862
1863                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1864                            "Processing IntentFilter verification with token:"
1865                            + verificationId + " and userId:" + userId);
1866
1867                    final IntentFilterVerificationResponse response =
1868                            (IntentFilterVerificationResponse) msg.obj;
1869
1870                    state.setVerifierResponse(response.callerUid, response.code);
1871
1872                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1873                            "IntentFilter verification with token:" + verificationId
1874                            + " and userId:" + userId
1875                            + " is settings verifier response with response code:"
1876                            + response.code);
1877
1878                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1879                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1880                                + response.getFailedDomainsString());
1881                    }
1882
1883                    if (state.isVerificationComplete()) {
1884                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1885                    } else {
1886                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1887                                "IntentFilter verification with token:" + verificationId
1888                                + " was not said to be complete");
1889                    }
1890
1891                    break;
1892                }
1893                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1894                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1895                            mInstantAppResolverConnection,
1896                            (InstantAppRequest) msg.obj,
1897                            mInstantAppInstallerActivity,
1898                            mHandler);
1899                }
1900            }
1901        }
1902    }
1903
1904    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1905            boolean killApp, String[] grantedPermissions,
1906            boolean launchedForRestore, String installerPackage,
1907            IPackageInstallObserver2 installObserver) {
1908        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1909            // Send the removed broadcasts
1910            if (res.removedInfo != null) {
1911                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1912            }
1913
1914            // Now that we successfully installed the package, grant runtime
1915            // permissions if requested before broadcasting the install. Also
1916            // for legacy apps in permission review mode we clear the permission
1917            // review flag which is used to emulate runtime permissions for
1918            // legacy apps.
1919            if (grantPermissions) {
1920                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1921            }
1922
1923            final boolean update = res.removedInfo != null
1924                    && res.removedInfo.removedPackage != null;
1925            final String origInstallerPackageName = res.removedInfo != null
1926                    ? res.removedInfo.installerPackageName : null;
1927
1928            // If this is the first time we have child packages for a disabled privileged
1929            // app that had no children, we grant requested runtime permissions to the new
1930            // children if the parent on the system image had them already granted.
1931            if (res.pkg.parentPackage != null) {
1932                synchronized (mPackages) {
1933                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1934                }
1935            }
1936
1937            synchronized (mPackages) {
1938                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1939            }
1940
1941            final String packageName = res.pkg.applicationInfo.packageName;
1942
1943            // Determine the set of users who are adding this package for
1944            // the first time vs. those who are seeing an update.
1945            int[] firstUsers = EMPTY_INT_ARRAY;
1946            int[] updateUsers = EMPTY_INT_ARRAY;
1947            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1948            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1949            for (int newUser : res.newUsers) {
1950                if (ps.getInstantApp(newUser)) {
1951                    continue;
1952                }
1953                if (allNewUsers) {
1954                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1955                    continue;
1956                }
1957                boolean isNew = true;
1958                for (int origUser : res.origUsers) {
1959                    if (origUser == newUser) {
1960                        isNew = false;
1961                        break;
1962                    }
1963                }
1964                if (isNew) {
1965                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1966                } else {
1967                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1968                }
1969            }
1970
1971            // Send installed broadcasts if the package is not a static shared lib.
1972            if (res.pkg.staticSharedLibName == null) {
1973                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1974
1975                // Send added for users that see the package for the first time
1976                // sendPackageAddedForNewUsers also deals with system apps
1977                int appId = UserHandle.getAppId(res.uid);
1978                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1979                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1980
1981                // Send added for users that don't see the package for the first time
1982                Bundle extras = new Bundle(1);
1983                extras.putInt(Intent.EXTRA_UID, res.uid);
1984                if (update) {
1985                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1986                }
1987                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1988                        extras, 0 /*flags*/,
1989                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1990                if (origInstallerPackageName != null) {
1991                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1992                            extras, 0 /*flags*/,
1993                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1994                }
1995
1996                // Send replaced for users that don't see the package for the first time
1997                if (update) {
1998                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1999                            packageName, extras, 0 /*flags*/,
2000                            null /*targetPackage*/, null /*finishedReceiver*/,
2001                            updateUsers);
2002                    if (origInstallerPackageName != null) {
2003                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2004                                extras, 0 /*flags*/,
2005                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2006                    }
2007                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2008                            null /*package*/, null /*extras*/, 0 /*flags*/,
2009                            packageName /*targetPackage*/,
2010                            null /*finishedReceiver*/, updateUsers);
2011                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2012                    // First-install and we did a restore, so we're responsible for the
2013                    // first-launch broadcast.
2014                    if (DEBUG_BACKUP) {
2015                        Slog.i(TAG, "Post-restore of " + packageName
2016                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2017                    }
2018                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2019                }
2020
2021                // Send broadcast package appeared if forward locked/external for all users
2022                // treat asec-hosted packages like removable media on upgrade
2023                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2024                    if (DEBUG_INSTALL) {
2025                        Slog.i(TAG, "upgrading pkg " + res.pkg
2026                                + " is ASEC-hosted -> AVAILABLE");
2027                    }
2028                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2029                    ArrayList<String> pkgList = new ArrayList<>(1);
2030                    pkgList.add(packageName);
2031                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2032                }
2033            }
2034
2035            // Work that needs to happen on first install within each user
2036            if (firstUsers != null && firstUsers.length > 0) {
2037                synchronized (mPackages) {
2038                    for (int userId : firstUsers) {
2039                        // If this app is a browser and it's newly-installed for some
2040                        // users, clear any default-browser state in those users. The
2041                        // app's nature doesn't depend on the user, so we can just check
2042                        // its browser nature in any user and generalize.
2043                        if (packageIsBrowser(packageName, userId)) {
2044                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2045                        }
2046
2047                        // We may also need to apply pending (restored) runtime
2048                        // permission grants within these users.
2049                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2050                    }
2051                }
2052            }
2053
2054            // Log current value of "unknown sources" setting
2055            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2056                    getUnknownSourcesSettings());
2057
2058            // Remove the replaced package's older resources safely now
2059            // We delete after a gc for applications  on sdcard.
2060            if (res.removedInfo != null && res.removedInfo.args != null) {
2061                Runtime.getRuntime().gc();
2062                synchronized (mInstallLock) {
2063                    res.removedInfo.args.doPostDeleteLI(true);
2064                }
2065            } else {
2066                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2067                // and not block here.
2068                VMRuntime.getRuntime().requestConcurrentGC();
2069            }
2070
2071            // Notify DexManager that the package was installed for new users.
2072            // The updated users should already be indexed and the package code paths
2073            // should not change.
2074            // Don't notify the manager for ephemeral apps as they are not expected to
2075            // survive long enough to benefit of background optimizations.
2076            for (int userId : firstUsers) {
2077                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2078                // There's a race currently where some install events may interleave with an uninstall.
2079                // This can lead to package info being null (b/36642664).
2080                if (info != null) {
2081                    mDexManager.notifyPackageInstalled(info, userId);
2082                }
2083            }
2084        }
2085
2086        // If someone is watching installs - notify them
2087        if (installObserver != null) {
2088            try {
2089                Bundle extras = extrasForInstallResult(res);
2090                installObserver.onPackageInstalled(res.name, res.returnCode,
2091                        res.returnMsg, extras);
2092            } catch (RemoteException e) {
2093                Slog.i(TAG, "Observer no longer exists.");
2094            }
2095        }
2096    }
2097
2098    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2099            PackageParser.Package pkg) {
2100        if (pkg.parentPackage == null) {
2101            return;
2102        }
2103        if (pkg.requestedPermissions == null) {
2104            return;
2105        }
2106        final PackageSetting disabledSysParentPs = mSettings
2107                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2108        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2109                || !disabledSysParentPs.isPrivileged()
2110                || (disabledSysParentPs.childPackageNames != null
2111                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2112            return;
2113        }
2114        final int[] allUserIds = sUserManager.getUserIds();
2115        final int permCount = pkg.requestedPermissions.size();
2116        for (int i = 0; i < permCount; i++) {
2117            String permission = pkg.requestedPermissions.get(i);
2118            BasePermission bp = mSettings.mPermissions.get(permission);
2119            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2120                continue;
2121            }
2122            for (int userId : allUserIds) {
2123                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2124                        permission, userId)) {
2125                    grantRuntimePermission(pkg.packageName, permission, userId);
2126                }
2127            }
2128        }
2129    }
2130
2131    private StorageEventListener mStorageListener = new StorageEventListener() {
2132        @Override
2133        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2134            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2135                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2136                    final String volumeUuid = vol.getFsUuid();
2137
2138                    // Clean up any users or apps that were removed or recreated
2139                    // while this volume was missing
2140                    sUserManager.reconcileUsers(volumeUuid);
2141                    reconcileApps(volumeUuid);
2142
2143                    // Clean up any install sessions that expired or were
2144                    // cancelled while this volume was missing
2145                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2146
2147                    loadPrivatePackages(vol);
2148
2149                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2150                    unloadPrivatePackages(vol);
2151                }
2152            }
2153
2154            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2155                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2156                    updateExternalMediaStatus(true, false);
2157                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2158                    updateExternalMediaStatus(false, false);
2159                }
2160            }
2161        }
2162
2163        @Override
2164        public void onVolumeForgotten(String fsUuid) {
2165            if (TextUtils.isEmpty(fsUuid)) {
2166                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2167                return;
2168            }
2169
2170            // Remove any apps installed on the forgotten volume
2171            synchronized (mPackages) {
2172                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2173                for (PackageSetting ps : packages) {
2174                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2175                    deletePackageVersioned(new VersionedPackage(ps.name,
2176                            PackageManager.VERSION_CODE_HIGHEST),
2177                            new LegacyPackageDeleteObserver(null).getBinder(),
2178                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2179                    // Try very hard to release any references to this package
2180                    // so we don't risk the system server being killed due to
2181                    // open FDs
2182                    AttributeCache.instance().removePackage(ps.name);
2183                }
2184
2185                mSettings.onVolumeForgotten(fsUuid);
2186                mSettings.writeLPr();
2187            }
2188        }
2189    };
2190
2191    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2192            String[] grantedPermissions) {
2193        for (int userId : userIds) {
2194            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2195        }
2196    }
2197
2198    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2199            String[] grantedPermissions) {
2200        PackageSetting ps = (PackageSetting) pkg.mExtras;
2201        if (ps == null) {
2202            return;
2203        }
2204
2205        PermissionsState permissionsState = ps.getPermissionsState();
2206
2207        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2208                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2209
2210        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2211                >= Build.VERSION_CODES.M;
2212
2213        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2214
2215        for (String permission : pkg.requestedPermissions) {
2216            final BasePermission bp;
2217            synchronized (mPackages) {
2218                bp = mSettings.mPermissions.get(permission);
2219            }
2220            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2221                    && (!instantApp || bp.isInstant())
2222                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2223                    && (grantedPermissions == null
2224                           || ArrayUtils.contains(grantedPermissions, permission))) {
2225                final int flags = permissionsState.getPermissionFlags(permission, userId);
2226                if (supportsRuntimePermissions) {
2227                    // Installer cannot change immutable permissions.
2228                    if ((flags & immutableFlags) == 0) {
2229                        grantRuntimePermission(pkg.packageName, permission, userId);
2230                    }
2231                } else if (mPermissionReviewRequired) {
2232                    // In permission review mode we clear the review flag when we
2233                    // are asked to install the app with all permissions granted.
2234                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2235                        updatePermissionFlags(permission, pkg.packageName,
2236                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2237                    }
2238                }
2239            }
2240        }
2241    }
2242
2243    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2244        Bundle extras = null;
2245        switch (res.returnCode) {
2246            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2247                extras = new Bundle();
2248                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2249                        res.origPermission);
2250                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2251                        res.origPackage);
2252                break;
2253            }
2254            case PackageManager.INSTALL_SUCCEEDED: {
2255                extras = new Bundle();
2256                extras.putBoolean(Intent.EXTRA_REPLACING,
2257                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2258                break;
2259            }
2260        }
2261        return extras;
2262    }
2263
2264    void scheduleWriteSettingsLocked() {
2265        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2266            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2267        }
2268    }
2269
2270    void scheduleWritePackageListLocked(int userId) {
2271        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2272            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2273            msg.arg1 = userId;
2274            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2275        }
2276    }
2277
2278    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2279        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2280        scheduleWritePackageRestrictionsLocked(userId);
2281    }
2282
2283    void scheduleWritePackageRestrictionsLocked(int userId) {
2284        final int[] userIds = (userId == UserHandle.USER_ALL)
2285                ? sUserManager.getUserIds() : new int[]{userId};
2286        for (int nextUserId : userIds) {
2287            if (!sUserManager.exists(nextUserId)) return;
2288            mDirtyUsers.add(nextUserId);
2289            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2290                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2291            }
2292        }
2293    }
2294
2295    public static PackageManagerService main(Context context, Installer installer,
2296            boolean factoryTest, boolean onlyCore) {
2297        // Self-check for initial settings.
2298        PackageManagerServiceCompilerMapping.checkProperties();
2299
2300        PackageManagerService m = new PackageManagerService(context, installer,
2301                factoryTest, onlyCore);
2302        m.enableSystemUserPackages();
2303        ServiceManager.addService("package", m);
2304        return m;
2305    }
2306
2307    private void enableSystemUserPackages() {
2308        if (!UserManager.isSplitSystemUser()) {
2309            return;
2310        }
2311        // For system user, enable apps based on the following conditions:
2312        // - app is whitelisted or belong to one of these groups:
2313        //   -- system app which has no launcher icons
2314        //   -- system app which has INTERACT_ACROSS_USERS permission
2315        //   -- system IME app
2316        // - app is not in the blacklist
2317        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2318        Set<String> enableApps = new ArraySet<>();
2319        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2320                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2321                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2322        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2323        enableApps.addAll(wlApps);
2324        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2325                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2326        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2327        enableApps.removeAll(blApps);
2328        Log.i(TAG, "Applications installed for system user: " + enableApps);
2329        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2330                UserHandle.SYSTEM);
2331        final int allAppsSize = allAps.size();
2332        synchronized (mPackages) {
2333            for (int i = 0; i < allAppsSize; i++) {
2334                String pName = allAps.get(i);
2335                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2336                // Should not happen, but we shouldn't be failing if it does
2337                if (pkgSetting == null) {
2338                    continue;
2339                }
2340                boolean install = enableApps.contains(pName);
2341                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2342                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2343                            + " for system user");
2344                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2345                }
2346            }
2347            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2348        }
2349    }
2350
2351    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2352        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2353                Context.DISPLAY_SERVICE);
2354        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2355    }
2356
2357    /**
2358     * Requests that files preopted on a secondary system partition be copied to the data partition
2359     * if possible.  Note that the actual copying of the files is accomplished by init for security
2360     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2361     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2362     */
2363    private static void requestCopyPreoptedFiles() {
2364        final int WAIT_TIME_MS = 100;
2365        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2366        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2367            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2368            // We will wait for up to 100 seconds.
2369            final long timeStart = SystemClock.uptimeMillis();
2370            final long timeEnd = timeStart + 100 * 1000;
2371            long timeNow = timeStart;
2372            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2373                try {
2374                    Thread.sleep(WAIT_TIME_MS);
2375                } catch (InterruptedException e) {
2376                    // Do nothing
2377                }
2378                timeNow = SystemClock.uptimeMillis();
2379                if (timeNow > timeEnd) {
2380                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2381                    Slog.wtf(TAG, "cppreopt did not finish!");
2382                    break;
2383                }
2384            }
2385
2386            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2387        }
2388    }
2389
2390    public PackageManagerService(Context context, Installer installer,
2391            boolean factoryTest, boolean onlyCore) {
2392        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2393        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2394        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2395                SystemClock.uptimeMillis());
2396
2397        if (mSdkVersion <= 0) {
2398            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2399        }
2400
2401        mContext = context;
2402
2403        mPermissionReviewRequired = context.getResources().getBoolean(
2404                R.bool.config_permissionReviewRequired);
2405
2406        mFactoryTest = factoryTest;
2407        mOnlyCore = onlyCore;
2408        mMetrics = new DisplayMetrics();
2409        mSettings = new Settings(mPackages);
2410        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2415                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2416        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2417                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2418        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2419                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2420        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2421                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2422
2423        String separateProcesses = SystemProperties.get("debug.separate_processes");
2424        if (separateProcesses != null && separateProcesses.length() > 0) {
2425            if ("*".equals(separateProcesses)) {
2426                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2427                mSeparateProcesses = null;
2428                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2429            } else {
2430                mDefParseFlags = 0;
2431                mSeparateProcesses = separateProcesses.split(",");
2432                Slog.w(TAG, "Running with debug.separate_processes: "
2433                        + separateProcesses);
2434            }
2435        } else {
2436            mDefParseFlags = 0;
2437            mSeparateProcesses = null;
2438        }
2439
2440        mInstaller = installer;
2441        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2442                "*dexopt*");
2443        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2444        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2445
2446        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2447                FgThread.get().getLooper());
2448
2449        getDefaultDisplayMetrics(context, mMetrics);
2450
2451        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2452        SystemConfig systemConfig = SystemConfig.getInstance();
2453        mGlobalGids = systemConfig.getGlobalGids();
2454        mSystemPermissions = systemConfig.getSystemPermissions();
2455        mAvailableFeatures = systemConfig.getAvailableFeatures();
2456        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2457
2458        mProtectedPackages = new ProtectedPackages(mContext);
2459
2460        synchronized (mInstallLock) {
2461        // writer
2462        synchronized (mPackages) {
2463            mHandlerThread = new ServiceThread(TAG,
2464                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2465            mHandlerThread.start();
2466            mHandler = new PackageHandler(mHandlerThread.getLooper());
2467            mProcessLoggingHandler = new ProcessLoggingHandler();
2468            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2469
2470            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2471            mInstantAppRegistry = new InstantAppRegistry(this);
2472
2473            File dataDir = Environment.getDataDirectory();
2474            mAppInstallDir = new File(dataDir, "app");
2475            mAppLib32InstallDir = new File(dataDir, "app-lib");
2476            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2477            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2478            sUserManager = new UserManagerService(context, this,
2479                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2480
2481            // Propagate permission configuration in to package manager.
2482            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2483                    = systemConfig.getPermissions();
2484            for (int i=0; i<permConfig.size(); i++) {
2485                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2486                BasePermission bp = mSettings.mPermissions.get(perm.name);
2487                if (bp == null) {
2488                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2489                    mSettings.mPermissions.put(perm.name, bp);
2490                }
2491                if (perm.gids != null) {
2492                    bp.setGids(perm.gids, perm.perUser);
2493                }
2494            }
2495
2496            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2497            final int builtInLibCount = libConfig.size();
2498            for (int i = 0; i < builtInLibCount; i++) {
2499                String name = libConfig.keyAt(i);
2500                String path = libConfig.valueAt(i);
2501                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2502                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2503            }
2504
2505            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2506
2507            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2508            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2509            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2510
2511            // Clean up orphaned packages for which the code path doesn't exist
2512            // and they are an update to a system app - caused by bug/32321269
2513            final int packageSettingCount = mSettings.mPackages.size();
2514            for (int i = packageSettingCount - 1; i >= 0; i--) {
2515                PackageSetting ps = mSettings.mPackages.valueAt(i);
2516                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2517                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2518                    mSettings.mPackages.removeAt(i);
2519                    mSettings.enableSystemPackageLPw(ps.name);
2520                }
2521            }
2522
2523            if (mFirstBoot) {
2524                requestCopyPreoptedFiles();
2525            }
2526
2527            String customResolverActivity = Resources.getSystem().getString(
2528                    R.string.config_customResolverActivity);
2529            if (TextUtils.isEmpty(customResolverActivity)) {
2530                customResolverActivity = null;
2531            } else {
2532                mCustomResolverComponentName = ComponentName.unflattenFromString(
2533                        customResolverActivity);
2534            }
2535
2536            long startTime = SystemClock.uptimeMillis();
2537
2538            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2539                    startTime);
2540
2541            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2542            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2543
2544            if (bootClassPath == null) {
2545                Slog.w(TAG, "No BOOTCLASSPATH found!");
2546            }
2547
2548            if (systemServerClassPath == null) {
2549                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2550            }
2551
2552            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2553
2554            final VersionInfo ver = mSettings.getInternalVersion();
2555            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2556            if (mIsUpgrade) {
2557                logCriticalInfo(Log.INFO,
2558                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2559            }
2560
2561            // when upgrading from pre-M, promote system app permissions from install to runtime
2562            mPromoteSystemApps =
2563                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2564
2565            // When upgrading from pre-N, we need to handle package extraction like first boot,
2566            // as there is no profiling data available.
2567            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2568
2569            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2570
2571            // save off the names of pre-existing system packages prior to scanning; we don't
2572            // want to automatically grant runtime permissions for new system apps
2573            if (mPromoteSystemApps) {
2574                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2575                while (pkgSettingIter.hasNext()) {
2576                    PackageSetting ps = pkgSettingIter.next();
2577                    if (isSystemApp(ps)) {
2578                        mExistingSystemPackages.add(ps.name);
2579                    }
2580                }
2581            }
2582
2583            mCacheDir = preparePackageParserCache(mIsUpgrade);
2584
2585            // Set flag to monitor and not change apk file paths when
2586            // scanning install directories.
2587            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2588
2589            if (mIsUpgrade || mFirstBoot) {
2590                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2591            }
2592
2593            // Collect vendor overlay packages. (Do this before scanning any apps.)
2594            // For security and version matching reason, only consider
2595            // overlay packages if they reside in the right directory.
2596            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR
2599                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2600
2601            mParallelPackageParserCallback.findStaticOverlayPackages();
2602
2603            // Find base frameworks (resource packages without code).
2604            scanDirTracedLI(frameworkDir, mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR
2607                    | PackageParser.PARSE_IS_PRIVILEGED,
2608                    scanFlags | SCAN_NO_DEX, 0);
2609
2610            // Collected privileged system packages.
2611            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2612            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2613                    | PackageParser.PARSE_IS_SYSTEM
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR
2615                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2616
2617            // Collect ordinary system packages.
2618            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2619            scanDirTracedLI(systemAppDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2622
2623            // Collect all vendor packages.
2624            File vendorAppDir = new File("/vendor/app");
2625            try {
2626                vendorAppDir = vendorAppDir.getCanonicalFile();
2627            } catch (IOException e) {
2628                // failed to look up canonical path, continue with original one
2629            }
2630            scanDirTracedLI(vendorAppDir, mDefParseFlags
2631                    | PackageParser.PARSE_IS_SYSTEM
2632                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2633
2634            // Collect all OEM packages.
2635            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2636            scanDirTracedLI(oemAppDir, mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM
2638                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2639
2640            // Prune any system packages that no longer exist.
2641            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2642            // Stub packages must either be replaced with full versions in the /data
2643            // partition or be disabled.
2644            final List<String> stubSystemApps = new ArrayList<>();
2645            if (!mOnlyCore) {
2646                // do this first before mucking with mPackages for the "expecting better" case
2647                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2648                while (pkgIterator.hasNext()) {
2649                    final PackageParser.Package pkg = pkgIterator.next();
2650                    if (pkg.isStub) {
2651                        stubSystemApps.add(pkg.packageName);
2652                    }
2653                }
2654
2655                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2656                while (psit.hasNext()) {
2657                    PackageSetting ps = psit.next();
2658
2659                    /*
2660                     * If this is not a system app, it can't be a
2661                     * disable system app.
2662                     */
2663                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2664                        continue;
2665                    }
2666
2667                    /*
2668                     * If the package is scanned, it's not erased.
2669                     */
2670                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2671                    if (scannedPkg != null) {
2672                        /*
2673                         * If the system app is both scanned and in the
2674                         * disabled packages list, then it must have been
2675                         * added via OTA. Remove it from the currently
2676                         * scanned package so the previously user-installed
2677                         * application can be scanned.
2678                         */
2679                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2680                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2681                                    + ps.name + "; removing system app.  Last known codePath="
2682                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2683                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2684                                    + scannedPkg.mVersionCode);
2685                            removePackageLI(scannedPkg, true);
2686                            mExpectingBetter.put(ps.name, ps.codePath);
2687                        }
2688
2689                        continue;
2690                    }
2691
2692                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2693                        psit.remove();
2694                        logCriticalInfo(Log.WARN, "System package " + ps.name
2695                                + " no longer exists; it's data will be wiped");
2696                        // Actual deletion of code and data will be handled by later
2697                        // reconciliation step
2698                    } else {
2699                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2700                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2701                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2702                        }
2703                    }
2704                }
2705            }
2706
2707            //look for any incomplete package installations
2708            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2709            for (int i = 0; i < deletePkgsList.size(); i++) {
2710                // Actual deletion of code and data will be handled by later
2711                // reconciliation step
2712                final String packageName = deletePkgsList.get(i).name;
2713                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2714                synchronized (mPackages) {
2715                    mSettings.removePackageLPw(packageName);
2716                }
2717            }
2718
2719            //delete tmp files
2720            deleteTempPackageFiles();
2721
2722            // Remove any shared userIDs that have no associated packages
2723            mSettings.pruneSharedUsersLPw();
2724            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2725            final int systemPackagesCount = mPackages.size();
2726            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2727                    + " ms, packageCount: " + systemPackagesCount
2728                    + " ms, timePerPackage: "
2729                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
2730            if (mIsUpgrade && systemPackagesCount > 0) {
2731                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2732                        ((int) systemScanTime) / systemPackagesCount);
2733            }
2734            if (!mOnlyCore) {
2735                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2736                        SystemClock.uptimeMillis());
2737                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2738
2739                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2740                        | PackageParser.PARSE_FORWARD_LOCK,
2741                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2742
2743                // Remove disable package settings for updated system apps that were
2744                // removed via an OTA. If the update is no longer present, remove the
2745                // app completely. Otherwise, revoke their system privileges.
2746                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2747                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2748                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2749
2750                    final String msg;
2751                    if (deletedPkg == null) {
2752                        // should have found an update, but, we didn't; remove everything
2753                        msg = "Updated system package " + deletedAppName
2754                                + " no longer exists; removing its data";
2755                        // Actual deletion of code and data will be handled by later
2756                        // reconciliation step
2757                    } else {
2758                        // found an update; revoke system privileges
2759                        msg = "Updated system package + " + deletedAppName
2760                                + " no longer exists; revoking system privileges";
2761
2762                        // Don't do anything if a stub is removed from the system image. If
2763                        // we were to remove the uncompressed version from the /data partition,
2764                        // this is where it'd be done.
2765
2766                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2767                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2768                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2769                    }
2770                    logCriticalInfo(Log.WARN, msg);
2771                }
2772
2773                /*
2774                 * Make sure all system apps that we expected to appear on
2775                 * the userdata partition actually showed up. If they never
2776                 * appeared, crawl back and revive the system version.
2777                 */
2778                for (int i = 0; i < mExpectingBetter.size(); i++) {
2779                    final String packageName = mExpectingBetter.keyAt(i);
2780                    if (!mPackages.containsKey(packageName)) {
2781                        final File scanFile = mExpectingBetter.valueAt(i);
2782
2783                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2784                                + " but never showed up; reverting to system");
2785
2786                        int reparseFlags = mDefParseFlags;
2787                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2788                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2789                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2790                                    | PackageParser.PARSE_IS_PRIVILEGED;
2791                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2792                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2793                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2794                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2795                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2796                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2797                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2798                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2799                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2800                        } else {
2801                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2802                            continue;
2803                        }
2804
2805                        mSettings.enableSystemPackageLPw(packageName);
2806
2807                        try {
2808                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2809                        } catch (PackageManagerException e) {
2810                            Slog.e(TAG, "Failed to parse original system package: "
2811                                    + e.getMessage());
2812                        }
2813                    }
2814                }
2815
2816                // Uncompress and install any stubbed system applications.
2817                // This must be done last to ensure all stubs are replaced or disabled.
2818                decompressSystemApplications(stubSystemApps, scanFlags);
2819
2820                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2821                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2822                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2823                        + " ms, packageCount: " + dataPackagesCount
2824                        + " ms, timePerPackage: "
2825                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2826                if (mIsUpgrade && dataPackagesCount > 0) {
2827                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2828                            ((int) dataScanTime) / dataPackagesCount);
2829                }
2830            }
2831            mExpectingBetter.clear();
2832
2833            // Resolve the storage manager.
2834            mStorageManagerPackage = getStorageManagerPackageName();
2835
2836            // Resolve protected action filters. Only the setup wizard is allowed to
2837            // have a high priority filter for these actions.
2838            mSetupWizardPackage = getSetupWizardPackageName();
2839            if (mProtectedFilters.size() > 0) {
2840                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2841                    Slog.i(TAG, "No setup wizard;"
2842                        + " All protected intents capped to priority 0");
2843                }
2844                for (ActivityIntentInfo filter : mProtectedFilters) {
2845                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2846                        if (DEBUG_FILTERS) {
2847                            Slog.i(TAG, "Found setup wizard;"
2848                                + " allow priority " + filter.getPriority() + ";"
2849                                + " package: " + filter.activity.info.packageName
2850                                + " activity: " + filter.activity.className
2851                                + " priority: " + filter.getPriority());
2852                        }
2853                        // skip setup wizard; allow it to keep the high priority filter
2854                        continue;
2855                    }
2856                    if (DEBUG_FILTERS) {
2857                        Slog.i(TAG, "Protected action; cap priority to 0;"
2858                                + " package: " + filter.activity.info.packageName
2859                                + " activity: " + filter.activity.className
2860                                + " origPrio: " + filter.getPriority());
2861                    }
2862                    filter.setPriority(0);
2863                }
2864            }
2865            mDeferProtectedFilters = false;
2866            mProtectedFilters.clear();
2867
2868            // Now that we know all of the shared libraries, update all clients to have
2869            // the correct library paths.
2870            updateAllSharedLibrariesLPw(null);
2871
2872            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2873                // NOTE: We ignore potential failures here during a system scan (like
2874                // the rest of the commands above) because there's precious little we
2875                // can do about it. A settings error is reported, though.
2876                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2877            }
2878
2879            // Now that we know all the packages we are keeping,
2880            // read and update their last usage times.
2881            mPackageUsage.read(mPackages);
2882            mCompilerStats.read();
2883
2884            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2885                    SystemClock.uptimeMillis());
2886            Slog.i(TAG, "Time to scan packages: "
2887                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2888                    + " seconds");
2889
2890            // If the platform SDK has changed since the last time we booted,
2891            // we need to re-grant app permission to catch any new ones that
2892            // appear.  This is really a hack, and means that apps can in some
2893            // cases get permissions that the user didn't initially explicitly
2894            // allow...  it would be nice to have some better way to handle
2895            // this situation.
2896            int updateFlags = UPDATE_PERMISSIONS_ALL;
2897            if (ver.sdkVersion != mSdkVersion) {
2898                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2899                        + mSdkVersion + "; regranting permissions for internal storage");
2900                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2901            }
2902            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2903            ver.sdkVersion = mSdkVersion;
2904
2905            // If this is the first boot or an update from pre-M, and it is a normal
2906            // boot, then we need to initialize the default preferred apps across
2907            // all defined users.
2908            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2909                for (UserInfo user : sUserManager.getUsers(true)) {
2910                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2911                    applyFactoryDefaultBrowserLPw(user.id);
2912                    primeDomainVerificationsLPw(user.id);
2913                }
2914            }
2915
2916            // Prepare storage for system user really early during boot,
2917            // since core system apps like SettingsProvider and SystemUI
2918            // can't wait for user to start
2919            final int storageFlags;
2920            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2921                storageFlags = StorageManager.FLAG_STORAGE_DE;
2922            } else {
2923                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2924            }
2925            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2926                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2927                    true /* onlyCoreApps */);
2928            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2929                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2930                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2931                traceLog.traceBegin("AppDataFixup");
2932                try {
2933                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2934                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2935                } catch (InstallerException e) {
2936                    Slog.w(TAG, "Trouble fixing GIDs", e);
2937                }
2938                traceLog.traceEnd();
2939
2940                traceLog.traceBegin("AppDataPrepare");
2941                if (deferPackages == null || deferPackages.isEmpty()) {
2942                    return;
2943                }
2944                int count = 0;
2945                for (String pkgName : deferPackages) {
2946                    PackageParser.Package pkg = null;
2947                    synchronized (mPackages) {
2948                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2949                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2950                            pkg = ps.pkg;
2951                        }
2952                    }
2953                    if (pkg != null) {
2954                        synchronized (mInstallLock) {
2955                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2956                                    true /* maybeMigrateAppData */);
2957                        }
2958                        count++;
2959                    }
2960                }
2961                traceLog.traceEnd();
2962                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2963            }, "prepareAppData");
2964
2965            // If this is first boot after an OTA, and a normal boot, then
2966            // we need to clear code cache directories.
2967            // Note that we do *not* clear the application profiles. These remain valid
2968            // across OTAs and are used to drive profile verification (post OTA) and
2969            // profile compilation (without waiting to collect a fresh set of profiles).
2970            if (mIsUpgrade && !onlyCore) {
2971                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2972                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2973                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2974                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2975                        // No apps are running this early, so no need to freeze
2976                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2977                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2978                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2979                    }
2980                }
2981                ver.fingerprint = Build.FINGERPRINT;
2982            }
2983
2984            checkDefaultBrowser();
2985
2986            // clear only after permissions and other defaults have been updated
2987            mExistingSystemPackages.clear();
2988            mPromoteSystemApps = false;
2989
2990            // All the changes are done during package scanning.
2991            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2992
2993            // can downgrade to reader
2994            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2995            mSettings.writeLPr();
2996            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2997            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2998                    SystemClock.uptimeMillis());
2999
3000            if (!mOnlyCore) {
3001                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3002                mRequiredInstallerPackage = getRequiredInstallerLPr();
3003                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3004                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3005                if (mIntentFilterVerifierComponent != null) {
3006                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3007                            mIntentFilterVerifierComponent);
3008                } else {
3009                    mIntentFilterVerifier = null;
3010                }
3011                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3012                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3013                        SharedLibraryInfo.VERSION_UNDEFINED);
3014                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3015                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3016                        SharedLibraryInfo.VERSION_UNDEFINED);
3017            } else {
3018                mRequiredVerifierPackage = null;
3019                mRequiredInstallerPackage = null;
3020                mRequiredUninstallerPackage = null;
3021                mIntentFilterVerifierComponent = null;
3022                mIntentFilterVerifier = null;
3023                mServicesSystemSharedLibraryPackageName = null;
3024                mSharedSystemSharedLibraryPackageName = null;
3025            }
3026
3027            mInstallerService = new PackageInstallerService(context, this);
3028            final Pair<ComponentName, String> instantAppResolverComponent =
3029                    getInstantAppResolverLPr();
3030            if (instantAppResolverComponent != null) {
3031                if (DEBUG_EPHEMERAL) {
3032                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3033                }
3034                mInstantAppResolverConnection = new EphemeralResolverConnection(
3035                        mContext, instantAppResolverComponent.first,
3036                        instantAppResolverComponent.second);
3037                mInstantAppResolverSettingsComponent =
3038                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3039            } else {
3040                mInstantAppResolverConnection = null;
3041                mInstantAppResolverSettingsComponent = null;
3042            }
3043            updateInstantAppInstallerLocked(null);
3044
3045            // Read and update the usage of dex files.
3046            // Do this at the end of PM init so that all the packages have their
3047            // data directory reconciled.
3048            // At this point we know the code paths of the packages, so we can validate
3049            // the disk file and build the internal cache.
3050            // The usage file is expected to be small so loading and verifying it
3051            // should take a fairly small time compare to the other activities (e.g. package
3052            // scanning).
3053            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3054            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3055            for (int userId : currentUserIds) {
3056                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3057            }
3058            mDexManager.load(userPackages);
3059            if (mIsUpgrade) {
3060                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3061                        (int) (SystemClock.uptimeMillis() - startTime));
3062            }
3063        } // synchronized (mPackages)
3064        } // synchronized (mInstallLock)
3065
3066        // Now after opening every single application zip, make sure they
3067        // are all flushed.  Not really needed, but keeps things nice and
3068        // tidy.
3069        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3070        Runtime.getRuntime().gc();
3071        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3072
3073        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3074        FallbackCategoryProvider.loadFallbacks();
3075        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3076
3077        // The initial scanning above does many calls into installd while
3078        // holding the mPackages lock, but we're mostly interested in yelling
3079        // once we have a booted system.
3080        mInstaller.setWarnIfHeld(mPackages);
3081
3082        // Expose private service for system components to use.
3083        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3084        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3085    }
3086
3087    /**
3088     * Uncompress and install stub applications.
3089     * <p>In order to save space on the system partition, some applications are shipped in a
3090     * compressed form. In addition the compressed bits for the full application, the
3091     * system image contains a tiny stub comprised of only the Android manifest.
3092     * <p>During the first boot, attempt to uncompress and install the full application. If
3093     * the application can't be installed for any reason, disable the stub and prevent
3094     * uncompressing the full application during future boots.
3095     * <p>In order to forcefully attempt an installation of a full application, go to app
3096     * settings and enable the application.
3097     */
3098    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3099        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3100            final String pkgName = stubSystemApps.get(i);
3101            // skip if the system package is already disabled
3102            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3103                stubSystemApps.remove(i);
3104                continue;
3105            }
3106            // skip if the package isn't installed (?!); this should never happen
3107            final PackageParser.Package pkg = mPackages.get(pkgName);
3108            if (pkg == null) {
3109                stubSystemApps.remove(i);
3110                continue;
3111            }
3112            // skip if the package has been disabled by the user
3113            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3114            if (ps != null) {
3115                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3116                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3117                    stubSystemApps.remove(i);
3118                    continue;
3119                }
3120            }
3121
3122            if (DEBUG_COMPRESSION) {
3123                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3124            }
3125
3126            // uncompress the binary to its eventual destination on /data
3127            final File scanFile = decompressPackage(pkg);
3128            if (scanFile == null) {
3129                continue;
3130            }
3131
3132            // install the package to replace the stub on /system
3133            try {
3134                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3135                removePackageLI(pkg, true /*chatty*/);
3136                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3137                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3138                        UserHandle.USER_SYSTEM, "android");
3139                stubSystemApps.remove(i);
3140                continue;
3141            } catch (PackageManagerException e) {
3142                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3143            }
3144
3145            // any failed attempt to install the package will be cleaned up later
3146        }
3147
3148        // disable any stub still left; these failed to install the full application
3149        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3150            final String pkgName = stubSystemApps.get(i);
3151            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3152            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3153                    UserHandle.USER_SYSTEM, "android");
3154            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3155        }
3156    }
3157
3158    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3159        if (DEBUG_COMPRESSION) {
3160            Slog.i(TAG, "Decompress file"
3161                    + "; src: " + srcFile.getAbsolutePath()
3162                    + ", dst: " + dstFile.getAbsolutePath());
3163        }
3164        try (
3165                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3166                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3167        ) {
3168            Streams.copy(fileIn, fileOut);
3169            Os.chmod(dstFile.getAbsolutePath(), 0644);
3170            return PackageManager.INSTALL_SUCCEEDED;
3171        } catch (IOException e) {
3172            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3173                    + "; src: " + srcFile.getAbsolutePath()
3174                    + ", dst: " + dstFile.getAbsolutePath());
3175        }
3176        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3177    }
3178
3179    private File[] getCompressedFiles(String codePath) {
3180        return new File(codePath).listFiles(new FilenameFilter() {
3181            @Override
3182            public boolean accept(File dir, String name) {
3183                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3184            }
3185        });
3186    }
3187
3188    private boolean compressedFileExists(String codePath) {
3189        final File[] compressedFiles = getCompressedFiles(codePath);
3190        return compressedFiles != null && compressedFiles.length > 0;
3191    }
3192
3193    /**
3194     * Decompresses the given package on the system image onto
3195     * the /data partition.
3196     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3197     */
3198    private File decompressPackage(PackageParser.Package pkg) {
3199        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3200        if (compressedFiles == null || compressedFiles.length == 0) {
3201            if (DEBUG_COMPRESSION) {
3202                Slog.i(TAG, "No files to decompress");
3203            }
3204            return null;
3205        }
3206        final File dstCodePath =
3207                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3208        int ret = PackageManager.INSTALL_SUCCEEDED;
3209        try {
3210            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3211            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3212            for (File srcFile : compressedFiles) {
3213                final String srcFileName = srcFile.getName();
3214                final String dstFileName = srcFileName.substring(
3215                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3216                final File dstFile = new File(dstCodePath, dstFileName);
3217                ret = decompressFile(srcFile, dstFile);
3218                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3219                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3220                            + "; pkg: " + pkg.packageName
3221                            + ", file: " + dstFileName);
3222                    break;
3223                }
3224            }
3225        } catch (ErrnoException e) {
3226            logCriticalInfo(Log.ERROR, "Failed to decompress"
3227                    + "; pkg: " + pkg.packageName
3228                    + ", err: " + e.errno);
3229        }
3230        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3231            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3232            NativeLibraryHelper.Handle handle = null;
3233            try {
3234                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3235                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3236                        null /*abiOverride*/);
3237            } catch (IOException e) {
3238                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3239                        + "; pkg: " + pkg.packageName);
3240                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3241            } finally {
3242                IoUtils.closeQuietly(handle);
3243            }
3244        }
3245        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3246            if (dstCodePath == null || !dstCodePath.exists()) {
3247                return null;
3248            }
3249            removeCodePathLI(dstCodePath);
3250            return null;
3251        }
3252        return dstCodePath;
3253    }
3254
3255    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3256        // we're only interested in updating the installer appliction when 1) it's not
3257        // already set or 2) the modified package is the installer
3258        if (mInstantAppInstallerActivity != null
3259                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3260                        .equals(modifiedPackage)) {
3261            return;
3262        }
3263        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3264    }
3265
3266    private static File preparePackageParserCache(boolean isUpgrade) {
3267        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3268            return null;
3269        }
3270
3271        // Disable package parsing on eng builds to allow for faster incremental development.
3272        if (Build.IS_ENG) {
3273            return null;
3274        }
3275
3276        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3277            Slog.i(TAG, "Disabling package parser cache due to system property.");
3278            return null;
3279        }
3280
3281        // The base directory for the package parser cache lives under /data/system/.
3282        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3283                "package_cache");
3284        if (cacheBaseDir == null) {
3285            return null;
3286        }
3287
3288        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3289        // This also serves to "GC" unused entries when the package cache version changes (which
3290        // can only happen during upgrades).
3291        if (isUpgrade) {
3292            FileUtils.deleteContents(cacheBaseDir);
3293        }
3294
3295
3296        // Return the versioned package cache directory. This is something like
3297        // "/data/system/package_cache/1"
3298        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3299
3300        // The following is a workaround to aid development on non-numbered userdebug
3301        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3302        // the system partition is newer.
3303        //
3304        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3305        // that starts with "eng." to signify that this is an engineering build and not
3306        // destined for release.
3307        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3308            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3309
3310            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3311            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3312            // in general and should not be used for production changes. In this specific case,
3313            // we know that they will work.
3314            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3315            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3316                FileUtils.deleteContents(cacheBaseDir);
3317                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3318            }
3319        }
3320
3321        return cacheDir;
3322    }
3323
3324    @Override
3325    public boolean isFirstBoot() {
3326        // allow instant applications
3327        return mFirstBoot;
3328    }
3329
3330    @Override
3331    public boolean isOnlyCoreApps() {
3332        // allow instant applications
3333        return mOnlyCore;
3334    }
3335
3336    @Override
3337    public boolean isUpgrade() {
3338        // allow instant applications
3339        return mIsUpgrade;
3340    }
3341
3342    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3343        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3344
3345        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3346                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3347                UserHandle.USER_SYSTEM);
3348        if (matches.size() == 1) {
3349            return matches.get(0).getComponentInfo().packageName;
3350        } else if (matches.size() == 0) {
3351            Log.e(TAG, "There should probably be a verifier, but, none were found");
3352            return null;
3353        }
3354        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3355    }
3356
3357    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3358        synchronized (mPackages) {
3359            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3360            if (libraryEntry == null) {
3361                throw new IllegalStateException("Missing required shared library:" + name);
3362            }
3363            return libraryEntry.apk;
3364        }
3365    }
3366
3367    private @NonNull String getRequiredInstallerLPr() {
3368        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3369        intent.addCategory(Intent.CATEGORY_DEFAULT);
3370        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3371
3372        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3373                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3374                UserHandle.USER_SYSTEM);
3375        if (matches.size() == 1) {
3376            ResolveInfo resolveInfo = matches.get(0);
3377            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3378                throw new RuntimeException("The installer must be a privileged app");
3379            }
3380            return matches.get(0).getComponentInfo().packageName;
3381        } else {
3382            throw new RuntimeException("There must be exactly one installer; found " + matches);
3383        }
3384    }
3385
3386    private @NonNull String getRequiredUninstallerLPr() {
3387        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3388        intent.addCategory(Intent.CATEGORY_DEFAULT);
3389        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3390
3391        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3392                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3393                UserHandle.USER_SYSTEM);
3394        if (resolveInfo == null ||
3395                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3396            throw new RuntimeException("There must be exactly one uninstaller; found "
3397                    + resolveInfo);
3398        }
3399        return resolveInfo.getComponentInfo().packageName;
3400    }
3401
3402    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3403        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3404
3405        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3406                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3407                UserHandle.USER_SYSTEM);
3408        ResolveInfo best = null;
3409        final int N = matches.size();
3410        for (int i = 0; i < N; i++) {
3411            final ResolveInfo cur = matches.get(i);
3412            final String packageName = cur.getComponentInfo().packageName;
3413            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3414                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3415                continue;
3416            }
3417
3418            if (best == null || cur.priority > best.priority) {
3419                best = cur;
3420            }
3421        }
3422
3423        if (best != null) {
3424            return best.getComponentInfo().getComponentName();
3425        }
3426        Slog.w(TAG, "Intent filter verifier not found");
3427        return null;
3428    }
3429
3430    @Override
3431    public @Nullable ComponentName getInstantAppResolverComponent() {
3432        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3433            return null;
3434        }
3435        synchronized (mPackages) {
3436            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3437            if (instantAppResolver == null) {
3438                return null;
3439            }
3440            return instantAppResolver.first;
3441        }
3442    }
3443
3444    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3445        final String[] packageArray =
3446                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3447        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3448            if (DEBUG_EPHEMERAL) {
3449                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3450            }
3451            return null;
3452        }
3453
3454        final int callingUid = Binder.getCallingUid();
3455        final int resolveFlags =
3456                MATCH_DIRECT_BOOT_AWARE
3457                | MATCH_DIRECT_BOOT_UNAWARE
3458                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3459        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3460        final Intent resolverIntent = new Intent(actionName);
3461        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3462                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3463        // temporarily look for the old action
3464        if (resolvers.size() == 0) {
3465            if (DEBUG_EPHEMERAL) {
3466                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3467            }
3468            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3469            resolverIntent.setAction(actionName);
3470            resolvers = queryIntentServicesInternal(resolverIntent, null,
3471                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3472        }
3473        final int N = resolvers.size();
3474        if (N == 0) {
3475            if (DEBUG_EPHEMERAL) {
3476                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3477            }
3478            return null;
3479        }
3480
3481        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3482        for (int i = 0; i < N; i++) {
3483            final ResolveInfo info = resolvers.get(i);
3484
3485            if (info.serviceInfo == null) {
3486                continue;
3487            }
3488
3489            final String packageName = info.serviceInfo.packageName;
3490            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3491                if (DEBUG_EPHEMERAL) {
3492                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3493                            + " pkg: " + packageName + ", info:" + info);
3494                }
3495                continue;
3496            }
3497
3498            if (DEBUG_EPHEMERAL) {
3499                Slog.v(TAG, "Ephemeral resolver found;"
3500                        + " pkg: " + packageName + ", info:" + info);
3501            }
3502            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3503        }
3504        if (DEBUG_EPHEMERAL) {
3505            Slog.v(TAG, "Ephemeral resolver NOT found");
3506        }
3507        return null;
3508    }
3509
3510    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3511        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3512        intent.addCategory(Intent.CATEGORY_DEFAULT);
3513        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3514
3515        final int resolveFlags =
3516                MATCH_DIRECT_BOOT_AWARE
3517                | MATCH_DIRECT_BOOT_UNAWARE
3518                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3519        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3520                resolveFlags, UserHandle.USER_SYSTEM);
3521        // temporarily look for the old action
3522        if (matches.isEmpty()) {
3523            if (DEBUG_EPHEMERAL) {
3524                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3525            }
3526            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3527            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3528                    resolveFlags, UserHandle.USER_SYSTEM);
3529        }
3530        Iterator<ResolveInfo> iter = matches.iterator();
3531        while (iter.hasNext()) {
3532            final ResolveInfo rInfo = iter.next();
3533            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3534            if (ps != null) {
3535                final PermissionsState permissionsState = ps.getPermissionsState();
3536                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3537                    continue;
3538                }
3539            }
3540            iter.remove();
3541        }
3542        if (matches.size() == 0) {
3543            return null;
3544        } else if (matches.size() == 1) {
3545            return (ActivityInfo) matches.get(0).getComponentInfo();
3546        } else {
3547            throw new RuntimeException(
3548                    "There must be at most one ephemeral installer; found " + matches);
3549        }
3550    }
3551
3552    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3553            @NonNull ComponentName resolver) {
3554        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3555                .addCategory(Intent.CATEGORY_DEFAULT)
3556                .setPackage(resolver.getPackageName());
3557        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3558        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3559                UserHandle.USER_SYSTEM);
3560        // temporarily look for the old action
3561        if (matches.isEmpty()) {
3562            if (DEBUG_EPHEMERAL) {
3563                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3564            }
3565            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3566            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3567                    UserHandle.USER_SYSTEM);
3568        }
3569        if (matches.isEmpty()) {
3570            return null;
3571        }
3572        return matches.get(0).getComponentInfo().getComponentName();
3573    }
3574
3575    private void primeDomainVerificationsLPw(int userId) {
3576        if (DEBUG_DOMAIN_VERIFICATION) {
3577            Slog.d(TAG, "Priming domain verifications in user " + userId);
3578        }
3579
3580        SystemConfig systemConfig = SystemConfig.getInstance();
3581        ArraySet<String> packages = systemConfig.getLinkedApps();
3582
3583        for (String packageName : packages) {
3584            PackageParser.Package pkg = mPackages.get(packageName);
3585            if (pkg != null) {
3586                if (!pkg.isSystemApp()) {
3587                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3588                    continue;
3589                }
3590
3591                ArraySet<String> domains = null;
3592                for (PackageParser.Activity a : pkg.activities) {
3593                    for (ActivityIntentInfo filter : a.intents) {
3594                        if (hasValidDomains(filter)) {
3595                            if (domains == null) {
3596                                domains = new ArraySet<String>();
3597                            }
3598                            domains.addAll(filter.getHostsList());
3599                        }
3600                    }
3601                }
3602
3603                if (domains != null && domains.size() > 0) {
3604                    if (DEBUG_DOMAIN_VERIFICATION) {
3605                        Slog.v(TAG, "      + " + packageName);
3606                    }
3607                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3608                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3609                    // and then 'always' in the per-user state actually used for intent resolution.
3610                    final IntentFilterVerificationInfo ivi;
3611                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3612                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3613                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3614                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3615                } else {
3616                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3617                            + "' does not handle web links");
3618                }
3619            } else {
3620                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3621            }
3622        }
3623
3624        scheduleWritePackageRestrictionsLocked(userId);
3625        scheduleWriteSettingsLocked();
3626    }
3627
3628    private void applyFactoryDefaultBrowserLPw(int userId) {
3629        // The default browser app's package name is stored in a string resource,
3630        // with a product-specific overlay used for vendor customization.
3631        String browserPkg = mContext.getResources().getString(
3632                com.android.internal.R.string.default_browser);
3633        if (!TextUtils.isEmpty(browserPkg)) {
3634            // non-empty string => required to be a known package
3635            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3636            if (ps == null) {
3637                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3638                browserPkg = null;
3639            } else {
3640                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3641            }
3642        }
3643
3644        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3645        // default.  If there's more than one, just leave everything alone.
3646        if (browserPkg == null) {
3647            calculateDefaultBrowserLPw(userId);
3648        }
3649    }
3650
3651    private void calculateDefaultBrowserLPw(int userId) {
3652        List<String> allBrowsers = resolveAllBrowserApps(userId);
3653        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3654        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3655    }
3656
3657    private List<String> resolveAllBrowserApps(int userId) {
3658        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3659        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3660                PackageManager.MATCH_ALL, userId);
3661
3662        final int count = list.size();
3663        List<String> result = new ArrayList<String>(count);
3664        for (int i=0; i<count; i++) {
3665            ResolveInfo info = list.get(i);
3666            if (info.activityInfo == null
3667                    || !info.handleAllWebDataURI
3668                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3669                    || result.contains(info.activityInfo.packageName)) {
3670                continue;
3671            }
3672            result.add(info.activityInfo.packageName);
3673        }
3674
3675        return result;
3676    }
3677
3678    private boolean packageIsBrowser(String packageName, int userId) {
3679        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3680                PackageManager.MATCH_ALL, userId);
3681        final int N = list.size();
3682        for (int i = 0; i < N; i++) {
3683            ResolveInfo info = list.get(i);
3684            if (packageName.equals(info.activityInfo.packageName)) {
3685                return true;
3686            }
3687        }
3688        return false;
3689    }
3690
3691    private void checkDefaultBrowser() {
3692        final int myUserId = UserHandle.myUserId();
3693        final String packageName = getDefaultBrowserPackageName(myUserId);
3694        if (packageName != null) {
3695            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3696            if (info == null) {
3697                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3698                synchronized (mPackages) {
3699                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3700                }
3701            }
3702        }
3703    }
3704
3705    @Override
3706    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3707            throws RemoteException {
3708        try {
3709            return super.onTransact(code, data, reply, flags);
3710        } catch (RuntimeException e) {
3711            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3712                Slog.wtf(TAG, "Package Manager Crash", e);
3713            }
3714            throw e;
3715        }
3716    }
3717
3718    static int[] appendInts(int[] cur, int[] add) {
3719        if (add == null) return cur;
3720        if (cur == null) return add;
3721        final int N = add.length;
3722        for (int i=0; i<N; i++) {
3723            cur = appendInt(cur, add[i]);
3724        }
3725        return cur;
3726    }
3727
3728    /**
3729     * Returns whether or not a full application can see an instant application.
3730     * <p>
3731     * Currently, there are three cases in which this can occur:
3732     * <ol>
3733     * <li>The calling application is a "special" process. The special
3734     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3735     *     and {@code 0}</li>
3736     * <li>The calling application has the permission
3737     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3738     * <li>The calling application is the default launcher on the
3739     *     system partition.</li>
3740     * </ol>
3741     */
3742    private boolean canViewInstantApps(int callingUid, int userId) {
3743        if (callingUid == Process.SYSTEM_UID
3744                || callingUid == Process.SHELL_UID
3745                || callingUid == Process.ROOT_UID) {
3746            return true;
3747        }
3748        if (mContext.checkCallingOrSelfPermission(
3749                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3750            return true;
3751        }
3752        if (mContext.checkCallingOrSelfPermission(
3753                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3754            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3755            if (homeComponent != null
3756                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3757                return true;
3758            }
3759        }
3760        return false;
3761    }
3762
3763    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3764        if (!sUserManager.exists(userId)) return null;
3765        if (ps == null) {
3766            return null;
3767        }
3768        PackageParser.Package p = ps.pkg;
3769        if (p == null) {
3770            return null;
3771        }
3772        final int callingUid = Binder.getCallingUid();
3773        // Filter out ephemeral app metadata:
3774        //   * The system/shell/root can see metadata for any app
3775        //   * An installed app can see metadata for 1) other installed apps
3776        //     and 2) ephemeral apps that have explicitly interacted with it
3777        //   * Ephemeral apps can only see their own data and exposed installed apps
3778        //   * Holding a signature permission allows seeing instant apps
3779        if (filterAppAccessLPr(ps, callingUid, userId)) {
3780            return null;
3781        }
3782
3783        final PermissionsState permissionsState = ps.getPermissionsState();
3784
3785        // Compute GIDs only if requested
3786        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3787                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3788        // Compute granted permissions only if package has requested permissions
3789        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3790                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3791        final PackageUserState state = ps.readUserState(userId);
3792
3793        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3794                && ps.isSystem()) {
3795            flags |= MATCH_ANY_USER;
3796        }
3797
3798        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3799                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3800
3801        if (packageInfo == null) {
3802            return null;
3803        }
3804
3805        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3806                resolveExternalPackageNameLPr(p);
3807
3808        return packageInfo;
3809    }
3810
3811    @Override
3812    public void checkPackageStartable(String packageName, int userId) {
3813        final int callingUid = Binder.getCallingUid();
3814        if (getInstantAppPackageName(callingUid) != null) {
3815            throw new SecurityException("Instant applications don't have access to this method");
3816        }
3817        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3818        synchronized (mPackages) {
3819            final PackageSetting ps = mSettings.mPackages.get(packageName);
3820            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3821                throw new SecurityException("Package " + packageName + " was not found!");
3822            }
3823
3824            if (!ps.getInstalled(userId)) {
3825                throw new SecurityException(
3826                        "Package " + packageName + " was not installed for user " + userId + "!");
3827            }
3828
3829            if (mSafeMode && !ps.isSystem()) {
3830                throw new SecurityException("Package " + packageName + " not a system app!");
3831            }
3832
3833            if (mFrozenPackages.contains(packageName)) {
3834                throw new SecurityException("Package " + packageName + " is currently frozen!");
3835            }
3836
3837            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3838                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3839                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3840            }
3841        }
3842    }
3843
3844    @Override
3845    public boolean isPackageAvailable(String packageName, int userId) {
3846        if (!sUserManager.exists(userId)) return false;
3847        final int callingUid = Binder.getCallingUid();
3848        enforceCrossUserPermission(callingUid, userId,
3849                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3850        synchronized (mPackages) {
3851            PackageParser.Package p = mPackages.get(packageName);
3852            if (p != null) {
3853                final PackageSetting ps = (PackageSetting) p.mExtras;
3854                if (filterAppAccessLPr(ps, callingUid, userId)) {
3855                    return false;
3856                }
3857                if (ps != null) {
3858                    final PackageUserState state = ps.readUserState(userId);
3859                    if (state != null) {
3860                        return PackageParser.isAvailable(state);
3861                    }
3862                }
3863            }
3864        }
3865        return false;
3866    }
3867
3868    @Override
3869    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3870        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3871                flags, Binder.getCallingUid(), userId);
3872    }
3873
3874    @Override
3875    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3876            int flags, int userId) {
3877        return getPackageInfoInternal(versionedPackage.getPackageName(),
3878                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3879    }
3880
3881    /**
3882     * Important: The provided filterCallingUid is used exclusively to filter out packages
3883     * that can be seen based on user state. It's typically the original caller uid prior
3884     * to clearing. Because it can only be provided by trusted code, it's value can be
3885     * trusted and will be used as-is; unlike userId which will be validated by this method.
3886     */
3887    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3888            int flags, int filterCallingUid, int userId) {
3889        if (!sUserManager.exists(userId)) return null;
3890        flags = updateFlagsForPackage(flags, userId, packageName);
3891        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3892                false /* requireFullPermission */, false /* checkShell */, "get package info");
3893
3894        // reader
3895        synchronized (mPackages) {
3896            // Normalize package name to handle renamed packages and static libs
3897            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3898
3899            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3900            if (matchFactoryOnly) {
3901                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3902                if (ps != null) {
3903                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3904                        return null;
3905                    }
3906                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3907                        return null;
3908                    }
3909                    return generatePackageInfo(ps, flags, userId);
3910                }
3911            }
3912
3913            PackageParser.Package p = mPackages.get(packageName);
3914            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3915                return null;
3916            }
3917            if (DEBUG_PACKAGE_INFO)
3918                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3919            if (p != null) {
3920                final PackageSetting ps = (PackageSetting) p.mExtras;
3921                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3922                    return null;
3923                }
3924                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3925                    return null;
3926                }
3927                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3928            }
3929            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3930                final PackageSetting ps = mSettings.mPackages.get(packageName);
3931                if (ps == null) return null;
3932                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3933                    return null;
3934                }
3935                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3936                    return null;
3937                }
3938                return generatePackageInfo(ps, flags, userId);
3939            }
3940        }
3941        return null;
3942    }
3943
3944    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3945        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3946            return true;
3947        }
3948        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3949            return true;
3950        }
3951        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3952            return true;
3953        }
3954        return false;
3955    }
3956
3957    private boolean isComponentVisibleToInstantApp(
3958            @Nullable ComponentName component, @ComponentType int type) {
3959        if (type == TYPE_ACTIVITY) {
3960            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3961            return activity != null
3962                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3963                    : false;
3964        } else if (type == TYPE_RECEIVER) {
3965            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3966            return activity != null
3967                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3968                    : false;
3969        } else if (type == TYPE_SERVICE) {
3970            final PackageParser.Service service = mServices.mServices.get(component);
3971            return service != null
3972                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3973                    : false;
3974        } else if (type == TYPE_PROVIDER) {
3975            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3976            return provider != null
3977                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3978                    : false;
3979        } else if (type == TYPE_UNKNOWN) {
3980            return isComponentVisibleToInstantApp(component);
3981        }
3982        return false;
3983    }
3984
3985    /**
3986     * Returns whether or not access to the application should be filtered.
3987     * <p>
3988     * Access may be limited based upon whether the calling or target applications
3989     * are instant applications.
3990     *
3991     * @see #canAccessInstantApps(int)
3992     */
3993    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3994            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3995        // if we're in an isolated process, get the real calling UID
3996        if (Process.isIsolated(callingUid)) {
3997            callingUid = mIsolatedOwners.get(callingUid);
3998        }
3999        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4000        final boolean callerIsInstantApp = instantAppPkgName != null;
4001        if (ps == null) {
4002            if (callerIsInstantApp) {
4003                // pretend the application exists, but, needs to be filtered
4004                return true;
4005            }
4006            return false;
4007        }
4008        // if the target and caller are the same application, don't filter
4009        if (isCallerSameApp(ps.name, callingUid)) {
4010            return false;
4011        }
4012        if (callerIsInstantApp) {
4013            // request for a specific component; if it hasn't been explicitly exposed, filter
4014            if (component != null) {
4015                return !isComponentVisibleToInstantApp(component, componentType);
4016            }
4017            // request for application; if no components have been explicitly exposed, filter
4018            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4019        }
4020        if (ps.getInstantApp(userId)) {
4021            // caller can see all components of all instant applications, don't filter
4022            if (canViewInstantApps(callingUid, userId)) {
4023                return false;
4024            }
4025            // request for a specific instant application component, filter
4026            if (component != null) {
4027                return true;
4028            }
4029            // request for an instant application; if the caller hasn't been granted access, filter
4030            return !mInstantAppRegistry.isInstantAccessGranted(
4031                    userId, UserHandle.getAppId(callingUid), ps.appId);
4032        }
4033        return false;
4034    }
4035
4036    /**
4037     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4038     */
4039    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4040        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4041    }
4042
4043    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4044            int flags) {
4045        // Callers can access only the libs they depend on, otherwise they need to explicitly
4046        // ask for the shared libraries given the caller is allowed to access all static libs.
4047        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4048            // System/shell/root get to see all static libs
4049            final int appId = UserHandle.getAppId(uid);
4050            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4051                    || appId == Process.ROOT_UID) {
4052                return false;
4053            }
4054        }
4055
4056        // No package means no static lib as it is always on internal storage
4057        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4058            return false;
4059        }
4060
4061        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4062                ps.pkg.staticSharedLibVersion);
4063        if (libEntry == null) {
4064            return false;
4065        }
4066
4067        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4068        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4069        if (uidPackageNames == null) {
4070            return true;
4071        }
4072
4073        for (String uidPackageName : uidPackageNames) {
4074            if (ps.name.equals(uidPackageName)) {
4075                return false;
4076            }
4077            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4078            if (uidPs != null) {
4079                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4080                        libEntry.info.getName());
4081                if (index < 0) {
4082                    continue;
4083                }
4084                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4085                    return false;
4086                }
4087            }
4088        }
4089        return true;
4090    }
4091
4092    @Override
4093    public String[] currentToCanonicalPackageNames(String[] names) {
4094        final int callingUid = Binder.getCallingUid();
4095        if (getInstantAppPackageName(callingUid) != null) {
4096            return names;
4097        }
4098        final String[] out = new String[names.length];
4099        // reader
4100        synchronized (mPackages) {
4101            final int callingUserId = UserHandle.getUserId(callingUid);
4102            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4103            for (int i=names.length-1; i>=0; i--) {
4104                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4105                boolean translateName = false;
4106                if (ps != null && ps.realName != null) {
4107                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4108                    translateName = !targetIsInstantApp
4109                            || canViewInstantApps
4110                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4111                                    UserHandle.getAppId(callingUid), ps.appId);
4112                }
4113                out[i] = translateName ? ps.realName : names[i];
4114            }
4115        }
4116        return out;
4117    }
4118
4119    @Override
4120    public String[] canonicalToCurrentPackageNames(String[] names) {
4121        final int callingUid = Binder.getCallingUid();
4122        if (getInstantAppPackageName(callingUid) != null) {
4123            return names;
4124        }
4125        final String[] out = new String[names.length];
4126        // reader
4127        synchronized (mPackages) {
4128            final int callingUserId = UserHandle.getUserId(callingUid);
4129            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4130            for (int i=names.length-1; i>=0; i--) {
4131                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4132                boolean translateName = false;
4133                if (cur != null) {
4134                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4135                    final boolean targetIsInstantApp =
4136                            ps != null && ps.getInstantApp(callingUserId);
4137                    translateName = !targetIsInstantApp
4138                            || canViewInstantApps
4139                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4140                                    UserHandle.getAppId(callingUid), ps.appId);
4141                }
4142                out[i] = translateName ? cur : names[i];
4143            }
4144        }
4145        return out;
4146    }
4147
4148    @Override
4149    public int getPackageUid(String packageName, int flags, int userId) {
4150        if (!sUserManager.exists(userId)) return -1;
4151        final int callingUid = Binder.getCallingUid();
4152        flags = updateFlagsForPackage(flags, userId, packageName);
4153        enforceCrossUserPermission(callingUid, userId,
4154                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4155
4156        // reader
4157        synchronized (mPackages) {
4158            final PackageParser.Package p = mPackages.get(packageName);
4159            if (p != null && p.isMatch(flags)) {
4160                PackageSetting ps = (PackageSetting) p.mExtras;
4161                if (filterAppAccessLPr(ps, callingUid, userId)) {
4162                    return -1;
4163                }
4164                return UserHandle.getUid(userId, p.applicationInfo.uid);
4165            }
4166            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4167                final PackageSetting ps = mSettings.mPackages.get(packageName);
4168                if (ps != null && ps.isMatch(flags)
4169                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4170                    return UserHandle.getUid(userId, ps.appId);
4171                }
4172            }
4173        }
4174
4175        return -1;
4176    }
4177
4178    @Override
4179    public int[] getPackageGids(String packageName, int flags, int userId) {
4180        if (!sUserManager.exists(userId)) return null;
4181        final int callingUid = Binder.getCallingUid();
4182        flags = updateFlagsForPackage(flags, userId, packageName);
4183        enforceCrossUserPermission(callingUid, userId,
4184                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4185
4186        // reader
4187        synchronized (mPackages) {
4188            final PackageParser.Package p = mPackages.get(packageName);
4189            if (p != null && p.isMatch(flags)) {
4190                PackageSetting ps = (PackageSetting) p.mExtras;
4191                if (filterAppAccessLPr(ps, callingUid, userId)) {
4192                    return null;
4193                }
4194                // TODO: Shouldn't this be checking for package installed state for userId and
4195                // return null?
4196                return ps.getPermissionsState().computeGids(userId);
4197            }
4198            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4199                final PackageSetting ps = mSettings.mPackages.get(packageName);
4200                if (ps != null && ps.isMatch(flags)
4201                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4202                    return ps.getPermissionsState().computeGids(userId);
4203                }
4204            }
4205        }
4206
4207        return null;
4208    }
4209
4210    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4211        if (bp.perm != null) {
4212            return PackageParser.generatePermissionInfo(bp.perm, flags);
4213        }
4214        PermissionInfo pi = new PermissionInfo();
4215        pi.name = bp.name;
4216        pi.packageName = bp.sourcePackage;
4217        pi.nonLocalizedLabel = bp.name;
4218        pi.protectionLevel = bp.protectionLevel;
4219        return pi;
4220    }
4221
4222    @Override
4223    public PermissionInfo getPermissionInfo(String name, int flags) {
4224        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4225            return null;
4226        }
4227        // reader
4228        synchronized (mPackages) {
4229            final BasePermission p = mSettings.mPermissions.get(name);
4230            if (p != null) {
4231                return generatePermissionInfo(p, flags);
4232            }
4233            return null;
4234        }
4235    }
4236
4237    @Override
4238    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4239            int flags) {
4240        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4241            return null;
4242        }
4243        // reader
4244        synchronized (mPackages) {
4245            if (group != null && !mPermissionGroups.containsKey(group)) {
4246                // This is thrown as NameNotFoundException
4247                return null;
4248            }
4249
4250            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4251            for (BasePermission p : mSettings.mPermissions.values()) {
4252                if (group == null) {
4253                    if (p.perm == null || p.perm.info.group == null) {
4254                        out.add(generatePermissionInfo(p, flags));
4255                    }
4256                } else {
4257                    if (p.perm != null && group.equals(p.perm.info.group)) {
4258                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4259                    }
4260                }
4261            }
4262            return new ParceledListSlice<>(out);
4263        }
4264    }
4265
4266    @Override
4267    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4268        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4269            return null;
4270        }
4271        // reader
4272        synchronized (mPackages) {
4273            return PackageParser.generatePermissionGroupInfo(
4274                    mPermissionGroups.get(name), flags);
4275        }
4276    }
4277
4278    @Override
4279    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4280        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4281            return ParceledListSlice.emptyList();
4282        }
4283        // reader
4284        synchronized (mPackages) {
4285            final int N = mPermissionGroups.size();
4286            ArrayList<PermissionGroupInfo> out
4287                    = new ArrayList<PermissionGroupInfo>(N);
4288            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4289                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4290            }
4291            return new ParceledListSlice<>(out);
4292        }
4293    }
4294
4295    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4296            int filterCallingUid, int userId) {
4297        if (!sUserManager.exists(userId)) return null;
4298        PackageSetting ps = mSettings.mPackages.get(packageName);
4299        if (ps != null) {
4300            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4301                return null;
4302            }
4303            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4304                return null;
4305            }
4306            if (ps.pkg == null) {
4307                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4308                if (pInfo != null) {
4309                    return pInfo.applicationInfo;
4310                }
4311                return null;
4312            }
4313            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4314                    ps.readUserState(userId), userId);
4315            if (ai != null) {
4316                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4317            }
4318            return ai;
4319        }
4320        return null;
4321    }
4322
4323    @Override
4324    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4325        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4326    }
4327
4328    /**
4329     * Important: The provided filterCallingUid is used exclusively to filter out applications
4330     * that can be seen based on user state. It's typically the original caller uid prior
4331     * to clearing. Because it can only be provided by trusted code, it's value can be
4332     * trusted and will be used as-is; unlike userId which will be validated by this method.
4333     */
4334    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4335            int filterCallingUid, int userId) {
4336        if (!sUserManager.exists(userId)) return null;
4337        flags = updateFlagsForApplication(flags, userId, packageName);
4338        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4339                false /* requireFullPermission */, false /* checkShell */, "get application info");
4340
4341        // writer
4342        synchronized (mPackages) {
4343            // Normalize package name to handle renamed packages and static libs
4344            packageName = resolveInternalPackageNameLPr(packageName,
4345                    PackageManager.VERSION_CODE_HIGHEST);
4346
4347            PackageParser.Package p = mPackages.get(packageName);
4348            if (DEBUG_PACKAGE_INFO) Log.v(
4349                    TAG, "getApplicationInfo " + packageName
4350                    + ": " + p);
4351            if (p != null) {
4352                PackageSetting ps = mSettings.mPackages.get(packageName);
4353                if (ps == null) return null;
4354                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4355                    return null;
4356                }
4357                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4358                    return null;
4359                }
4360                // Note: isEnabledLP() does not apply here - always return info
4361                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4362                        p, flags, ps.readUserState(userId), userId);
4363                if (ai != null) {
4364                    ai.packageName = resolveExternalPackageNameLPr(p);
4365                }
4366                return ai;
4367            }
4368            if ("android".equals(packageName)||"system".equals(packageName)) {
4369                return mAndroidApplication;
4370            }
4371            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4372                // Already generates the external package name
4373                return generateApplicationInfoFromSettingsLPw(packageName,
4374                        flags, filterCallingUid, userId);
4375            }
4376        }
4377        return null;
4378    }
4379
4380    private String normalizePackageNameLPr(String packageName) {
4381        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4382        return normalizedPackageName != null ? normalizedPackageName : packageName;
4383    }
4384
4385    @Override
4386    public void deletePreloadsFileCache() {
4387        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4388            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4389        }
4390        File dir = Environment.getDataPreloadsFileCacheDirectory();
4391        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4392        FileUtils.deleteContents(dir);
4393    }
4394
4395    @Override
4396    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4397            final int storageFlags, final IPackageDataObserver observer) {
4398        mContext.enforceCallingOrSelfPermission(
4399                android.Manifest.permission.CLEAR_APP_CACHE, null);
4400        mHandler.post(() -> {
4401            boolean success = false;
4402            try {
4403                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4404                success = true;
4405            } catch (IOException e) {
4406                Slog.w(TAG, e);
4407            }
4408            if (observer != null) {
4409                try {
4410                    observer.onRemoveCompleted(null, success);
4411                } catch (RemoteException e) {
4412                    Slog.w(TAG, e);
4413                }
4414            }
4415        });
4416    }
4417
4418    @Override
4419    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4420            final int storageFlags, final IntentSender pi) {
4421        mContext.enforceCallingOrSelfPermission(
4422                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4423        mHandler.post(() -> {
4424            boolean success = false;
4425            try {
4426                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4427                success = true;
4428            } catch (IOException e) {
4429                Slog.w(TAG, e);
4430            }
4431            if (pi != null) {
4432                try {
4433                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4434                } catch (SendIntentException e) {
4435                    Slog.w(TAG, e);
4436                }
4437            }
4438        });
4439    }
4440
4441    /**
4442     * Blocking call to clear various types of cached data across the system
4443     * until the requested bytes are available.
4444     */
4445    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4446        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4447        final File file = storage.findPathForUuid(volumeUuid);
4448        if (file.getUsableSpace() >= bytes) return;
4449
4450        if (ENABLE_FREE_CACHE_V2) {
4451            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4452                    volumeUuid);
4453            final boolean aggressive = (storageFlags
4454                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4455            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4456
4457            // 1. Pre-flight to determine if we have any chance to succeed
4458            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4459            if (internalVolume && (aggressive || SystemProperties
4460                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4461                deletePreloadsFileCache();
4462                if (file.getUsableSpace() >= bytes) return;
4463            }
4464
4465            // 3. Consider parsed APK data (aggressive only)
4466            if (internalVolume && aggressive) {
4467                FileUtils.deleteContents(mCacheDir);
4468                if (file.getUsableSpace() >= bytes) return;
4469            }
4470
4471            // 4. Consider cached app data (above quotas)
4472            try {
4473                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4474                        Installer.FLAG_FREE_CACHE_V2);
4475            } catch (InstallerException ignored) {
4476            }
4477            if (file.getUsableSpace() >= bytes) return;
4478
4479            // 5. Consider shared libraries with refcount=0 and age>min cache period
4480            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4481                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4482                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4483                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4484                return;
4485            }
4486
4487            // 6. Consider dexopt output (aggressive only)
4488            // TODO: Implement
4489
4490            // 7. Consider installed instant apps unused longer than min cache period
4491            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4492                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4493                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4494                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4495                return;
4496            }
4497
4498            // 8. Consider cached app data (below quotas)
4499            try {
4500                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4501                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4502            } catch (InstallerException ignored) {
4503            }
4504            if (file.getUsableSpace() >= bytes) return;
4505
4506            // 9. Consider DropBox entries
4507            // TODO: Implement
4508
4509            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4510            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4511                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4512                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4513                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4514                return;
4515            }
4516        } else {
4517            try {
4518                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4519            } catch (InstallerException ignored) {
4520            }
4521            if (file.getUsableSpace() >= bytes) return;
4522        }
4523
4524        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4525    }
4526
4527    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4528            throws IOException {
4529        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4530        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4531
4532        List<VersionedPackage> packagesToDelete = null;
4533        final long now = System.currentTimeMillis();
4534
4535        synchronized (mPackages) {
4536            final int[] allUsers = sUserManager.getUserIds();
4537            final int libCount = mSharedLibraries.size();
4538            for (int i = 0; i < libCount; i++) {
4539                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4540                if (versionedLib == null) {
4541                    continue;
4542                }
4543                final int versionCount = versionedLib.size();
4544                for (int j = 0; j < versionCount; j++) {
4545                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4546                    // Skip packages that are not static shared libs.
4547                    if (!libInfo.isStatic()) {
4548                        break;
4549                    }
4550                    // Important: We skip static shared libs used for some user since
4551                    // in such a case we need to keep the APK on the device. The check for
4552                    // a lib being used for any user is performed by the uninstall call.
4553                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4554                    // Resolve the package name - we use synthetic package names internally
4555                    final String internalPackageName = resolveInternalPackageNameLPr(
4556                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4557                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4558                    // Skip unused static shared libs cached less than the min period
4559                    // to prevent pruning a lib needed by a subsequently installed package.
4560                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4561                        continue;
4562                    }
4563                    if (packagesToDelete == null) {
4564                        packagesToDelete = new ArrayList<>();
4565                    }
4566                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4567                            declaringPackage.getVersionCode()));
4568                }
4569            }
4570        }
4571
4572        if (packagesToDelete != null) {
4573            final int packageCount = packagesToDelete.size();
4574            for (int i = 0; i < packageCount; i++) {
4575                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4576                // Delete the package synchronously (will fail of the lib used for any user).
4577                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4578                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4579                                == PackageManager.DELETE_SUCCEEDED) {
4580                    if (volume.getUsableSpace() >= neededSpace) {
4581                        return true;
4582                    }
4583                }
4584            }
4585        }
4586
4587        return false;
4588    }
4589
4590    /**
4591     * Update given flags based on encryption status of current user.
4592     */
4593    private int updateFlags(int flags, int userId) {
4594        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4595                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4596            // Caller expressed an explicit opinion about what encryption
4597            // aware/unaware components they want to see, so fall through and
4598            // give them what they want
4599        } else {
4600            // Caller expressed no opinion, so match based on user state
4601            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4602                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4603            } else {
4604                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4605            }
4606        }
4607        return flags;
4608    }
4609
4610    private UserManagerInternal getUserManagerInternal() {
4611        if (mUserManagerInternal == null) {
4612            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4613        }
4614        return mUserManagerInternal;
4615    }
4616
4617    private DeviceIdleController.LocalService getDeviceIdleController() {
4618        if (mDeviceIdleController == null) {
4619            mDeviceIdleController =
4620                    LocalServices.getService(DeviceIdleController.LocalService.class);
4621        }
4622        return mDeviceIdleController;
4623    }
4624
4625    /**
4626     * Update given flags when being used to request {@link PackageInfo}.
4627     */
4628    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4629        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4630        boolean triaged = true;
4631        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4632                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4633            // Caller is asking for component details, so they'd better be
4634            // asking for specific encryption matching behavior, or be triaged
4635            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4636                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4637                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4638                triaged = false;
4639            }
4640        }
4641        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4642                | PackageManager.MATCH_SYSTEM_ONLY
4643                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4644            triaged = false;
4645        }
4646        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4647            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4648                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4649                    + Debug.getCallers(5));
4650        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4651                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4652            // If the caller wants all packages and has a restricted profile associated with it,
4653            // then match all users. This is to make sure that launchers that need to access work
4654            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4655            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4656            flags |= PackageManager.MATCH_ANY_USER;
4657        }
4658        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4659            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4660                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4661        }
4662        return updateFlags(flags, userId);
4663    }
4664
4665    /**
4666     * Update given flags when being used to request {@link ApplicationInfo}.
4667     */
4668    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4669        return updateFlagsForPackage(flags, userId, cookie);
4670    }
4671
4672    /**
4673     * Update given flags when being used to request {@link ComponentInfo}.
4674     */
4675    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4676        if (cookie instanceof Intent) {
4677            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4678                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4679            }
4680        }
4681
4682        boolean triaged = true;
4683        // Caller is asking for component details, so they'd better be
4684        // asking for specific encryption matching behavior, or be triaged
4685        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4686                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4687                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4688            triaged = false;
4689        }
4690        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4691            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4692                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4693        }
4694
4695        return updateFlags(flags, userId);
4696    }
4697
4698    /**
4699     * Update given intent when being used to request {@link ResolveInfo}.
4700     */
4701    private Intent updateIntentForResolve(Intent intent) {
4702        if (intent.getSelector() != null) {
4703            intent = intent.getSelector();
4704        }
4705        if (DEBUG_PREFERRED) {
4706            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4707        }
4708        return intent;
4709    }
4710
4711    /**
4712     * Update given flags when being used to request {@link ResolveInfo}.
4713     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4714     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4715     * flag set. However, this flag is only honoured in three circumstances:
4716     * <ul>
4717     * <li>when called from a system process</li>
4718     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4719     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4720     * action and a {@code android.intent.category.BROWSABLE} category</li>
4721     * </ul>
4722     */
4723    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4724        return updateFlagsForResolve(flags, userId, intent, callingUid,
4725                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4726    }
4727    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4728            boolean wantInstantApps) {
4729        return updateFlagsForResolve(flags, userId, intent, callingUid,
4730                wantInstantApps, false /*onlyExposedExplicitly*/);
4731    }
4732    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4733            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4734        // Safe mode means we shouldn't match any third-party components
4735        if (mSafeMode) {
4736            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4737        }
4738        if (getInstantAppPackageName(callingUid) != null) {
4739            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4740            if (onlyExposedExplicitly) {
4741                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4742            }
4743            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4744            flags |= PackageManager.MATCH_INSTANT;
4745        } else {
4746            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4747            final boolean allowMatchInstant =
4748                    (wantInstantApps
4749                            && Intent.ACTION_VIEW.equals(intent.getAction())
4750                            && hasWebURI(intent))
4751                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4752            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4753                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4754            if (!allowMatchInstant) {
4755                flags &= ~PackageManager.MATCH_INSTANT;
4756            }
4757        }
4758        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4759    }
4760
4761    @Override
4762    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4763        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4764    }
4765
4766    /**
4767     * Important: The provided filterCallingUid is used exclusively to filter out activities
4768     * that can be seen based on user state. It's typically the original caller uid prior
4769     * to clearing. Because it can only be provided by trusted code, it's value can be
4770     * trusted and will be used as-is; unlike userId which will be validated by this method.
4771     */
4772    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4773            int filterCallingUid, int userId) {
4774        if (!sUserManager.exists(userId)) return null;
4775        flags = updateFlagsForComponent(flags, userId, component);
4776        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4777                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4778        synchronized (mPackages) {
4779            PackageParser.Activity a = mActivities.mActivities.get(component);
4780
4781            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4782            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4783                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4784                if (ps == null) return null;
4785                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4786                    return null;
4787                }
4788                return PackageParser.generateActivityInfo(
4789                        a, flags, ps.readUserState(userId), userId);
4790            }
4791            if (mResolveComponentName.equals(component)) {
4792                return PackageParser.generateActivityInfo(
4793                        mResolveActivity, flags, new PackageUserState(), userId);
4794            }
4795        }
4796        return null;
4797    }
4798
4799    @Override
4800    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4801            String resolvedType) {
4802        synchronized (mPackages) {
4803            if (component.equals(mResolveComponentName)) {
4804                // The resolver supports EVERYTHING!
4805                return true;
4806            }
4807            final int callingUid = Binder.getCallingUid();
4808            final int callingUserId = UserHandle.getUserId(callingUid);
4809            PackageParser.Activity a = mActivities.mActivities.get(component);
4810            if (a == null) {
4811                return false;
4812            }
4813            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4814            if (ps == null) {
4815                return false;
4816            }
4817            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4818                return false;
4819            }
4820            for (int i=0; i<a.intents.size(); i++) {
4821                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4822                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4823                    return true;
4824                }
4825            }
4826            return false;
4827        }
4828    }
4829
4830    @Override
4831    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4832        if (!sUserManager.exists(userId)) return null;
4833        final int callingUid = Binder.getCallingUid();
4834        flags = updateFlagsForComponent(flags, userId, component);
4835        enforceCrossUserPermission(callingUid, userId,
4836                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4837        synchronized (mPackages) {
4838            PackageParser.Activity a = mReceivers.mActivities.get(component);
4839            if (DEBUG_PACKAGE_INFO) Log.v(
4840                TAG, "getReceiverInfo " + component + ": " + a);
4841            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4842                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4843                if (ps == null) return null;
4844                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4845                    return null;
4846                }
4847                return PackageParser.generateActivityInfo(
4848                        a, flags, ps.readUserState(userId), userId);
4849            }
4850        }
4851        return null;
4852    }
4853
4854    @Override
4855    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4856            int flags, int userId) {
4857        if (!sUserManager.exists(userId)) return null;
4858        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4859        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4860            return null;
4861        }
4862
4863        flags = updateFlagsForPackage(flags, userId, null);
4864
4865        final boolean canSeeStaticLibraries =
4866                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4867                        == PERMISSION_GRANTED
4868                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4869                        == PERMISSION_GRANTED
4870                || canRequestPackageInstallsInternal(packageName,
4871                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4872                        false  /* throwIfPermNotDeclared*/)
4873                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4874                        == PERMISSION_GRANTED;
4875
4876        synchronized (mPackages) {
4877            List<SharedLibraryInfo> result = null;
4878
4879            final int libCount = mSharedLibraries.size();
4880            for (int i = 0; i < libCount; i++) {
4881                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4882                if (versionedLib == null) {
4883                    continue;
4884                }
4885
4886                final int versionCount = versionedLib.size();
4887                for (int j = 0; j < versionCount; j++) {
4888                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4889                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4890                        break;
4891                    }
4892                    final long identity = Binder.clearCallingIdentity();
4893                    try {
4894                        PackageInfo packageInfo = getPackageInfoVersioned(
4895                                libInfo.getDeclaringPackage(), flags
4896                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4897                        if (packageInfo == null) {
4898                            continue;
4899                        }
4900                    } finally {
4901                        Binder.restoreCallingIdentity(identity);
4902                    }
4903
4904                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4905                            libInfo.getVersion(), libInfo.getType(),
4906                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4907                            flags, userId));
4908
4909                    if (result == null) {
4910                        result = new ArrayList<>();
4911                    }
4912                    result.add(resLibInfo);
4913                }
4914            }
4915
4916            return result != null ? new ParceledListSlice<>(result) : null;
4917        }
4918    }
4919
4920    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4921            SharedLibraryInfo libInfo, int flags, int userId) {
4922        List<VersionedPackage> versionedPackages = null;
4923        final int packageCount = mSettings.mPackages.size();
4924        for (int i = 0; i < packageCount; i++) {
4925            PackageSetting ps = mSettings.mPackages.valueAt(i);
4926
4927            if (ps == null) {
4928                continue;
4929            }
4930
4931            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4932                continue;
4933            }
4934
4935            final String libName = libInfo.getName();
4936            if (libInfo.isStatic()) {
4937                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4938                if (libIdx < 0) {
4939                    continue;
4940                }
4941                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4942                    continue;
4943                }
4944                if (versionedPackages == null) {
4945                    versionedPackages = new ArrayList<>();
4946                }
4947                // If the dependent is a static shared lib, use the public package name
4948                String dependentPackageName = ps.name;
4949                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4950                    dependentPackageName = ps.pkg.manifestPackageName;
4951                }
4952                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4953            } else if (ps.pkg != null) {
4954                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4955                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4956                    if (versionedPackages == null) {
4957                        versionedPackages = new ArrayList<>();
4958                    }
4959                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4960                }
4961            }
4962        }
4963
4964        return versionedPackages;
4965    }
4966
4967    @Override
4968    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4969        if (!sUserManager.exists(userId)) return null;
4970        final int callingUid = Binder.getCallingUid();
4971        flags = updateFlagsForComponent(flags, userId, component);
4972        enforceCrossUserPermission(callingUid, userId,
4973                false /* requireFullPermission */, false /* checkShell */, "get service info");
4974        synchronized (mPackages) {
4975            PackageParser.Service s = mServices.mServices.get(component);
4976            if (DEBUG_PACKAGE_INFO) Log.v(
4977                TAG, "getServiceInfo " + component + ": " + s);
4978            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4979                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4980                if (ps == null) return null;
4981                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4982                    return null;
4983                }
4984                return PackageParser.generateServiceInfo(
4985                        s, flags, ps.readUserState(userId), userId);
4986            }
4987        }
4988        return null;
4989    }
4990
4991    @Override
4992    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4993        if (!sUserManager.exists(userId)) return null;
4994        final int callingUid = Binder.getCallingUid();
4995        flags = updateFlagsForComponent(flags, userId, component);
4996        enforceCrossUserPermission(callingUid, userId,
4997                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4998        synchronized (mPackages) {
4999            PackageParser.Provider p = mProviders.mProviders.get(component);
5000            if (DEBUG_PACKAGE_INFO) Log.v(
5001                TAG, "getProviderInfo " + component + ": " + p);
5002            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5003                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5004                if (ps == null) return null;
5005                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5006                    return null;
5007                }
5008                return PackageParser.generateProviderInfo(
5009                        p, flags, ps.readUserState(userId), userId);
5010            }
5011        }
5012        return null;
5013    }
5014
5015    @Override
5016    public String[] getSystemSharedLibraryNames() {
5017        // allow instant applications
5018        synchronized (mPackages) {
5019            Set<String> libs = null;
5020            final int libCount = mSharedLibraries.size();
5021            for (int i = 0; i < libCount; i++) {
5022                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5023                if (versionedLib == null) {
5024                    continue;
5025                }
5026                final int versionCount = versionedLib.size();
5027                for (int j = 0; j < versionCount; j++) {
5028                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5029                    if (!libEntry.info.isStatic()) {
5030                        if (libs == null) {
5031                            libs = new ArraySet<>();
5032                        }
5033                        libs.add(libEntry.info.getName());
5034                        break;
5035                    }
5036                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5037                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5038                            UserHandle.getUserId(Binder.getCallingUid()),
5039                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5040                        if (libs == null) {
5041                            libs = new ArraySet<>();
5042                        }
5043                        libs.add(libEntry.info.getName());
5044                        break;
5045                    }
5046                }
5047            }
5048
5049            if (libs != null) {
5050                String[] libsArray = new String[libs.size()];
5051                libs.toArray(libsArray);
5052                return libsArray;
5053            }
5054
5055            return null;
5056        }
5057    }
5058
5059    @Override
5060    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5061        // allow instant applications
5062        synchronized (mPackages) {
5063            return mServicesSystemSharedLibraryPackageName;
5064        }
5065    }
5066
5067    @Override
5068    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5069        // allow instant applications
5070        synchronized (mPackages) {
5071            return mSharedSystemSharedLibraryPackageName;
5072        }
5073    }
5074
5075    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5076        for (int i = userList.length - 1; i >= 0; --i) {
5077            final int userId = userList[i];
5078            // don't add instant app to the list of updates
5079            if (pkgSetting.getInstantApp(userId)) {
5080                continue;
5081            }
5082            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5083            if (changedPackages == null) {
5084                changedPackages = new SparseArray<>();
5085                mChangedPackages.put(userId, changedPackages);
5086            }
5087            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5088            if (sequenceNumbers == null) {
5089                sequenceNumbers = new HashMap<>();
5090                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5091            }
5092            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5093            if (sequenceNumber != null) {
5094                changedPackages.remove(sequenceNumber);
5095            }
5096            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5097            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5098        }
5099        mChangedPackagesSequenceNumber++;
5100    }
5101
5102    @Override
5103    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5104        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5105            return null;
5106        }
5107        synchronized (mPackages) {
5108            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5109                return null;
5110            }
5111            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5112            if (changedPackages == null) {
5113                return null;
5114            }
5115            final List<String> packageNames =
5116                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5117            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5118                final String packageName = changedPackages.get(i);
5119                if (packageName != null) {
5120                    packageNames.add(packageName);
5121                }
5122            }
5123            return packageNames.isEmpty()
5124                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5125        }
5126    }
5127
5128    @Override
5129    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5130        // allow instant applications
5131        ArrayList<FeatureInfo> res;
5132        synchronized (mAvailableFeatures) {
5133            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5134            res.addAll(mAvailableFeatures.values());
5135        }
5136        final FeatureInfo fi = new FeatureInfo();
5137        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5138                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5139        res.add(fi);
5140
5141        return new ParceledListSlice<>(res);
5142    }
5143
5144    @Override
5145    public boolean hasSystemFeature(String name, int version) {
5146        // allow instant applications
5147        synchronized (mAvailableFeatures) {
5148            final FeatureInfo feat = mAvailableFeatures.get(name);
5149            if (feat == null) {
5150                return false;
5151            } else {
5152                return feat.version >= version;
5153            }
5154        }
5155    }
5156
5157    @Override
5158    public int checkPermission(String permName, String pkgName, int userId) {
5159        if (!sUserManager.exists(userId)) {
5160            return PackageManager.PERMISSION_DENIED;
5161        }
5162        final int callingUid = Binder.getCallingUid();
5163
5164        synchronized (mPackages) {
5165            final PackageParser.Package p = mPackages.get(pkgName);
5166            if (p != null && p.mExtras != null) {
5167                final PackageSetting ps = (PackageSetting) p.mExtras;
5168                if (filterAppAccessLPr(ps, callingUid, userId)) {
5169                    return PackageManager.PERMISSION_DENIED;
5170                }
5171                final boolean instantApp = ps.getInstantApp(userId);
5172                final PermissionsState permissionsState = ps.getPermissionsState();
5173                if (permissionsState.hasPermission(permName, userId)) {
5174                    if (instantApp) {
5175                        BasePermission bp = mSettings.mPermissions.get(permName);
5176                        if (bp != null && bp.isInstant()) {
5177                            return PackageManager.PERMISSION_GRANTED;
5178                        }
5179                    } else {
5180                        return PackageManager.PERMISSION_GRANTED;
5181                    }
5182                }
5183                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5184                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5185                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5186                    return PackageManager.PERMISSION_GRANTED;
5187                }
5188            }
5189        }
5190
5191        return PackageManager.PERMISSION_DENIED;
5192    }
5193
5194    @Override
5195    public int checkUidPermission(String permName, int uid) {
5196        final int callingUid = Binder.getCallingUid();
5197        final int callingUserId = UserHandle.getUserId(callingUid);
5198        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5199        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5200        final int userId = UserHandle.getUserId(uid);
5201        if (!sUserManager.exists(userId)) {
5202            return PackageManager.PERMISSION_DENIED;
5203        }
5204
5205        synchronized (mPackages) {
5206            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5207            if (obj != null) {
5208                if (obj instanceof SharedUserSetting) {
5209                    if (isCallerInstantApp) {
5210                        return PackageManager.PERMISSION_DENIED;
5211                    }
5212                } else if (obj instanceof PackageSetting) {
5213                    final PackageSetting ps = (PackageSetting) obj;
5214                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5215                        return PackageManager.PERMISSION_DENIED;
5216                    }
5217                }
5218                final SettingBase settingBase = (SettingBase) obj;
5219                final PermissionsState permissionsState = settingBase.getPermissionsState();
5220                if (permissionsState.hasPermission(permName, userId)) {
5221                    if (isUidInstantApp) {
5222                        BasePermission bp = mSettings.mPermissions.get(permName);
5223                        if (bp != null && bp.isInstant()) {
5224                            return PackageManager.PERMISSION_GRANTED;
5225                        }
5226                    } else {
5227                        return PackageManager.PERMISSION_GRANTED;
5228                    }
5229                }
5230                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5231                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5232                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5233                    return PackageManager.PERMISSION_GRANTED;
5234                }
5235            } else {
5236                ArraySet<String> perms = mSystemPermissions.get(uid);
5237                if (perms != null) {
5238                    if (perms.contains(permName)) {
5239                        return PackageManager.PERMISSION_GRANTED;
5240                    }
5241                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5242                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5243                        return PackageManager.PERMISSION_GRANTED;
5244                    }
5245                }
5246            }
5247        }
5248
5249        return PackageManager.PERMISSION_DENIED;
5250    }
5251
5252    @Override
5253    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5254        if (UserHandle.getCallingUserId() != userId) {
5255            mContext.enforceCallingPermission(
5256                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5257                    "isPermissionRevokedByPolicy for user " + userId);
5258        }
5259
5260        if (checkPermission(permission, packageName, userId)
5261                == PackageManager.PERMISSION_GRANTED) {
5262            return false;
5263        }
5264
5265        final int callingUid = Binder.getCallingUid();
5266        if (getInstantAppPackageName(callingUid) != null) {
5267            if (!isCallerSameApp(packageName, callingUid)) {
5268                return false;
5269            }
5270        } else {
5271            if (isInstantApp(packageName, userId)) {
5272                return false;
5273            }
5274        }
5275
5276        final long identity = Binder.clearCallingIdentity();
5277        try {
5278            final int flags = getPermissionFlags(permission, packageName, userId);
5279            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5280        } finally {
5281            Binder.restoreCallingIdentity(identity);
5282        }
5283    }
5284
5285    @Override
5286    public String getPermissionControllerPackageName() {
5287        synchronized (mPackages) {
5288            return mRequiredInstallerPackage;
5289        }
5290    }
5291
5292    /**
5293     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5294     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5295     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5296     * @param message the message to log on security exception
5297     */
5298    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5299            boolean checkShell, String message) {
5300        if (userId < 0) {
5301            throw new IllegalArgumentException("Invalid userId " + userId);
5302        }
5303        if (checkShell) {
5304            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5305        }
5306        if (userId == UserHandle.getUserId(callingUid)) return;
5307        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5308            if (requireFullPermission) {
5309                mContext.enforceCallingOrSelfPermission(
5310                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5311            } else {
5312                try {
5313                    mContext.enforceCallingOrSelfPermission(
5314                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5315                } catch (SecurityException se) {
5316                    mContext.enforceCallingOrSelfPermission(
5317                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5318                }
5319            }
5320        }
5321    }
5322
5323    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5324        if (callingUid == Process.SHELL_UID) {
5325            if (userHandle >= 0
5326                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5327                throw new SecurityException("Shell does not have permission to access user "
5328                        + userHandle);
5329            } else if (userHandle < 0) {
5330                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5331                        + Debug.getCallers(3));
5332            }
5333        }
5334    }
5335
5336    private BasePermission findPermissionTreeLP(String permName) {
5337        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5338            if (permName.startsWith(bp.name) &&
5339                    permName.length() > bp.name.length() &&
5340                    permName.charAt(bp.name.length()) == '.') {
5341                return bp;
5342            }
5343        }
5344        return null;
5345    }
5346
5347    private BasePermission checkPermissionTreeLP(String permName) {
5348        if (permName != null) {
5349            BasePermission bp = findPermissionTreeLP(permName);
5350            if (bp != null) {
5351                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5352                    return bp;
5353                }
5354                throw new SecurityException("Calling uid "
5355                        + Binder.getCallingUid()
5356                        + " is not allowed to add to permission tree "
5357                        + bp.name + " owned by uid " + bp.uid);
5358            }
5359        }
5360        throw new SecurityException("No permission tree found for " + permName);
5361    }
5362
5363    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5364        if (s1 == null) {
5365            return s2 == null;
5366        }
5367        if (s2 == null) {
5368            return false;
5369        }
5370        if (s1.getClass() != s2.getClass()) {
5371            return false;
5372        }
5373        return s1.equals(s2);
5374    }
5375
5376    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5377        if (pi1.icon != pi2.icon) return false;
5378        if (pi1.logo != pi2.logo) return false;
5379        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5380        if (!compareStrings(pi1.name, pi2.name)) return false;
5381        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5382        // We'll take care of setting this one.
5383        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5384        // These are not currently stored in settings.
5385        //if (!compareStrings(pi1.group, pi2.group)) return false;
5386        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5387        //if (pi1.labelRes != pi2.labelRes) return false;
5388        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5389        return true;
5390    }
5391
5392    int permissionInfoFootprint(PermissionInfo info) {
5393        int size = info.name.length();
5394        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5395        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5396        return size;
5397    }
5398
5399    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5400        int size = 0;
5401        for (BasePermission perm : mSettings.mPermissions.values()) {
5402            if (perm.uid == tree.uid) {
5403                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5404            }
5405        }
5406        return size;
5407    }
5408
5409    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5410        // We calculate the max size of permissions defined by this uid and throw
5411        // if that plus the size of 'info' would exceed our stated maximum.
5412        if (tree.uid != Process.SYSTEM_UID) {
5413            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5414            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5415                throw new SecurityException("Permission tree size cap exceeded");
5416            }
5417        }
5418    }
5419
5420    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5421        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5422            throw new SecurityException("Instant apps can't add permissions");
5423        }
5424        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5425            throw new SecurityException("Label must be specified in permission");
5426        }
5427        BasePermission tree = checkPermissionTreeLP(info.name);
5428        BasePermission bp = mSettings.mPermissions.get(info.name);
5429        boolean added = bp == null;
5430        boolean changed = true;
5431        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5432        if (added) {
5433            enforcePermissionCapLocked(info, tree);
5434            bp = new BasePermission(info.name, tree.sourcePackage,
5435                    BasePermission.TYPE_DYNAMIC);
5436        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5437            throw new SecurityException(
5438                    "Not allowed to modify non-dynamic permission "
5439                    + info.name);
5440        } else {
5441            if (bp.protectionLevel == fixedLevel
5442                    && bp.perm.owner.equals(tree.perm.owner)
5443                    && bp.uid == tree.uid
5444                    && comparePermissionInfos(bp.perm.info, info)) {
5445                changed = false;
5446            }
5447        }
5448        bp.protectionLevel = fixedLevel;
5449        info = new PermissionInfo(info);
5450        info.protectionLevel = fixedLevel;
5451        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5452        bp.perm.info.packageName = tree.perm.info.packageName;
5453        bp.uid = tree.uid;
5454        if (added) {
5455            mSettings.mPermissions.put(info.name, bp);
5456        }
5457        if (changed) {
5458            if (!async) {
5459                mSettings.writeLPr();
5460            } else {
5461                scheduleWriteSettingsLocked();
5462            }
5463        }
5464        return added;
5465    }
5466
5467    @Override
5468    public boolean addPermission(PermissionInfo info) {
5469        synchronized (mPackages) {
5470            return addPermissionLocked(info, false);
5471        }
5472    }
5473
5474    @Override
5475    public boolean addPermissionAsync(PermissionInfo info) {
5476        synchronized (mPackages) {
5477            return addPermissionLocked(info, true);
5478        }
5479    }
5480
5481    @Override
5482    public void removePermission(String name) {
5483        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5484            throw new SecurityException("Instant applications don't have access to this method");
5485        }
5486        synchronized (mPackages) {
5487            checkPermissionTreeLP(name);
5488            BasePermission bp = mSettings.mPermissions.get(name);
5489            if (bp != null) {
5490                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5491                    throw new SecurityException(
5492                            "Not allowed to modify non-dynamic permission "
5493                            + name);
5494                }
5495                mSettings.mPermissions.remove(name);
5496                mSettings.writeLPr();
5497            }
5498        }
5499    }
5500
5501    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5502            PackageParser.Package pkg, BasePermission bp) {
5503        int index = pkg.requestedPermissions.indexOf(bp.name);
5504        if (index == -1) {
5505            throw new SecurityException("Package " + pkg.packageName
5506                    + " has not requested permission " + bp.name);
5507        }
5508        if (!bp.isRuntime() && !bp.isDevelopment()) {
5509            throw new SecurityException("Permission " + bp.name
5510                    + " is not a changeable permission type");
5511        }
5512    }
5513
5514    @Override
5515    public void grantRuntimePermission(String packageName, String name, final int userId) {
5516        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5517    }
5518
5519    private void grantRuntimePermission(String packageName, String name, final int userId,
5520            boolean overridePolicy) {
5521        if (!sUserManager.exists(userId)) {
5522            Log.e(TAG, "No such user:" + userId);
5523            return;
5524        }
5525        final int callingUid = Binder.getCallingUid();
5526
5527        mContext.enforceCallingOrSelfPermission(
5528                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5529                "grantRuntimePermission");
5530
5531        enforceCrossUserPermission(callingUid, userId,
5532                true /* requireFullPermission */, true /* checkShell */,
5533                "grantRuntimePermission");
5534
5535        final int uid;
5536        final PackageSetting ps;
5537
5538        synchronized (mPackages) {
5539            final PackageParser.Package pkg = mPackages.get(packageName);
5540            if (pkg == null) {
5541                throw new IllegalArgumentException("Unknown package: " + packageName);
5542            }
5543            final BasePermission bp = mSettings.mPermissions.get(name);
5544            if (bp == null) {
5545                throw new IllegalArgumentException("Unknown permission: " + name);
5546            }
5547            ps = (PackageSetting) pkg.mExtras;
5548            if (ps == null
5549                    || filterAppAccessLPr(ps, callingUid, userId)) {
5550                throw new IllegalArgumentException("Unknown package: " + packageName);
5551            }
5552
5553            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5554
5555            // If a permission review is required for legacy apps we represent
5556            // their permissions as always granted runtime ones since we need
5557            // to keep the review required permission flag per user while an
5558            // install permission's state is shared across all users.
5559            if (mPermissionReviewRequired
5560                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5561                    && bp.isRuntime()) {
5562                return;
5563            }
5564
5565            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5566
5567            final PermissionsState permissionsState = ps.getPermissionsState();
5568
5569            final int flags = permissionsState.getPermissionFlags(name, userId);
5570            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5571                throw new SecurityException("Cannot grant system fixed permission "
5572                        + name + " for package " + packageName);
5573            }
5574            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5575                throw new SecurityException("Cannot grant policy fixed permission "
5576                        + name + " for package " + packageName);
5577            }
5578
5579            if (bp.isDevelopment()) {
5580                // Development permissions must be handled specially, since they are not
5581                // normal runtime permissions.  For now they apply to all users.
5582                if (permissionsState.grantInstallPermission(bp) !=
5583                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5584                    scheduleWriteSettingsLocked();
5585                }
5586                return;
5587            }
5588
5589            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5590                throw new SecurityException("Cannot grant non-ephemeral permission"
5591                        + name + " for package " + packageName);
5592            }
5593
5594            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5595                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5596                return;
5597            }
5598
5599            final int result = permissionsState.grantRuntimePermission(bp, userId);
5600            switch (result) {
5601                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5602                    return;
5603                }
5604
5605                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5606                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5607                    mHandler.post(new Runnable() {
5608                        @Override
5609                        public void run() {
5610                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5611                        }
5612                    });
5613                }
5614                break;
5615            }
5616
5617            if (bp.isRuntime()) {
5618                logPermissionGranted(mContext, name, packageName);
5619            }
5620
5621            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5622
5623            // Not critical if that is lost - app has to request again.
5624            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5625        }
5626
5627        // Only need to do this if user is initialized. Otherwise it's a new user
5628        // and there are no processes running as the user yet and there's no need
5629        // to make an expensive call to remount processes for the changed permissions.
5630        if (READ_EXTERNAL_STORAGE.equals(name)
5631                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5632            final long token = Binder.clearCallingIdentity();
5633            try {
5634                if (sUserManager.isInitialized(userId)) {
5635                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5636                            StorageManagerInternal.class);
5637                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5638                }
5639            } finally {
5640                Binder.restoreCallingIdentity(token);
5641            }
5642        }
5643    }
5644
5645    @Override
5646    public void revokeRuntimePermission(String packageName, String name, int userId) {
5647        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5648    }
5649
5650    private void revokeRuntimePermission(String packageName, String name, int userId,
5651            boolean overridePolicy) {
5652        if (!sUserManager.exists(userId)) {
5653            Log.e(TAG, "No such user:" + userId);
5654            return;
5655        }
5656
5657        mContext.enforceCallingOrSelfPermission(
5658                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5659                "revokeRuntimePermission");
5660
5661        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5662                true /* requireFullPermission */, true /* checkShell */,
5663                "revokeRuntimePermission");
5664
5665        final int appId;
5666
5667        synchronized (mPackages) {
5668            final PackageParser.Package pkg = mPackages.get(packageName);
5669            if (pkg == null) {
5670                throw new IllegalArgumentException("Unknown package: " + packageName);
5671            }
5672            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5673            if (ps == null
5674                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5675                throw new IllegalArgumentException("Unknown package: " + packageName);
5676            }
5677            final BasePermission bp = mSettings.mPermissions.get(name);
5678            if (bp == null) {
5679                throw new IllegalArgumentException("Unknown permission: " + name);
5680            }
5681
5682            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5683
5684            // If a permission review is required for legacy apps we represent
5685            // their permissions as always granted runtime ones since we need
5686            // to keep the review required permission flag per user while an
5687            // install permission's state is shared across all users.
5688            if (mPermissionReviewRequired
5689                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5690                    && bp.isRuntime()) {
5691                return;
5692            }
5693
5694            final PermissionsState permissionsState = ps.getPermissionsState();
5695
5696            final int flags = permissionsState.getPermissionFlags(name, userId);
5697            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5698                throw new SecurityException("Cannot revoke system fixed permission "
5699                        + name + " for package " + packageName);
5700            }
5701            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5702                throw new SecurityException("Cannot revoke policy fixed permission "
5703                        + name + " for package " + packageName);
5704            }
5705
5706            if (bp.isDevelopment()) {
5707                // Development permissions must be handled specially, since they are not
5708                // normal runtime permissions.  For now they apply to all users.
5709                if (permissionsState.revokeInstallPermission(bp) !=
5710                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5711                    scheduleWriteSettingsLocked();
5712                }
5713                return;
5714            }
5715
5716            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5717                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5718                return;
5719            }
5720
5721            if (bp.isRuntime()) {
5722                logPermissionRevoked(mContext, name, packageName);
5723            }
5724
5725            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5726
5727            // Critical, after this call app should never have the permission.
5728            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5729
5730            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5731        }
5732
5733        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5734    }
5735
5736    /**
5737     * Get the first event id for the permission.
5738     *
5739     * <p>There are four events for each permission: <ul>
5740     *     <li>Request permission: first id + 0</li>
5741     *     <li>Grant permission: first id + 1</li>
5742     *     <li>Request for permission denied: first id + 2</li>
5743     *     <li>Revoke permission: first id + 3</li>
5744     * </ul></p>
5745     *
5746     * @param name name of the permission
5747     *
5748     * @return The first event id for the permission
5749     */
5750    private static int getBaseEventId(@NonNull String name) {
5751        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5752
5753        if (eventIdIndex == -1) {
5754            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5755                    || Build.IS_USER) {
5756                Log.i(TAG, "Unknown permission " + name);
5757
5758                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5759            } else {
5760                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5761                //
5762                // Also update
5763                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5764                // - metrics_constants.proto
5765                throw new IllegalStateException("Unknown permission " + name);
5766            }
5767        }
5768
5769        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5770    }
5771
5772    /**
5773     * Log that a permission was revoked.
5774     *
5775     * @param context Context of the caller
5776     * @param name name of the permission
5777     * @param packageName package permission if for
5778     */
5779    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5780            @NonNull String packageName) {
5781        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5782    }
5783
5784    /**
5785     * Log that a permission request was granted.
5786     *
5787     * @param context Context of the caller
5788     * @param name name of the permission
5789     * @param packageName package permission if for
5790     */
5791    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5792            @NonNull String packageName) {
5793        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5794    }
5795
5796    @Override
5797    public void resetRuntimePermissions() {
5798        mContext.enforceCallingOrSelfPermission(
5799                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5800                "revokeRuntimePermission");
5801
5802        int callingUid = Binder.getCallingUid();
5803        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5804            mContext.enforceCallingOrSelfPermission(
5805                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5806                    "resetRuntimePermissions");
5807        }
5808
5809        synchronized (mPackages) {
5810            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5811            for (int userId : UserManagerService.getInstance().getUserIds()) {
5812                final int packageCount = mPackages.size();
5813                for (int i = 0; i < packageCount; i++) {
5814                    PackageParser.Package pkg = mPackages.valueAt(i);
5815                    if (!(pkg.mExtras instanceof PackageSetting)) {
5816                        continue;
5817                    }
5818                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5819                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5820                }
5821            }
5822        }
5823    }
5824
5825    @Override
5826    public int getPermissionFlags(String name, String packageName, int userId) {
5827        if (!sUserManager.exists(userId)) {
5828            return 0;
5829        }
5830
5831        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5832
5833        final int callingUid = Binder.getCallingUid();
5834        enforceCrossUserPermission(callingUid, userId,
5835                true /* requireFullPermission */, false /* checkShell */,
5836                "getPermissionFlags");
5837
5838        synchronized (mPackages) {
5839            final PackageParser.Package pkg = mPackages.get(packageName);
5840            if (pkg == null) {
5841                return 0;
5842            }
5843            final BasePermission bp = mSettings.mPermissions.get(name);
5844            if (bp == null) {
5845                return 0;
5846            }
5847            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5848            if (ps == null
5849                    || filterAppAccessLPr(ps, callingUid, userId)) {
5850                return 0;
5851            }
5852            PermissionsState permissionsState = ps.getPermissionsState();
5853            return permissionsState.getPermissionFlags(name, userId);
5854        }
5855    }
5856
5857    @Override
5858    public void updatePermissionFlags(String name, String packageName, int flagMask,
5859            int flagValues, int userId) {
5860        if (!sUserManager.exists(userId)) {
5861            return;
5862        }
5863
5864        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5865
5866        final int callingUid = Binder.getCallingUid();
5867        enforceCrossUserPermission(callingUid, userId,
5868                true /* requireFullPermission */, true /* checkShell */,
5869                "updatePermissionFlags");
5870
5871        // Only the system can change these flags and nothing else.
5872        if (getCallingUid() != Process.SYSTEM_UID) {
5873            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5874            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5875            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5876            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5877            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5878        }
5879
5880        synchronized (mPackages) {
5881            final PackageParser.Package pkg = mPackages.get(packageName);
5882            if (pkg == null) {
5883                throw new IllegalArgumentException("Unknown package: " + packageName);
5884            }
5885            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5886            if (ps == null
5887                    || filterAppAccessLPr(ps, callingUid, userId)) {
5888                throw new IllegalArgumentException("Unknown package: " + packageName);
5889            }
5890
5891            final BasePermission bp = mSettings.mPermissions.get(name);
5892            if (bp == null) {
5893                throw new IllegalArgumentException("Unknown permission: " + name);
5894            }
5895
5896            PermissionsState permissionsState = ps.getPermissionsState();
5897
5898            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5899
5900            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5901                // Install and runtime permissions are stored in different places,
5902                // so figure out what permission changed and persist the change.
5903                if (permissionsState.getInstallPermissionState(name) != null) {
5904                    scheduleWriteSettingsLocked();
5905                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5906                        || hadState) {
5907                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5908                }
5909            }
5910        }
5911    }
5912
5913    /**
5914     * Update the permission flags for all packages and runtime permissions of a user in order
5915     * to allow device or profile owner to remove POLICY_FIXED.
5916     */
5917    @Override
5918    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5919        if (!sUserManager.exists(userId)) {
5920            return;
5921        }
5922
5923        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5924
5925        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5926                true /* requireFullPermission */, true /* checkShell */,
5927                "updatePermissionFlagsForAllApps");
5928
5929        // Only the system can change system fixed flags.
5930        if (getCallingUid() != Process.SYSTEM_UID) {
5931            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5932            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5933        }
5934
5935        synchronized (mPackages) {
5936            boolean changed = false;
5937            final int packageCount = mPackages.size();
5938            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5939                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5940                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5941                if (ps == null) {
5942                    continue;
5943                }
5944                PermissionsState permissionsState = ps.getPermissionsState();
5945                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5946                        userId, flagMask, flagValues);
5947            }
5948            if (changed) {
5949                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5950            }
5951        }
5952    }
5953
5954    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5955        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5956                != PackageManager.PERMISSION_GRANTED
5957            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5958                != PackageManager.PERMISSION_GRANTED) {
5959            throw new SecurityException(message + " requires "
5960                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5961                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5962        }
5963    }
5964
5965    @Override
5966    public boolean shouldShowRequestPermissionRationale(String permissionName,
5967            String packageName, int userId) {
5968        if (UserHandle.getCallingUserId() != userId) {
5969            mContext.enforceCallingPermission(
5970                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5971                    "canShowRequestPermissionRationale for user " + userId);
5972        }
5973
5974        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5975        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5976            return false;
5977        }
5978
5979        if (checkPermission(permissionName, packageName, userId)
5980                == PackageManager.PERMISSION_GRANTED) {
5981            return false;
5982        }
5983
5984        final int flags;
5985
5986        final long identity = Binder.clearCallingIdentity();
5987        try {
5988            flags = getPermissionFlags(permissionName,
5989                    packageName, userId);
5990        } finally {
5991            Binder.restoreCallingIdentity(identity);
5992        }
5993
5994        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5995                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5996                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5997
5998        if ((flags & fixedFlags) != 0) {
5999            return false;
6000        }
6001
6002        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6003    }
6004
6005    @Override
6006    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6007        mContext.enforceCallingOrSelfPermission(
6008                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6009                "addOnPermissionsChangeListener");
6010
6011        synchronized (mPackages) {
6012            mOnPermissionChangeListeners.addListenerLocked(listener);
6013        }
6014    }
6015
6016    @Override
6017    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6018        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6019            throw new SecurityException("Instant applications don't have access to this method");
6020        }
6021        synchronized (mPackages) {
6022            mOnPermissionChangeListeners.removeListenerLocked(listener);
6023        }
6024    }
6025
6026    @Override
6027    public boolean isProtectedBroadcast(String actionName) {
6028        // allow instant applications
6029        synchronized (mProtectedBroadcasts) {
6030            if (mProtectedBroadcasts.contains(actionName)) {
6031                return true;
6032            } else if (actionName != null) {
6033                // TODO: remove these terrible hacks
6034                if (actionName.startsWith("android.net.netmon.lingerExpired")
6035                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6036                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6037                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6038                    return true;
6039                }
6040            }
6041        }
6042        return false;
6043    }
6044
6045    @Override
6046    public int checkSignatures(String pkg1, String pkg2) {
6047        synchronized (mPackages) {
6048            final PackageParser.Package p1 = mPackages.get(pkg1);
6049            final PackageParser.Package p2 = mPackages.get(pkg2);
6050            if (p1 == null || p1.mExtras == null
6051                    || p2 == null || p2.mExtras == null) {
6052                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6053            }
6054            final int callingUid = Binder.getCallingUid();
6055            final int callingUserId = UserHandle.getUserId(callingUid);
6056            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6057            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6058            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6059                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6060                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6061            }
6062            return compareSignatures(p1.mSignatures, p2.mSignatures);
6063        }
6064    }
6065
6066    @Override
6067    public int checkUidSignatures(int uid1, int uid2) {
6068        final int callingUid = Binder.getCallingUid();
6069        final int callingUserId = UserHandle.getUserId(callingUid);
6070        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6071        // Map to base uids.
6072        uid1 = UserHandle.getAppId(uid1);
6073        uid2 = UserHandle.getAppId(uid2);
6074        // reader
6075        synchronized (mPackages) {
6076            Signature[] s1;
6077            Signature[] s2;
6078            Object obj = mSettings.getUserIdLPr(uid1);
6079            if (obj != null) {
6080                if (obj instanceof SharedUserSetting) {
6081                    if (isCallerInstantApp) {
6082                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6083                    }
6084                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6085                } else if (obj instanceof PackageSetting) {
6086                    final PackageSetting ps = (PackageSetting) obj;
6087                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6088                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6089                    }
6090                    s1 = ps.signatures.mSignatures;
6091                } else {
6092                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6093                }
6094            } else {
6095                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6096            }
6097            obj = mSettings.getUserIdLPr(uid2);
6098            if (obj != null) {
6099                if (obj instanceof SharedUserSetting) {
6100                    if (isCallerInstantApp) {
6101                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6102                    }
6103                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6104                } else if (obj instanceof PackageSetting) {
6105                    final PackageSetting ps = (PackageSetting) obj;
6106                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6107                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6108                    }
6109                    s2 = ps.signatures.mSignatures;
6110                } else {
6111                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6112                }
6113            } else {
6114                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6115            }
6116            return compareSignatures(s1, s2);
6117        }
6118    }
6119
6120    /**
6121     * This method should typically only be used when granting or revoking
6122     * permissions, since the app may immediately restart after this call.
6123     * <p>
6124     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6125     * guard your work against the app being relaunched.
6126     */
6127    private void killUid(int appId, int userId, String reason) {
6128        final long identity = Binder.clearCallingIdentity();
6129        try {
6130            IActivityManager am = ActivityManager.getService();
6131            if (am != null) {
6132                try {
6133                    am.killUid(appId, userId, reason);
6134                } catch (RemoteException e) {
6135                    /* ignore - same process */
6136                }
6137            }
6138        } finally {
6139            Binder.restoreCallingIdentity(identity);
6140        }
6141    }
6142
6143    /**
6144     * Compares two sets of signatures. Returns:
6145     * <br />
6146     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6147     * <br />
6148     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6149     * <br />
6150     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6151     * <br />
6152     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6153     * <br />
6154     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6155     */
6156    static int compareSignatures(Signature[] s1, Signature[] s2) {
6157        if (s1 == null) {
6158            return s2 == null
6159                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6160                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6161        }
6162
6163        if (s2 == null) {
6164            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6165        }
6166
6167        if (s1.length != s2.length) {
6168            return PackageManager.SIGNATURE_NO_MATCH;
6169        }
6170
6171        // Since both signature sets are of size 1, we can compare without HashSets.
6172        if (s1.length == 1) {
6173            return s1[0].equals(s2[0]) ?
6174                    PackageManager.SIGNATURE_MATCH :
6175                    PackageManager.SIGNATURE_NO_MATCH;
6176        }
6177
6178        ArraySet<Signature> set1 = new ArraySet<Signature>();
6179        for (Signature sig : s1) {
6180            set1.add(sig);
6181        }
6182        ArraySet<Signature> set2 = new ArraySet<Signature>();
6183        for (Signature sig : s2) {
6184            set2.add(sig);
6185        }
6186        // Make sure s2 contains all signatures in s1.
6187        if (set1.equals(set2)) {
6188            return PackageManager.SIGNATURE_MATCH;
6189        }
6190        return PackageManager.SIGNATURE_NO_MATCH;
6191    }
6192
6193    /**
6194     * If the database version for this type of package (internal storage or
6195     * external storage) is less than the version where package signatures
6196     * were updated, return true.
6197     */
6198    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6199        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6200        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6201    }
6202
6203    /**
6204     * Used for backward compatibility to make sure any packages with
6205     * certificate chains get upgraded to the new style. {@code existingSigs}
6206     * will be in the old format (since they were stored on disk from before the
6207     * system upgrade) and {@code scannedSigs} will be in the newer format.
6208     */
6209    private int compareSignaturesCompat(PackageSignatures existingSigs,
6210            PackageParser.Package scannedPkg) {
6211        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6212            return PackageManager.SIGNATURE_NO_MATCH;
6213        }
6214
6215        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6216        for (Signature sig : existingSigs.mSignatures) {
6217            existingSet.add(sig);
6218        }
6219        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6220        for (Signature sig : scannedPkg.mSignatures) {
6221            try {
6222                Signature[] chainSignatures = sig.getChainSignatures();
6223                for (Signature chainSig : chainSignatures) {
6224                    scannedCompatSet.add(chainSig);
6225                }
6226            } catch (CertificateEncodingException e) {
6227                scannedCompatSet.add(sig);
6228            }
6229        }
6230        /*
6231         * Make sure the expanded scanned set contains all signatures in the
6232         * existing one.
6233         */
6234        if (scannedCompatSet.equals(existingSet)) {
6235            // Migrate the old signatures to the new scheme.
6236            existingSigs.assignSignatures(scannedPkg.mSignatures);
6237            // The new KeySets will be re-added later in the scanning process.
6238            synchronized (mPackages) {
6239                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6240            }
6241            return PackageManager.SIGNATURE_MATCH;
6242        }
6243        return PackageManager.SIGNATURE_NO_MATCH;
6244    }
6245
6246    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6247        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6248        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6249    }
6250
6251    private int compareSignaturesRecover(PackageSignatures existingSigs,
6252            PackageParser.Package scannedPkg) {
6253        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6254            return PackageManager.SIGNATURE_NO_MATCH;
6255        }
6256
6257        String msg = null;
6258        try {
6259            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6260                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6261                        + scannedPkg.packageName);
6262                return PackageManager.SIGNATURE_MATCH;
6263            }
6264        } catch (CertificateException e) {
6265            msg = e.getMessage();
6266        }
6267
6268        logCriticalInfo(Log.INFO,
6269                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6270        return PackageManager.SIGNATURE_NO_MATCH;
6271    }
6272
6273    @Override
6274    public List<String> getAllPackages() {
6275        final int callingUid = Binder.getCallingUid();
6276        final int callingUserId = UserHandle.getUserId(callingUid);
6277        synchronized (mPackages) {
6278            if (canViewInstantApps(callingUid, callingUserId)) {
6279                return new ArrayList<String>(mPackages.keySet());
6280            }
6281            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6282            final List<String> result = new ArrayList<>();
6283            if (instantAppPkgName != null) {
6284                // caller is an instant application; filter unexposed applications
6285                for (PackageParser.Package pkg : mPackages.values()) {
6286                    if (!pkg.visibleToInstantApps) {
6287                        continue;
6288                    }
6289                    result.add(pkg.packageName);
6290                }
6291            } else {
6292                // caller is a normal application; filter instant applications
6293                for (PackageParser.Package pkg : mPackages.values()) {
6294                    final PackageSetting ps =
6295                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6296                    if (ps != null
6297                            && ps.getInstantApp(callingUserId)
6298                            && !mInstantAppRegistry.isInstantAccessGranted(
6299                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6300                        continue;
6301                    }
6302                    result.add(pkg.packageName);
6303                }
6304            }
6305            return result;
6306        }
6307    }
6308
6309    @Override
6310    public String[] getPackagesForUid(int uid) {
6311        final int callingUid = Binder.getCallingUid();
6312        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6313        final int userId = UserHandle.getUserId(uid);
6314        uid = UserHandle.getAppId(uid);
6315        // reader
6316        synchronized (mPackages) {
6317            Object obj = mSettings.getUserIdLPr(uid);
6318            if (obj instanceof SharedUserSetting) {
6319                if (isCallerInstantApp) {
6320                    return null;
6321                }
6322                final SharedUserSetting sus = (SharedUserSetting) obj;
6323                final int N = sus.packages.size();
6324                String[] res = new String[N];
6325                final Iterator<PackageSetting> it = sus.packages.iterator();
6326                int i = 0;
6327                while (it.hasNext()) {
6328                    PackageSetting ps = it.next();
6329                    if (ps.getInstalled(userId)) {
6330                        res[i++] = ps.name;
6331                    } else {
6332                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6333                    }
6334                }
6335                return res;
6336            } else if (obj instanceof PackageSetting) {
6337                final PackageSetting ps = (PackageSetting) obj;
6338                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6339                    return new String[]{ps.name};
6340                }
6341            }
6342        }
6343        return null;
6344    }
6345
6346    @Override
6347    public String getNameForUid(int uid) {
6348        final int callingUid = Binder.getCallingUid();
6349        if (getInstantAppPackageName(callingUid) != null) {
6350            return null;
6351        }
6352        synchronized (mPackages) {
6353            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6354            if (obj instanceof SharedUserSetting) {
6355                final SharedUserSetting sus = (SharedUserSetting) obj;
6356                return sus.name + ":" + sus.userId;
6357            } else if (obj instanceof PackageSetting) {
6358                final PackageSetting ps = (PackageSetting) obj;
6359                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6360                    return null;
6361                }
6362                return ps.name;
6363            }
6364        }
6365        return null;
6366    }
6367
6368    @Override
6369    public int getUidForSharedUser(String sharedUserName) {
6370        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6371            return -1;
6372        }
6373        if (sharedUserName == null) {
6374            return -1;
6375        }
6376        // reader
6377        synchronized (mPackages) {
6378            SharedUserSetting suid;
6379            try {
6380                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6381                if (suid != null) {
6382                    return suid.userId;
6383                }
6384            } catch (PackageManagerException ignore) {
6385                // can't happen, but, still need to catch it
6386            }
6387            return -1;
6388        }
6389    }
6390
6391    @Override
6392    public int getFlagsForUid(int uid) {
6393        final int callingUid = Binder.getCallingUid();
6394        if (getInstantAppPackageName(callingUid) != null) {
6395            return 0;
6396        }
6397        synchronized (mPackages) {
6398            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6399            if (obj instanceof SharedUserSetting) {
6400                final SharedUserSetting sus = (SharedUserSetting) obj;
6401                return sus.pkgFlags;
6402            } else if (obj instanceof PackageSetting) {
6403                final PackageSetting ps = (PackageSetting) obj;
6404                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6405                    return 0;
6406                }
6407                return ps.pkgFlags;
6408            }
6409        }
6410        return 0;
6411    }
6412
6413    @Override
6414    public int getPrivateFlagsForUid(int uid) {
6415        final int callingUid = Binder.getCallingUid();
6416        if (getInstantAppPackageName(callingUid) != null) {
6417            return 0;
6418        }
6419        synchronized (mPackages) {
6420            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6421            if (obj instanceof SharedUserSetting) {
6422                final SharedUserSetting sus = (SharedUserSetting) obj;
6423                return sus.pkgPrivateFlags;
6424            } else if (obj instanceof PackageSetting) {
6425                final PackageSetting ps = (PackageSetting) obj;
6426                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6427                    return 0;
6428                }
6429                return ps.pkgPrivateFlags;
6430            }
6431        }
6432        return 0;
6433    }
6434
6435    @Override
6436    public boolean isUidPrivileged(int uid) {
6437        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6438            return false;
6439        }
6440        uid = UserHandle.getAppId(uid);
6441        // reader
6442        synchronized (mPackages) {
6443            Object obj = mSettings.getUserIdLPr(uid);
6444            if (obj instanceof SharedUserSetting) {
6445                final SharedUserSetting sus = (SharedUserSetting) obj;
6446                final Iterator<PackageSetting> it = sus.packages.iterator();
6447                while (it.hasNext()) {
6448                    if (it.next().isPrivileged()) {
6449                        return true;
6450                    }
6451                }
6452            } else if (obj instanceof PackageSetting) {
6453                final PackageSetting ps = (PackageSetting) obj;
6454                return ps.isPrivileged();
6455            }
6456        }
6457        return false;
6458    }
6459
6460    @Override
6461    public String[] getAppOpPermissionPackages(String permissionName) {
6462        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6463            return null;
6464        }
6465        synchronized (mPackages) {
6466            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6467            if (pkgs == null) {
6468                return null;
6469            }
6470            return pkgs.toArray(new String[pkgs.size()]);
6471        }
6472    }
6473
6474    @Override
6475    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6476            int flags, int userId) {
6477        return resolveIntentInternal(
6478                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6479    }
6480
6481    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6482            int flags, int userId, boolean resolveForStart) {
6483        try {
6484            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6485
6486            if (!sUserManager.exists(userId)) return null;
6487            final int callingUid = Binder.getCallingUid();
6488            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6489            enforceCrossUserPermission(callingUid, userId,
6490                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6491
6492            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6493            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6494                    flags, callingUid, userId, resolveForStart);
6495            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6496
6497            final ResolveInfo bestChoice =
6498                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6499            return bestChoice;
6500        } finally {
6501            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6502        }
6503    }
6504
6505    @Override
6506    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6507        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6508            throw new SecurityException(
6509                    "findPersistentPreferredActivity can only be run by the system");
6510        }
6511        if (!sUserManager.exists(userId)) {
6512            return null;
6513        }
6514        final int callingUid = Binder.getCallingUid();
6515        intent = updateIntentForResolve(intent);
6516        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6517        final int flags = updateFlagsForResolve(
6518                0, userId, intent, callingUid, false /*includeInstantApps*/);
6519        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6520                userId);
6521        synchronized (mPackages) {
6522            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6523                    userId);
6524        }
6525    }
6526
6527    @Override
6528    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6529            IntentFilter filter, int match, ComponentName activity) {
6530        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6531            return;
6532        }
6533        final int userId = UserHandle.getCallingUserId();
6534        if (DEBUG_PREFERRED) {
6535            Log.v(TAG, "setLastChosenActivity intent=" + intent
6536                + " resolvedType=" + resolvedType
6537                + " flags=" + flags
6538                + " filter=" + filter
6539                + " match=" + match
6540                + " activity=" + activity);
6541            filter.dump(new PrintStreamPrinter(System.out), "    ");
6542        }
6543        intent.setComponent(null);
6544        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6545                userId);
6546        // Find any earlier preferred or last chosen entries and nuke them
6547        findPreferredActivity(intent, resolvedType,
6548                flags, query, 0, false, true, false, userId);
6549        // Add the new activity as the last chosen for this filter
6550        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6551                "Setting last chosen");
6552    }
6553
6554    @Override
6555    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6556        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6557            return null;
6558        }
6559        final int userId = UserHandle.getCallingUserId();
6560        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6561        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6562                userId);
6563        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6564                false, false, false, userId);
6565    }
6566
6567    /**
6568     * Returns whether or not instant apps have been disabled remotely.
6569     */
6570    private boolean isEphemeralDisabled() {
6571        return mEphemeralAppsDisabled;
6572    }
6573
6574    private boolean isInstantAppAllowed(
6575            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6576            boolean skipPackageCheck) {
6577        if (mInstantAppResolverConnection == null) {
6578            return false;
6579        }
6580        if (mInstantAppInstallerActivity == null) {
6581            return false;
6582        }
6583        if (intent.getComponent() != null) {
6584            return false;
6585        }
6586        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6587            return false;
6588        }
6589        if (!skipPackageCheck && intent.getPackage() != null) {
6590            return false;
6591        }
6592        final boolean isWebUri = hasWebURI(intent);
6593        if (!isWebUri || intent.getData().getHost() == null) {
6594            return false;
6595        }
6596        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6597        // Or if there's already an ephemeral app installed that handles the action
6598        synchronized (mPackages) {
6599            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6600            for (int n = 0; n < count; n++) {
6601                final ResolveInfo info = resolvedActivities.get(n);
6602                final String packageName = info.activityInfo.packageName;
6603                final PackageSetting ps = mSettings.mPackages.get(packageName);
6604                if (ps != null) {
6605                    // only check domain verification status if the app is not a browser
6606                    if (!info.handleAllWebDataURI) {
6607                        // Try to get the status from User settings first
6608                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6609                        final int status = (int) (packedStatus >> 32);
6610                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6611                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6612                            if (DEBUG_EPHEMERAL) {
6613                                Slog.v(TAG, "DENY instant app;"
6614                                    + " pkg: " + packageName + ", status: " + status);
6615                            }
6616                            return false;
6617                        }
6618                    }
6619                    if (ps.getInstantApp(userId)) {
6620                        if (DEBUG_EPHEMERAL) {
6621                            Slog.v(TAG, "DENY instant app installed;"
6622                                    + " pkg: " + packageName);
6623                        }
6624                        return false;
6625                    }
6626                }
6627            }
6628        }
6629        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6630        return true;
6631    }
6632
6633    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6634            Intent origIntent, String resolvedType, String callingPackage,
6635            Bundle verificationBundle, int userId) {
6636        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6637                new InstantAppRequest(responseObj, origIntent, resolvedType,
6638                        callingPackage, userId, verificationBundle));
6639        mHandler.sendMessage(msg);
6640    }
6641
6642    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6643            int flags, List<ResolveInfo> query, int userId) {
6644        if (query != null) {
6645            final int N = query.size();
6646            if (N == 1) {
6647                return query.get(0);
6648            } else if (N > 1) {
6649                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6650                // If there is more than one activity with the same priority,
6651                // then let the user decide between them.
6652                ResolveInfo r0 = query.get(0);
6653                ResolveInfo r1 = query.get(1);
6654                if (DEBUG_INTENT_MATCHING || debug) {
6655                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6656                            + r1.activityInfo.name + "=" + r1.priority);
6657                }
6658                // If the first activity has a higher priority, or a different
6659                // default, then it is always desirable to pick it.
6660                if (r0.priority != r1.priority
6661                        || r0.preferredOrder != r1.preferredOrder
6662                        || r0.isDefault != r1.isDefault) {
6663                    return query.get(0);
6664                }
6665                // If we have saved a preference for a preferred activity for
6666                // this Intent, use that.
6667                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6668                        flags, query, r0.priority, true, false, debug, userId);
6669                if (ri != null) {
6670                    return ri;
6671                }
6672                // If we have an ephemeral app, use it
6673                for (int i = 0; i < N; i++) {
6674                    ri = query.get(i);
6675                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6676                        final String packageName = ri.activityInfo.packageName;
6677                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6678                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6679                        final int status = (int)(packedStatus >> 32);
6680                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6681                            return ri;
6682                        }
6683                    }
6684                }
6685                ri = new ResolveInfo(mResolveInfo);
6686                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6687                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6688                // If all of the options come from the same package, show the application's
6689                // label and icon instead of the generic resolver's.
6690                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6691                // and then throw away the ResolveInfo itself, meaning that the caller loses
6692                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6693                // a fallback for this case; we only set the target package's resources on
6694                // the ResolveInfo, not the ActivityInfo.
6695                final String intentPackage = intent.getPackage();
6696                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6697                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6698                    ri.resolvePackageName = intentPackage;
6699                    if (userNeedsBadging(userId)) {
6700                        ri.noResourceId = true;
6701                    } else {
6702                        ri.icon = appi.icon;
6703                    }
6704                    ri.iconResourceId = appi.icon;
6705                    ri.labelRes = appi.labelRes;
6706                }
6707                ri.activityInfo.applicationInfo = new ApplicationInfo(
6708                        ri.activityInfo.applicationInfo);
6709                if (userId != 0) {
6710                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6711                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6712                }
6713                // Make sure that the resolver is displayable in car mode
6714                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6715                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6716                return ri;
6717            }
6718        }
6719        return null;
6720    }
6721
6722    /**
6723     * Return true if the given list is not empty and all of its contents have
6724     * an activityInfo with the given package name.
6725     */
6726    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6727        if (ArrayUtils.isEmpty(list)) {
6728            return false;
6729        }
6730        for (int i = 0, N = list.size(); i < N; i++) {
6731            final ResolveInfo ri = list.get(i);
6732            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6733            if (ai == null || !packageName.equals(ai.packageName)) {
6734                return false;
6735            }
6736        }
6737        return true;
6738    }
6739
6740    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6741            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6742        final int N = query.size();
6743        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6744                .get(userId);
6745        // Get the list of persistent preferred activities that handle the intent
6746        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6747        List<PersistentPreferredActivity> pprefs = ppir != null
6748                ? ppir.queryIntent(intent, resolvedType,
6749                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6750                        userId)
6751                : null;
6752        if (pprefs != null && pprefs.size() > 0) {
6753            final int M = pprefs.size();
6754            for (int i=0; i<M; i++) {
6755                final PersistentPreferredActivity ppa = pprefs.get(i);
6756                if (DEBUG_PREFERRED || debug) {
6757                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6758                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6759                            + "\n  component=" + ppa.mComponent);
6760                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6761                }
6762                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6763                        flags | MATCH_DISABLED_COMPONENTS, userId);
6764                if (DEBUG_PREFERRED || debug) {
6765                    Slog.v(TAG, "Found persistent preferred activity:");
6766                    if (ai != null) {
6767                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6768                    } else {
6769                        Slog.v(TAG, "  null");
6770                    }
6771                }
6772                if (ai == null) {
6773                    // This previously registered persistent preferred activity
6774                    // component is no longer known. Ignore it and do NOT remove it.
6775                    continue;
6776                }
6777                for (int j=0; j<N; j++) {
6778                    final ResolveInfo ri = query.get(j);
6779                    if (!ri.activityInfo.applicationInfo.packageName
6780                            .equals(ai.applicationInfo.packageName)) {
6781                        continue;
6782                    }
6783                    if (!ri.activityInfo.name.equals(ai.name)) {
6784                        continue;
6785                    }
6786                    //  Found a persistent preference that can handle the intent.
6787                    if (DEBUG_PREFERRED || debug) {
6788                        Slog.v(TAG, "Returning persistent preferred activity: " +
6789                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6790                    }
6791                    return ri;
6792                }
6793            }
6794        }
6795        return null;
6796    }
6797
6798    // TODO: handle preferred activities missing while user has amnesia
6799    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6800            List<ResolveInfo> query, int priority, boolean always,
6801            boolean removeMatches, boolean debug, int userId) {
6802        if (!sUserManager.exists(userId)) return null;
6803        final int callingUid = Binder.getCallingUid();
6804        flags = updateFlagsForResolve(
6805                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6806        intent = updateIntentForResolve(intent);
6807        // writer
6808        synchronized (mPackages) {
6809            // Try to find a matching persistent preferred activity.
6810            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6811                    debug, userId);
6812
6813            // If a persistent preferred activity matched, use it.
6814            if (pri != null) {
6815                return pri;
6816            }
6817
6818            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6819            // Get the list of preferred activities that handle the intent
6820            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6821            List<PreferredActivity> prefs = pir != null
6822                    ? pir.queryIntent(intent, resolvedType,
6823                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6824                            userId)
6825                    : null;
6826            if (prefs != null && prefs.size() > 0) {
6827                boolean changed = false;
6828                try {
6829                    // First figure out how good the original match set is.
6830                    // We will only allow preferred activities that came
6831                    // from the same match quality.
6832                    int match = 0;
6833
6834                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6835
6836                    final int N = query.size();
6837                    for (int j=0; j<N; j++) {
6838                        final ResolveInfo ri = query.get(j);
6839                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6840                                + ": 0x" + Integer.toHexString(match));
6841                        if (ri.match > match) {
6842                            match = ri.match;
6843                        }
6844                    }
6845
6846                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6847                            + Integer.toHexString(match));
6848
6849                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6850                    final int M = prefs.size();
6851                    for (int i=0; i<M; i++) {
6852                        final PreferredActivity pa = prefs.get(i);
6853                        if (DEBUG_PREFERRED || debug) {
6854                            Slog.v(TAG, "Checking PreferredActivity ds="
6855                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6856                                    + "\n  component=" + pa.mPref.mComponent);
6857                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6858                        }
6859                        if (pa.mPref.mMatch != match) {
6860                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6861                                    + Integer.toHexString(pa.mPref.mMatch));
6862                            continue;
6863                        }
6864                        // If it's not an "always" type preferred activity and that's what we're
6865                        // looking for, skip it.
6866                        if (always && !pa.mPref.mAlways) {
6867                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6868                            continue;
6869                        }
6870                        final ActivityInfo ai = getActivityInfo(
6871                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6872                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6873                                userId);
6874                        if (DEBUG_PREFERRED || debug) {
6875                            Slog.v(TAG, "Found preferred activity:");
6876                            if (ai != null) {
6877                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6878                            } else {
6879                                Slog.v(TAG, "  null");
6880                            }
6881                        }
6882                        if (ai == null) {
6883                            // This previously registered preferred activity
6884                            // component is no longer known.  Most likely an update
6885                            // to the app was installed and in the new version this
6886                            // component no longer exists.  Clean it up by removing
6887                            // it from the preferred activities list, and skip it.
6888                            Slog.w(TAG, "Removing dangling preferred activity: "
6889                                    + pa.mPref.mComponent);
6890                            pir.removeFilter(pa);
6891                            changed = true;
6892                            continue;
6893                        }
6894                        for (int j=0; j<N; j++) {
6895                            final ResolveInfo ri = query.get(j);
6896                            if (!ri.activityInfo.applicationInfo.packageName
6897                                    .equals(ai.applicationInfo.packageName)) {
6898                                continue;
6899                            }
6900                            if (!ri.activityInfo.name.equals(ai.name)) {
6901                                continue;
6902                            }
6903
6904                            if (removeMatches) {
6905                                pir.removeFilter(pa);
6906                                changed = true;
6907                                if (DEBUG_PREFERRED) {
6908                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6909                                }
6910                                break;
6911                            }
6912
6913                            // Okay we found a previously set preferred or last chosen app.
6914                            // If the result set is different from when this
6915                            // was created, we need to clear it and re-ask the
6916                            // user their preference, if we're looking for an "always" type entry.
6917                            if (always && !pa.mPref.sameSet(query)) {
6918                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6919                                        + intent + " type " + resolvedType);
6920                                if (DEBUG_PREFERRED) {
6921                                    Slog.v(TAG, "Removing preferred activity since set changed "
6922                                            + pa.mPref.mComponent);
6923                                }
6924                                pir.removeFilter(pa);
6925                                // Re-add the filter as a "last chosen" entry (!always)
6926                                PreferredActivity lastChosen = new PreferredActivity(
6927                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6928                                pir.addFilter(lastChosen);
6929                                changed = true;
6930                                return null;
6931                            }
6932
6933                            // Yay! Either the set matched or we're looking for the last chosen
6934                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6935                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6936                            return ri;
6937                        }
6938                    }
6939                } finally {
6940                    if (changed) {
6941                        if (DEBUG_PREFERRED) {
6942                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6943                        }
6944                        scheduleWritePackageRestrictionsLocked(userId);
6945                    }
6946                }
6947            }
6948        }
6949        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6950        return null;
6951    }
6952
6953    /*
6954     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6955     */
6956    @Override
6957    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6958            int targetUserId) {
6959        mContext.enforceCallingOrSelfPermission(
6960                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6961        List<CrossProfileIntentFilter> matches =
6962                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6963        if (matches != null) {
6964            int size = matches.size();
6965            for (int i = 0; i < size; i++) {
6966                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6967            }
6968        }
6969        if (hasWebURI(intent)) {
6970            // cross-profile app linking works only towards the parent.
6971            final int callingUid = Binder.getCallingUid();
6972            final UserInfo parent = getProfileParent(sourceUserId);
6973            synchronized(mPackages) {
6974                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6975                        false /*includeInstantApps*/);
6976                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6977                        intent, resolvedType, flags, sourceUserId, parent.id);
6978                return xpDomainInfo != null;
6979            }
6980        }
6981        return false;
6982    }
6983
6984    private UserInfo getProfileParent(int userId) {
6985        final long identity = Binder.clearCallingIdentity();
6986        try {
6987            return sUserManager.getProfileParent(userId);
6988        } finally {
6989            Binder.restoreCallingIdentity(identity);
6990        }
6991    }
6992
6993    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6994            String resolvedType, int userId) {
6995        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6996        if (resolver != null) {
6997            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6998        }
6999        return null;
7000    }
7001
7002    @Override
7003    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7004            String resolvedType, int flags, int userId) {
7005        try {
7006            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7007
7008            return new ParceledListSlice<>(
7009                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7010        } finally {
7011            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7012        }
7013    }
7014
7015    /**
7016     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7017     * instant, returns {@code null}.
7018     */
7019    private String getInstantAppPackageName(int callingUid) {
7020        synchronized (mPackages) {
7021            // If the caller is an isolated app use the owner's uid for the lookup.
7022            if (Process.isIsolated(callingUid)) {
7023                callingUid = mIsolatedOwners.get(callingUid);
7024            }
7025            final int appId = UserHandle.getAppId(callingUid);
7026            final Object obj = mSettings.getUserIdLPr(appId);
7027            if (obj instanceof PackageSetting) {
7028                final PackageSetting ps = (PackageSetting) obj;
7029                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7030                return isInstantApp ? ps.pkg.packageName : null;
7031            }
7032        }
7033        return null;
7034    }
7035
7036    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7037            String resolvedType, int flags, int userId) {
7038        return queryIntentActivitiesInternal(
7039                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
7040    }
7041
7042    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7043            String resolvedType, int flags, int filterCallingUid, int userId,
7044            boolean resolveForStart) {
7045        if (!sUserManager.exists(userId)) return Collections.emptyList();
7046        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7047        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7048                false /* requireFullPermission */, false /* checkShell */,
7049                "query intent activities");
7050        final String pkgName = intent.getPackage();
7051        ComponentName comp = intent.getComponent();
7052        if (comp == null) {
7053            if (intent.getSelector() != null) {
7054                intent = intent.getSelector();
7055                comp = intent.getComponent();
7056            }
7057        }
7058
7059        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7060                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7061        if (comp != null) {
7062            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7063            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7064            if (ai != null) {
7065                // When specifying an explicit component, we prevent the activity from being
7066                // used when either 1) the calling package is normal and the activity is within
7067                // an ephemeral application or 2) the calling package is ephemeral and the
7068                // activity is not visible to ephemeral applications.
7069                final boolean matchInstantApp =
7070                        (flags & PackageManager.MATCH_INSTANT) != 0;
7071                final boolean matchVisibleToInstantAppOnly =
7072                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7073                final boolean matchExplicitlyVisibleOnly =
7074                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7075                final boolean isCallerInstantApp =
7076                        instantAppPkgName != null;
7077                final boolean isTargetSameInstantApp =
7078                        comp.getPackageName().equals(instantAppPkgName);
7079                final boolean isTargetInstantApp =
7080                        (ai.applicationInfo.privateFlags
7081                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7082                final boolean isTargetVisibleToInstantApp =
7083                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7084                final boolean isTargetExplicitlyVisibleToInstantApp =
7085                        isTargetVisibleToInstantApp
7086                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7087                final boolean isTargetHiddenFromInstantApp =
7088                        !isTargetVisibleToInstantApp
7089                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7090                final boolean blockResolution =
7091                        !isTargetSameInstantApp
7092                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7093                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7094                                        && isTargetHiddenFromInstantApp));
7095                if (!blockResolution) {
7096                    final ResolveInfo ri = new ResolveInfo();
7097                    ri.activityInfo = ai;
7098                    list.add(ri);
7099                }
7100            }
7101            return applyPostResolutionFilter(list, instantAppPkgName);
7102        }
7103
7104        // reader
7105        boolean sortResult = false;
7106        boolean addEphemeral = false;
7107        List<ResolveInfo> result;
7108        final boolean ephemeralDisabled = isEphemeralDisabled();
7109        synchronized (mPackages) {
7110            if (pkgName == null) {
7111                List<CrossProfileIntentFilter> matchingFilters =
7112                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7113                // Check for results that need to skip the current profile.
7114                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7115                        resolvedType, flags, userId);
7116                if (xpResolveInfo != null) {
7117                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7118                    xpResult.add(xpResolveInfo);
7119                    return applyPostResolutionFilter(
7120                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
7121                }
7122
7123                // Check for results in the current profile.
7124                result = filterIfNotSystemUser(mActivities.queryIntent(
7125                        intent, resolvedType, flags, userId), userId);
7126                addEphemeral = !ephemeralDisabled
7127                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7128                // Check for cross profile results.
7129                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7130                xpResolveInfo = queryCrossProfileIntents(
7131                        matchingFilters, intent, resolvedType, flags, userId,
7132                        hasNonNegativePriorityResult);
7133                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7134                    boolean isVisibleToUser = filterIfNotSystemUser(
7135                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7136                    if (isVisibleToUser) {
7137                        result.add(xpResolveInfo);
7138                        sortResult = true;
7139                    }
7140                }
7141                if (hasWebURI(intent)) {
7142                    CrossProfileDomainInfo xpDomainInfo = null;
7143                    final UserInfo parent = getProfileParent(userId);
7144                    if (parent != null) {
7145                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7146                                flags, userId, parent.id);
7147                    }
7148                    if (xpDomainInfo != null) {
7149                        if (xpResolveInfo != null) {
7150                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7151                            // in the result.
7152                            result.remove(xpResolveInfo);
7153                        }
7154                        if (result.size() == 0 && !addEphemeral) {
7155                            // No result in current profile, but found candidate in parent user.
7156                            // And we are not going to add emphemeral app, so we can return the
7157                            // result straight away.
7158                            result.add(xpDomainInfo.resolveInfo);
7159                            return applyPostResolutionFilter(result, instantAppPkgName);
7160                        }
7161                    } else if (result.size() <= 1 && !addEphemeral) {
7162                        // No result in parent user and <= 1 result in current profile, and we
7163                        // are not going to add emphemeral app, so we can return the result without
7164                        // further processing.
7165                        return applyPostResolutionFilter(result, instantAppPkgName);
7166                    }
7167                    // We have more than one candidate (combining results from current and parent
7168                    // profile), so we need filtering and sorting.
7169                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7170                            intent, flags, result, xpDomainInfo, userId);
7171                    sortResult = true;
7172                }
7173            } else {
7174                final PackageParser.Package pkg = mPackages.get(pkgName);
7175                result = null;
7176                if (pkg != null) {
7177                    result = filterIfNotSystemUser(
7178                            mActivities.queryIntentForPackage(
7179                                    intent, resolvedType, flags, pkg.activities, userId),
7180                            userId);
7181                }
7182                if (result == null || result.size() == 0) {
7183                    // the caller wants to resolve for a particular package; however, there
7184                    // were no installed results, so, try to find an ephemeral result
7185                    addEphemeral = !ephemeralDisabled
7186                            && isInstantAppAllowed(
7187                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7188                    if (result == null) {
7189                        result = new ArrayList<>();
7190                    }
7191                }
7192            }
7193        }
7194        if (addEphemeral) {
7195            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7196        }
7197        if (sortResult) {
7198            Collections.sort(result, mResolvePrioritySorter);
7199        }
7200        return applyPostResolutionFilter(result, instantAppPkgName);
7201    }
7202
7203    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7204            String resolvedType, int flags, int userId) {
7205        // first, check to see if we've got an instant app already installed
7206        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7207        ResolveInfo localInstantApp = null;
7208        boolean blockResolution = false;
7209        if (!alreadyResolvedLocally) {
7210            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7211                    flags
7212                        | PackageManager.GET_RESOLVED_FILTER
7213                        | PackageManager.MATCH_INSTANT
7214                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7215                    userId);
7216            for (int i = instantApps.size() - 1; i >= 0; --i) {
7217                final ResolveInfo info = instantApps.get(i);
7218                final String packageName = info.activityInfo.packageName;
7219                final PackageSetting ps = mSettings.mPackages.get(packageName);
7220                if (ps.getInstantApp(userId)) {
7221                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7222                    final int status = (int)(packedStatus >> 32);
7223                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7224                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7225                        // there's a local instant application installed, but, the user has
7226                        // chosen to never use it; skip resolution and don't acknowledge
7227                        // an instant application is even available
7228                        if (DEBUG_EPHEMERAL) {
7229                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7230                        }
7231                        blockResolution = true;
7232                        break;
7233                    } else {
7234                        // we have a locally installed instant application; skip resolution
7235                        // but acknowledge there's an instant application available
7236                        if (DEBUG_EPHEMERAL) {
7237                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7238                        }
7239                        localInstantApp = info;
7240                        break;
7241                    }
7242                }
7243            }
7244        }
7245        // no app installed, let's see if one's available
7246        AuxiliaryResolveInfo auxiliaryResponse = null;
7247        if (!blockResolution) {
7248            if (localInstantApp == null) {
7249                // we don't have an instant app locally, resolve externally
7250                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7251                final InstantAppRequest requestObject = new InstantAppRequest(
7252                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7253                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7254                auxiliaryResponse =
7255                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7256                                mContext, mInstantAppResolverConnection, requestObject);
7257                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7258            } else {
7259                // we have an instant application locally, but, we can't admit that since
7260                // callers shouldn't be able to determine prior browsing. create a dummy
7261                // auxiliary response so the downstream code behaves as if there's an
7262                // instant application available externally. when it comes time to start
7263                // the instant application, we'll do the right thing.
7264                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7265                auxiliaryResponse = new AuxiliaryResolveInfo(
7266                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7267            }
7268        }
7269        if (auxiliaryResponse != null) {
7270            if (DEBUG_EPHEMERAL) {
7271                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7272            }
7273            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7274            final PackageSetting ps =
7275                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7276            if (ps != null) {
7277                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7278                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7279                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7280                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7281                // make sure this resolver is the default
7282                ephemeralInstaller.isDefault = true;
7283                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7284                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7285                // add a non-generic filter
7286                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7287                ephemeralInstaller.filter.addDataPath(
7288                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7289                ephemeralInstaller.isInstantAppAvailable = true;
7290                result.add(ephemeralInstaller);
7291            }
7292        }
7293        return result;
7294    }
7295
7296    private static class CrossProfileDomainInfo {
7297        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7298        ResolveInfo resolveInfo;
7299        /* Best domain verification status of the activities found in the other profile */
7300        int bestDomainVerificationStatus;
7301    }
7302
7303    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7304            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7305        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7306                sourceUserId)) {
7307            return null;
7308        }
7309        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7310                resolvedType, flags, parentUserId);
7311
7312        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7313            return null;
7314        }
7315        CrossProfileDomainInfo result = null;
7316        int size = resultTargetUser.size();
7317        for (int i = 0; i < size; i++) {
7318            ResolveInfo riTargetUser = resultTargetUser.get(i);
7319            // Intent filter verification is only for filters that specify a host. So don't return
7320            // those that handle all web uris.
7321            if (riTargetUser.handleAllWebDataURI) {
7322                continue;
7323            }
7324            String packageName = riTargetUser.activityInfo.packageName;
7325            PackageSetting ps = mSettings.mPackages.get(packageName);
7326            if (ps == null) {
7327                continue;
7328            }
7329            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7330            int status = (int)(verificationState >> 32);
7331            if (result == null) {
7332                result = new CrossProfileDomainInfo();
7333                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7334                        sourceUserId, parentUserId);
7335                result.bestDomainVerificationStatus = status;
7336            } else {
7337                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7338                        result.bestDomainVerificationStatus);
7339            }
7340        }
7341        // Don't consider matches with status NEVER across profiles.
7342        if (result != null && result.bestDomainVerificationStatus
7343                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7344            return null;
7345        }
7346        return result;
7347    }
7348
7349    /**
7350     * Verification statuses are ordered from the worse to the best, except for
7351     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7352     */
7353    private int bestDomainVerificationStatus(int status1, int status2) {
7354        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7355            return status2;
7356        }
7357        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7358            return status1;
7359        }
7360        return (int) MathUtils.max(status1, status2);
7361    }
7362
7363    private boolean isUserEnabled(int userId) {
7364        long callingId = Binder.clearCallingIdentity();
7365        try {
7366            UserInfo userInfo = sUserManager.getUserInfo(userId);
7367            return userInfo != null && userInfo.isEnabled();
7368        } finally {
7369            Binder.restoreCallingIdentity(callingId);
7370        }
7371    }
7372
7373    /**
7374     * Filter out activities with systemUserOnly flag set, when current user is not System.
7375     *
7376     * @return filtered list
7377     */
7378    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7379        if (userId == UserHandle.USER_SYSTEM) {
7380            return resolveInfos;
7381        }
7382        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7383            ResolveInfo info = resolveInfos.get(i);
7384            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7385                resolveInfos.remove(i);
7386            }
7387        }
7388        return resolveInfos;
7389    }
7390
7391    /**
7392     * Filters out ephemeral activities.
7393     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7394     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7395     *
7396     * @param resolveInfos The pre-filtered list of resolved activities
7397     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7398     *          is performed.
7399     * @return A filtered list of resolved activities.
7400     */
7401    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7402            String ephemeralPkgName) {
7403        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7404            final ResolveInfo info = resolveInfos.get(i);
7405            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7406            // TODO: When adding on-demand split support for non-instant apps, remove this check
7407            // and always apply post filtering
7408            // allow activities that are defined in the provided package
7409            if (isEphemeralApp) {
7410                if (info.activityInfo.splitName != null
7411                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7412                                info.activityInfo.splitName)) {
7413                    // requested activity is defined in a split that hasn't been installed yet.
7414                    // add the installer to the resolve list
7415                    if (DEBUG_EPHEMERAL) {
7416                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7417                    }
7418                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7419                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7420                            info.activityInfo.packageName, info.activityInfo.splitName,
7421                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7422                    // make sure this resolver is the default
7423                    installerInfo.isDefault = true;
7424                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7425                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7426                    // add a non-generic filter
7427                    installerInfo.filter = new IntentFilter();
7428                    // load resources from the correct package
7429                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7430                    resolveInfos.set(i, installerInfo);
7431                    continue;
7432                }
7433            }
7434            // caller is a full app, don't need to apply any other filtering
7435            if (ephemeralPkgName == null) {
7436                continue;
7437            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7438                // caller is same app; don't need to apply any other filtering
7439                continue;
7440            }
7441            // allow activities that have been explicitly exposed to ephemeral apps
7442            if (!isEphemeralApp
7443                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7444                continue;
7445            }
7446            resolveInfos.remove(i);
7447        }
7448        return resolveInfos;
7449    }
7450
7451    /**
7452     * @param resolveInfos list of resolve infos in descending priority order
7453     * @return if the list contains a resolve info with non-negative priority
7454     */
7455    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7456        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7457    }
7458
7459    private static boolean hasWebURI(Intent intent) {
7460        if (intent.getData() == null) {
7461            return false;
7462        }
7463        final String scheme = intent.getScheme();
7464        if (TextUtils.isEmpty(scheme)) {
7465            return false;
7466        }
7467        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7468    }
7469
7470    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7471            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7472            int userId) {
7473        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7474
7475        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7476            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7477                    candidates.size());
7478        }
7479
7480        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7481        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7482        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7483        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7484        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7485        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7486
7487        synchronized (mPackages) {
7488            final int count = candidates.size();
7489            // First, try to use linked apps. Partition the candidates into four lists:
7490            // one for the final results, one for the "do not use ever", one for "undefined status"
7491            // and finally one for "browser app type".
7492            for (int n=0; n<count; n++) {
7493                ResolveInfo info = candidates.get(n);
7494                String packageName = info.activityInfo.packageName;
7495                PackageSetting ps = mSettings.mPackages.get(packageName);
7496                if (ps != null) {
7497                    // Add to the special match all list (Browser use case)
7498                    if (info.handleAllWebDataURI) {
7499                        matchAllList.add(info);
7500                        continue;
7501                    }
7502                    // Try to get the status from User settings first
7503                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7504                    int status = (int)(packedStatus >> 32);
7505                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7506                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7507                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7508                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7509                                    + " : linkgen=" + linkGeneration);
7510                        }
7511                        // Use link-enabled generation as preferredOrder, i.e.
7512                        // prefer newly-enabled over earlier-enabled.
7513                        info.preferredOrder = linkGeneration;
7514                        alwaysList.add(info);
7515                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7516                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7517                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7518                        }
7519                        neverList.add(info);
7520                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7521                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7522                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7523                        }
7524                        alwaysAskList.add(info);
7525                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7526                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7527                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7528                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7529                        }
7530                        undefinedList.add(info);
7531                    }
7532                }
7533            }
7534
7535            // We'll want to include browser possibilities in a few cases
7536            boolean includeBrowser = false;
7537
7538            // First try to add the "always" resolution(s) for the current user, if any
7539            if (alwaysList.size() > 0) {
7540                result.addAll(alwaysList);
7541            } else {
7542                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7543                result.addAll(undefinedList);
7544                // Maybe add one for the other profile.
7545                if (xpDomainInfo != null && (
7546                        xpDomainInfo.bestDomainVerificationStatus
7547                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7548                    result.add(xpDomainInfo.resolveInfo);
7549                }
7550                includeBrowser = true;
7551            }
7552
7553            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7554            // If there were 'always' entries their preferred order has been set, so we also
7555            // back that off to make the alternatives equivalent
7556            if (alwaysAskList.size() > 0) {
7557                for (ResolveInfo i : result) {
7558                    i.preferredOrder = 0;
7559                }
7560                result.addAll(alwaysAskList);
7561                includeBrowser = true;
7562            }
7563
7564            if (includeBrowser) {
7565                // Also add browsers (all of them or only the default one)
7566                if (DEBUG_DOMAIN_VERIFICATION) {
7567                    Slog.v(TAG, "   ...including browsers in candidate set");
7568                }
7569                if ((matchFlags & MATCH_ALL) != 0) {
7570                    result.addAll(matchAllList);
7571                } else {
7572                    // Browser/generic handling case.  If there's a default browser, go straight
7573                    // to that (but only if there is no other higher-priority match).
7574                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7575                    int maxMatchPrio = 0;
7576                    ResolveInfo defaultBrowserMatch = null;
7577                    final int numCandidates = matchAllList.size();
7578                    for (int n = 0; n < numCandidates; n++) {
7579                        ResolveInfo info = matchAllList.get(n);
7580                        // track the highest overall match priority...
7581                        if (info.priority > maxMatchPrio) {
7582                            maxMatchPrio = info.priority;
7583                        }
7584                        // ...and the highest-priority default browser match
7585                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7586                            if (defaultBrowserMatch == null
7587                                    || (defaultBrowserMatch.priority < info.priority)) {
7588                                if (debug) {
7589                                    Slog.v(TAG, "Considering default browser match " + info);
7590                                }
7591                                defaultBrowserMatch = info;
7592                            }
7593                        }
7594                    }
7595                    if (defaultBrowserMatch != null
7596                            && defaultBrowserMatch.priority >= maxMatchPrio
7597                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7598                    {
7599                        if (debug) {
7600                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7601                        }
7602                        result.add(defaultBrowserMatch);
7603                    } else {
7604                        result.addAll(matchAllList);
7605                    }
7606                }
7607
7608                // If there is nothing selected, add all candidates and remove the ones that the user
7609                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7610                if (result.size() == 0) {
7611                    result.addAll(candidates);
7612                    result.removeAll(neverList);
7613                }
7614            }
7615        }
7616        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7617            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7618                    result.size());
7619            for (ResolveInfo info : result) {
7620                Slog.v(TAG, "  + " + info.activityInfo);
7621            }
7622        }
7623        return result;
7624    }
7625
7626    // Returns a packed value as a long:
7627    //
7628    // high 'int'-sized word: link status: undefined/ask/never/always.
7629    // low 'int'-sized word: relative priority among 'always' results.
7630    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7631        long result = ps.getDomainVerificationStatusForUser(userId);
7632        // if none available, get the master status
7633        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7634            if (ps.getIntentFilterVerificationInfo() != null) {
7635                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7636            }
7637        }
7638        return result;
7639    }
7640
7641    private ResolveInfo querySkipCurrentProfileIntents(
7642            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7643            int flags, int sourceUserId) {
7644        if (matchingFilters != null) {
7645            int size = matchingFilters.size();
7646            for (int i = 0; i < size; i ++) {
7647                CrossProfileIntentFilter filter = matchingFilters.get(i);
7648                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7649                    // Checking if there are activities in the target user that can handle the
7650                    // intent.
7651                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7652                            resolvedType, flags, sourceUserId);
7653                    if (resolveInfo != null) {
7654                        return resolveInfo;
7655                    }
7656                }
7657            }
7658        }
7659        return null;
7660    }
7661
7662    // Return matching ResolveInfo in target user if any.
7663    private ResolveInfo queryCrossProfileIntents(
7664            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7665            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7666        if (matchingFilters != null) {
7667            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7668            // match the same intent. For performance reasons, it is better not to
7669            // run queryIntent twice for the same userId
7670            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7671            int size = matchingFilters.size();
7672            for (int i = 0; i < size; i++) {
7673                CrossProfileIntentFilter filter = matchingFilters.get(i);
7674                int targetUserId = filter.getTargetUserId();
7675                boolean skipCurrentProfile =
7676                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7677                boolean skipCurrentProfileIfNoMatchFound =
7678                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7679                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7680                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7681                    // Checking if there are activities in the target user that can handle the
7682                    // intent.
7683                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7684                            resolvedType, flags, sourceUserId);
7685                    if (resolveInfo != null) return resolveInfo;
7686                    alreadyTriedUserIds.put(targetUserId, true);
7687                }
7688            }
7689        }
7690        return null;
7691    }
7692
7693    /**
7694     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7695     * will forward the intent to the filter's target user.
7696     * Otherwise, returns null.
7697     */
7698    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7699            String resolvedType, int flags, int sourceUserId) {
7700        int targetUserId = filter.getTargetUserId();
7701        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7702                resolvedType, flags, targetUserId);
7703        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7704            // If all the matches in the target profile are suspended, return null.
7705            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7706                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7707                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7708                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7709                            targetUserId);
7710                }
7711            }
7712        }
7713        return null;
7714    }
7715
7716    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7717            int sourceUserId, int targetUserId) {
7718        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7719        long ident = Binder.clearCallingIdentity();
7720        boolean targetIsProfile;
7721        try {
7722            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7723        } finally {
7724            Binder.restoreCallingIdentity(ident);
7725        }
7726        String className;
7727        if (targetIsProfile) {
7728            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7729        } else {
7730            className = FORWARD_INTENT_TO_PARENT;
7731        }
7732        ComponentName forwardingActivityComponentName = new ComponentName(
7733                mAndroidApplication.packageName, className);
7734        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7735                sourceUserId);
7736        if (!targetIsProfile) {
7737            forwardingActivityInfo.showUserIcon = targetUserId;
7738            forwardingResolveInfo.noResourceId = true;
7739        }
7740        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7741        forwardingResolveInfo.priority = 0;
7742        forwardingResolveInfo.preferredOrder = 0;
7743        forwardingResolveInfo.match = 0;
7744        forwardingResolveInfo.isDefault = true;
7745        forwardingResolveInfo.filter = filter;
7746        forwardingResolveInfo.targetUserId = targetUserId;
7747        return forwardingResolveInfo;
7748    }
7749
7750    @Override
7751    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7752            Intent[] specifics, String[] specificTypes, Intent intent,
7753            String resolvedType, int flags, int userId) {
7754        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7755                specificTypes, intent, resolvedType, flags, userId));
7756    }
7757
7758    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7759            Intent[] specifics, String[] specificTypes, Intent intent,
7760            String resolvedType, int flags, int userId) {
7761        if (!sUserManager.exists(userId)) return Collections.emptyList();
7762        final int callingUid = Binder.getCallingUid();
7763        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7764                false /*includeInstantApps*/);
7765        enforceCrossUserPermission(callingUid, userId,
7766                false /*requireFullPermission*/, false /*checkShell*/,
7767                "query intent activity options");
7768        final String resultsAction = intent.getAction();
7769
7770        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7771                | PackageManager.GET_RESOLVED_FILTER, userId);
7772
7773        if (DEBUG_INTENT_MATCHING) {
7774            Log.v(TAG, "Query " + intent + ": " + results);
7775        }
7776
7777        int specificsPos = 0;
7778        int N;
7779
7780        // todo: note that the algorithm used here is O(N^2).  This
7781        // isn't a problem in our current environment, but if we start running
7782        // into situations where we have more than 5 or 10 matches then this
7783        // should probably be changed to something smarter...
7784
7785        // First we go through and resolve each of the specific items
7786        // that were supplied, taking care of removing any corresponding
7787        // duplicate items in the generic resolve list.
7788        if (specifics != null) {
7789            for (int i=0; i<specifics.length; i++) {
7790                final Intent sintent = specifics[i];
7791                if (sintent == null) {
7792                    continue;
7793                }
7794
7795                if (DEBUG_INTENT_MATCHING) {
7796                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7797                }
7798
7799                String action = sintent.getAction();
7800                if (resultsAction != null && resultsAction.equals(action)) {
7801                    // If this action was explicitly requested, then don't
7802                    // remove things that have it.
7803                    action = null;
7804                }
7805
7806                ResolveInfo ri = null;
7807                ActivityInfo ai = null;
7808
7809                ComponentName comp = sintent.getComponent();
7810                if (comp == null) {
7811                    ri = resolveIntent(
7812                        sintent,
7813                        specificTypes != null ? specificTypes[i] : null,
7814                            flags, userId);
7815                    if (ri == null) {
7816                        continue;
7817                    }
7818                    if (ri == mResolveInfo) {
7819                        // ACK!  Must do something better with this.
7820                    }
7821                    ai = ri.activityInfo;
7822                    comp = new ComponentName(ai.applicationInfo.packageName,
7823                            ai.name);
7824                } else {
7825                    ai = getActivityInfo(comp, flags, userId);
7826                    if (ai == null) {
7827                        continue;
7828                    }
7829                }
7830
7831                // Look for any generic query activities that are duplicates
7832                // of this specific one, and remove them from the results.
7833                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7834                N = results.size();
7835                int j;
7836                for (j=specificsPos; j<N; j++) {
7837                    ResolveInfo sri = results.get(j);
7838                    if ((sri.activityInfo.name.equals(comp.getClassName())
7839                            && sri.activityInfo.applicationInfo.packageName.equals(
7840                                    comp.getPackageName()))
7841                        || (action != null && sri.filter.matchAction(action))) {
7842                        results.remove(j);
7843                        if (DEBUG_INTENT_MATCHING) Log.v(
7844                            TAG, "Removing duplicate item from " + j
7845                            + " due to specific " + specificsPos);
7846                        if (ri == null) {
7847                            ri = sri;
7848                        }
7849                        j--;
7850                        N--;
7851                    }
7852                }
7853
7854                // Add this specific item to its proper place.
7855                if (ri == null) {
7856                    ri = new ResolveInfo();
7857                    ri.activityInfo = ai;
7858                }
7859                results.add(specificsPos, ri);
7860                ri.specificIndex = i;
7861                specificsPos++;
7862            }
7863        }
7864
7865        // Now we go through the remaining generic results and remove any
7866        // duplicate actions that are found here.
7867        N = results.size();
7868        for (int i=specificsPos; i<N-1; i++) {
7869            final ResolveInfo rii = results.get(i);
7870            if (rii.filter == null) {
7871                continue;
7872            }
7873
7874            // Iterate over all of the actions of this result's intent
7875            // filter...  typically this should be just one.
7876            final Iterator<String> it = rii.filter.actionsIterator();
7877            if (it == null) {
7878                continue;
7879            }
7880            while (it.hasNext()) {
7881                final String action = it.next();
7882                if (resultsAction != null && resultsAction.equals(action)) {
7883                    // If this action was explicitly requested, then don't
7884                    // remove things that have it.
7885                    continue;
7886                }
7887                for (int j=i+1; j<N; j++) {
7888                    final ResolveInfo rij = results.get(j);
7889                    if (rij.filter != null && rij.filter.hasAction(action)) {
7890                        results.remove(j);
7891                        if (DEBUG_INTENT_MATCHING) Log.v(
7892                            TAG, "Removing duplicate item from " + j
7893                            + " due to action " + action + " at " + i);
7894                        j--;
7895                        N--;
7896                    }
7897                }
7898            }
7899
7900            // If the caller didn't request filter information, drop it now
7901            // so we don't have to marshall/unmarshall it.
7902            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7903                rii.filter = null;
7904            }
7905        }
7906
7907        // Filter out the caller activity if so requested.
7908        if (caller != null) {
7909            N = results.size();
7910            for (int i=0; i<N; i++) {
7911                ActivityInfo ainfo = results.get(i).activityInfo;
7912                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7913                        && caller.getClassName().equals(ainfo.name)) {
7914                    results.remove(i);
7915                    break;
7916                }
7917            }
7918        }
7919
7920        // If the caller didn't request filter information,
7921        // drop them now so we don't have to
7922        // marshall/unmarshall it.
7923        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7924            N = results.size();
7925            for (int i=0; i<N; i++) {
7926                results.get(i).filter = null;
7927            }
7928        }
7929
7930        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7931        return results;
7932    }
7933
7934    @Override
7935    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7936            String resolvedType, int flags, int userId) {
7937        return new ParceledListSlice<>(
7938                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7939    }
7940
7941    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7942            String resolvedType, int flags, int userId) {
7943        if (!sUserManager.exists(userId)) return Collections.emptyList();
7944        final int callingUid = Binder.getCallingUid();
7945        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7946        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7947                false /*includeInstantApps*/);
7948        ComponentName comp = intent.getComponent();
7949        if (comp == null) {
7950            if (intent.getSelector() != null) {
7951                intent = intent.getSelector();
7952                comp = intent.getComponent();
7953            }
7954        }
7955        if (comp != null) {
7956            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7957            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7958            if (ai != null) {
7959                // When specifying an explicit component, we prevent the activity from being
7960                // used when either 1) the calling package is normal and the activity is within
7961                // an instant application or 2) the calling package is ephemeral and the
7962                // activity is not visible to instant applications.
7963                final boolean matchInstantApp =
7964                        (flags & PackageManager.MATCH_INSTANT) != 0;
7965                final boolean matchVisibleToInstantAppOnly =
7966                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7967                final boolean matchExplicitlyVisibleOnly =
7968                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7969                final boolean isCallerInstantApp =
7970                        instantAppPkgName != null;
7971                final boolean isTargetSameInstantApp =
7972                        comp.getPackageName().equals(instantAppPkgName);
7973                final boolean isTargetInstantApp =
7974                        (ai.applicationInfo.privateFlags
7975                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7976                final boolean isTargetVisibleToInstantApp =
7977                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7978                final boolean isTargetExplicitlyVisibleToInstantApp =
7979                        isTargetVisibleToInstantApp
7980                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7981                final boolean isTargetHiddenFromInstantApp =
7982                        !isTargetVisibleToInstantApp
7983                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7984                final boolean blockResolution =
7985                        !isTargetSameInstantApp
7986                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7987                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7988                                        && isTargetHiddenFromInstantApp));
7989                if (!blockResolution) {
7990                    ResolveInfo ri = new ResolveInfo();
7991                    ri.activityInfo = ai;
7992                    list.add(ri);
7993                }
7994            }
7995            return applyPostResolutionFilter(list, instantAppPkgName);
7996        }
7997
7998        // reader
7999        synchronized (mPackages) {
8000            String pkgName = intent.getPackage();
8001            if (pkgName == null) {
8002                final List<ResolveInfo> result =
8003                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8004                return applyPostResolutionFilter(result, instantAppPkgName);
8005            }
8006            final PackageParser.Package pkg = mPackages.get(pkgName);
8007            if (pkg != null) {
8008                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8009                        intent, resolvedType, flags, pkg.receivers, userId);
8010                return applyPostResolutionFilter(result, instantAppPkgName);
8011            }
8012            return Collections.emptyList();
8013        }
8014    }
8015
8016    @Override
8017    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8018        final int callingUid = Binder.getCallingUid();
8019        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8020    }
8021
8022    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8023            int userId, int callingUid) {
8024        if (!sUserManager.exists(userId)) return null;
8025        flags = updateFlagsForResolve(
8026                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8027        List<ResolveInfo> query = queryIntentServicesInternal(
8028                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8029        if (query != null) {
8030            if (query.size() >= 1) {
8031                // If there is more than one service with the same priority,
8032                // just arbitrarily pick the first one.
8033                return query.get(0);
8034            }
8035        }
8036        return null;
8037    }
8038
8039    @Override
8040    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8041            String resolvedType, int flags, int userId) {
8042        final int callingUid = Binder.getCallingUid();
8043        return new ParceledListSlice<>(queryIntentServicesInternal(
8044                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8045    }
8046
8047    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8048            String resolvedType, int flags, int userId, int callingUid,
8049            boolean includeInstantApps) {
8050        if (!sUserManager.exists(userId)) return Collections.emptyList();
8051        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8052        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8053        ComponentName comp = intent.getComponent();
8054        if (comp == null) {
8055            if (intent.getSelector() != null) {
8056                intent = intent.getSelector();
8057                comp = intent.getComponent();
8058            }
8059        }
8060        if (comp != null) {
8061            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8062            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8063            if (si != null) {
8064                // When specifying an explicit component, we prevent the service from being
8065                // used when either 1) the service is in an instant application and the
8066                // caller is not the same instant application or 2) the calling package is
8067                // ephemeral and the activity is not visible to ephemeral applications.
8068                final boolean matchInstantApp =
8069                        (flags & PackageManager.MATCH_INSTANT) != 0;
8070                final boolean matchVisibleToInstantAppOnly =
8071                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8072                final boolean isCallerInstantApp =
8073                        instantAppPkgName != null;
8074                final boolean isTargetSameInstantApp =
8075                        comp.getPackageName().equals(instantAppPkgName);
8076                final boolean isTargetInstantApp =
8077                        (si.applicationInfo.privateFlags
8078                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8079                final boolean isTargetHiddenFromInstantApp =
8080                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8081                final boolean blockResolution =
8082                        !isTargetSameInstantApp
8083                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8084                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8085                                        && isTargetHiddenFromInstantApp));
8086                if (!blockResolution) {
8087                    final ResolveInfo ri = new ResolveInfo();
8088                    ri.serviceInfo = si;
8089                    list.add(ri);
8090                }
8091            }
8092            return list;
8093        }
8094
8095        // reader
8096        synchronized (mPackages) {
8097            String pkgName = intent.getPackage();
8098            if (pkgName == null) {
8099                return applyPostServiceResolutionFilter(
8100                        mServices.queryIntent(intent, resolvedType, flags, userId),
8101                        instantAppPkgName);
8102            }
8103            final PackageParser.Package pkg = mPackages.get(pkgName);
8104            if (pkg != null) {
8105                return applyPostServiceResolutionFilter(
8106                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8107                                userId),
8108                        instantAppPkgName);
8109            }
8110            return Collections.emptyList();
8111        }
8112    }
8113
8114    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8115            String instantAppPkgName) {
8116        // TODO: When adding on-demand split support for non-instant apps, remove this check
8117        // and always apply post filtering
8118        if (instantAppPkgName == null) {
8119            return resolveInfos;
8120        }
8121        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8122            final ResolveInfo info = resolveInfos.get(i);
8123            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8124            // allow services that are defined in the provided package
8125            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8126                if (info.serviceInfo.splitName != null
8127                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8128                                info.serviceInfo.splitName)) {
8129                    // requested service is defined in a split that hasn't been installed yet.
8130                    // add the installer to the resolve list
8131                    if (DEBUG_EPHEMERAL) {
8132                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8133                    }
8134                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8135                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8136                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8137                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
8138                    // make sure this resolver is the default
8139                    installerInfo.isDefault = true;
8140                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8141                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8142                    // add a non-generic filter
8143                    installerInfo.filter = new IntentFilter();
8144                    // load resources from the correct package
8145                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8146                    resolveInfos.set(i, installerInfo);
8147                }
8148                continue;
8149            }
8150            // allow services that have been explicitly exposed to ephemeral apps
8151            if (!isEphemeralApp
8152                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8153                continue;
8154            }
8155            resolveInfos.remove(i);
8156        }
8157        return resolveInfos;
8158    }
8159
8160    @Override
8161    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8162            String resolvedType, int flags, int userId) {
8163        return new ParceledListSlice<>(
8164                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8165    }
8166
8167    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8168            Intent intent, String resolvedType, int flags, int userId) {
8169        if (!sUserManager.exists(userId)) return Collections.emptyList();
8170        final int callingUid = Binder.getCallingUid();
8171        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8172        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8173                false /*includeInstantApps*/);
8174        ComponentName comp = intent.getComponent();
8175        if (comp == null) {
8176            if (intent.getSelector() != null) {
8177                intent = intent.getSelector();
8178                comp = intent.getComponent();
8179            }
8180        }
8181        if (comp != null) {
8182            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8183            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8184            if (pi != null) {
8185                // When specifying an explicit component, we prevent the provider from being
8186                // used when either 1) the provider is in an instant application and the
8187                // caller is not the same instant application or 2) the calling package is an
8188                // instant application and the provider is not visible to instant applications.
8189                final boolean matchInstantApp =
8190                        (flags & PackageManager.MATCH_INSTANT) != 0;
8191                final boolean matchVisibleToInstantAppOnly =
8192                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8193                final boolean isCallerInstantApp =
8194                        instantAppPkgName != null;
8195                final boolean isTargetSameInstantApp =
8196                        comp.getPackageName().equals(instantAppPkgName);
8197                final boolean isTargetInstantApp =
8198                        (pi.applicationInfo.privateFlags
8199                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8200                final boolean isTargetHiddenFromInstantApp =
8201                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8202                final boolean blockResolution =
8203                        !isTargetSameInstantApp
8204                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8205                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8206                                        && isTargetHiddenFromInstantApp));
8207                if (!blockResolution) {
8208                    final ResolveInfo ri = new ResolveInfo();
8209                    ri.providerInfo = pi;
8210                    list.add(ri);
8211                }
8212            }
8213            return list;
8214        }
8215
8216        // reader
8217        synchronized (mPackages) {
8218            String pkgName = intent.getPackage();
8219            if (pkgName == null) {
8220                return applyPostContentProviderResolutionFilter(
8221                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8222                        instantAppPkgName);
8223            }
8224            final PackageParser.Package pkg = mPackages.get(pkgName);
8225            if (pkg != null) {
8226                return applyPostContentProviderResolutionFilter(
8227                        mProviders.queryIntentForPackage(
8228                        intent, resolvedType, flags, pkg.providers, userId),
8229                        instantAppPkgName);
8230            }
8231            return Collections.emptyList();
8232        }
8233    }
8234
8235    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8236            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8237        // TODO: When adding on-demand split support for non-instant applications, remove
8238        // this check and always apply post filtering
8239        if (instantAppPkgName == null) {
8240            return resolveInfos;
8241        }
8242        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8243            final ResolveInfo info = resolveInfos.get(i);
8244            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8245            // allow providers that are defined in the provided package
8246            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8247                if (info.providerInfo.splitName != null
8248                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8249                                info.providerInfo.splitName)) {
8250                    // requested provider is defined in a split that hasn't been installed yet.
8251                    // add the installer to the resolve list
8252                    if (DEBUG_EPHEMERAL) {
8253                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8254                    }
8255                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8256                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8257                            info.providerInfo.packageName, info.providerInfo.splitName,
8258                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8259                    // make sure this resolver is the default
8260                    installerInfo.isDefault = true;
8261                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8262                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8263                    // add a non-generic filter
8264                    installerInfo.filter = new IntentFilter();
8265                    // load resources from the correct package
8266                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8267                    resolveInfos.set(i, installerInfo);
8268                }
8269                continue;
8270            }
8271            // allow providers that have been explicitly exposed to instant applications
8272            if (!isEphemeralApp
8273                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8274                continue;
8275            }
8276            resolveInfos.remove(i);
8277        }
8278        return resolveInfos;
8279    }
8280
8281    @Override
8282    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8283        final int callingUid = Binder.getCallingUid();
8284        if (getInstantAppPackageName(callingUid) != null) {
8285            return ParceledListSlice.emptyList();
8286        }
8287        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8288        flags = updateFlagsForPackage(flags, userId, null);
8289        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8290        enforceCrossUserPermission(callingUid, userId,
8291                true /* requireFullPermission */, false /* checkShell */,
8292                "get installed packages");
8293
8294        // writer
8295        synchronized (mPackages) {
8296            ArrayList<PackageInfo> list;
8297            if (listUninstalled) {
8298                list = new ArrayList<>(mSettings.mPackages.size());
8299                for (PackageSetting ps : mSettings.mPackages.values()) {
8300                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8301                        continue;
8302                    }
8303                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8304                        return null;
8305                    }
8306                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8307                    if (pi != null) {
8308                        list.add(pi);
8309                    }
8310                }
8311            } else {
8312                list = new ArrayList<>(mPackages.size());
8313                for (PackageParser.Package p : mPackages.values()) {
8314                    final PackageSetting ps = (PackageSetting) p.mExtras;
8315                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8316                        continue;
8317                    }
8318                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8319                        return null;
8320                    }
8321                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8322                            p.mExtras, flags, userId);
8323                    if (pi != null) {
8324                        list.add(pi);
8325                    }
8326                }
8327            }
8328
8329            return new ParceledListSlice<>(list);
8330        }
8331    }
8332
8333    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8334            String[] permissions, boolean[] tmp, int flags, int userId) {
8335        int numMatch = 0;
8336        final PermissionsState permissionsState = ps.getPermissionsState();
8337        for (int i=0; i<permissions.length; i++) {
8338            final String permission = permissions[i];
8339            if (permissionsState.hasPermission(permission, userId)) {
8340                tmp[i] = true;
8341                numMatch++;
8342            } else {
8343                tmp[i] = false;
8344            }
8345        }
8346        if (numMatch == 0) {
8347            return;
8348        }
8349        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8350
8351        // The above might return null in cases of uninstalled apps or install-state
8352        // skew across users/profiles.
8353        if (pi != null) {
8354            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8355                if (numMatch == permissions.length) {
8356                    pi.requestedPermissions = permissions;
8357                } else {
8358                    pi.requestedPermissions = new String[numMatch];
8359                    numMatch = 0;
8360                    for (int i=0; i<permissions.length; i++) {
8361                        if (tmp[i]) {
8362                            pi.requestedPermissions[numMatch] = permissions[i];
8363                            numMatch++;
8364                        }
8365                    }
8366                }
8367            }
8368            list.add(pi);
8369        }
8370    }
8371
8372    @Override
8373    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8374            String[] permissions, int flags, int userId) {
8375        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8376        flags = updateFlagsForPackage(flags, userId, permissions);
8377        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8378                true /* requireFullPermission */, false /* checkShell */,
8379                "get packages holding permissions");
8380        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8381
8382        // writer
8383        synchronized (mPackages) {
8384            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8385            boolean[] tmpBools = new boolean[permissions.length];
8386            if (listUninstalled) {
8387                for (PackageSetting ps : mSettings.mPackages.values()) {
8388                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8389                            userId);
8390                }
8391            } else {
8392                for (PackageParser.Package pkg : mPackages.values()) {
8393                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8394                    if (ps != null) {
8395                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8396                                userId);
8397                    }
8398                }
8399            }
8400
8401            return new ParceledListSlice<PackageInfo>(list);
8402        }
8403    }
8404
8405    @Override
8406    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8407        final int callingUid = Binder.getCallingUid();
8408        if (getInstantAppPackageName(callingUid) != null) {
8409            return ParceledListSlice.emptyList();
8410        }
8411        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8412        flags = updateFlagsForApplication(flags, userId, null);
8413        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8414
8415        // writer
8416        synchronized (mPackages) {
8417            ArrayList<ApplicationInfo> list;
8418            if (listUninstalled) {
8419                list = new ArrayList<>(mSettings.mPackages.size());
8420                for (PackageSetting ps : mSettings.mPackages.values()) {
8421                    ApplicationInfo ai;
8422                    int effectiveFlags = flags;
8423                    if (ps.isSystem()) {
8424                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8425                    }
8426                    if (ps.pkg != null) {
8427                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8428                            continue;
8429                        }
8430                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8431                            return null;
8432                        }
8433                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8434                                ps.readUserState(userId), userId);
8435                        if (ai != null) {
8436                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8437                        }
8438                    } else {
8439                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8440                        // and already converts to externally visible package name
8441                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8442                                callingUid, effectiveFlags, userId);
8443                    }
8444                    if (ai != null) {
8445                        list.add(ai);
8446                    }
8447                }
8448            } else {
8449                list = new ArrayList<>(mPackages.size());
8450                for (PackageParser.Package p : mPackages.values()) {
8451                    if (p.mExtras != null) {
8452                        PackageSetting ps = (PackageSetting) p.mExtras;
8453                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8454                            continue;
8455                        }
8456                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8457                            return null;
8458                        }
8459                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8460                                ps.readUserState(userId), userId);
8461                        if (ai != null) {
8462                            ai.packageName = resolveExternalPackageNameLPr(p);
8463                            list.add(ai);
8464                        }
8465                    }
8466                }
8467            }
8468
8469            return new ParceledListSlice<>(list);
8470        }
8471    }
8472
8473    @Override
8474    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8475        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8476            return null;
8477        }
8478        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8479                "getEphemeralApplications");
8480        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8481                true /* requireFullPermission */, false /* checkShell */,
8482                "getEphemeralApplications");
8483        synchronized (mPackages) {
8484            List<InstantAppInfo> instantApps = mInstantAppRegistry
8485                    .getInstantAppsLPr(userId);
8486            if (instantApps != null) {
8487                return new ParceledListSlice<>(instantApps);
8488            }
8489        }
8490        return null;
8491    }
8492
8493    @Override
8494    public boolean isInstantApp(String packageName, int userId) {
8495        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8496                true /* requireFullPermission */, false /* checkShell */,
8497                "isInstantApp");
8498        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8499            return false;
8500        }
8501
8502        synchronized (mPackages) {
8503            int callingUid = Binder.getCallingUid();
8504            if (Process.isIsolated(callingUid)) {
8505                callingUid = mIsolatedOwners.get(callingUid);
8506            }
8507            final PackageSetting ps = mSettings.mPackages.get(packageName);
8508            PackageParser.Package pkg = mPackages.get(packageName);
8509            final boolean returnAllowed =
8510                    ps != null
8511                    && (isCallerSameApp(packageName, callingUid)
8512                            || canViewInstantApps(callingUid, userId)
8513                            || mInstantAppRegistry.isInstantAccessGranted(
8514                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8515            if (returnAllowed) {
8516                return ps.getInstantApp(userId);
8517            }
8518        }
8519        return false;
8520    }
8521
8522    @Override
8523    public byte[] getInstantAppCookie(String packageName, int userId) {
8524        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8525            return null;
8526        }
8527
8528        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8529                true /* requireFullPermission */, false /* checkShell */,
8530                "getInstantAppCookie");
8531        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8532            return null;
8533        }
8534        synchronized (mPackages) {
8535            return mInstantAppRegistry.getInstantAppCookieLPw(
8536                    packageName, userId);
8537        }
8538    }
8539
8540    @Override
8541    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8542        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8543            return true;
8544        }
8545
8546        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8547                true /* requireFullPermission */, true /* checkShell */,
8548                "setInstantAppCookie");
8549        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8550            return false;
8551        }
8552        synchronized (mPackages) {
8553            return mInstantAppRegistry.setInstantAppCookieLPw(
8554                    packageName, cookie, userId);
8555        }
8556    }
8557
8558    @Override
8559    public Bitmap getInstantAppIcon(String packageName, int userId) {
8560        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8561            return null;
8562        }
8563
8564        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8565                "getInstantAppIcon");
8566
8567        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8568                true /* requireFullPermission */, false /* checkShell */,
8569                "getInstantAppIcon");
8570
8571        synchronized (mPackages) {
8572            return mInstantAppRegistry.getInstantAppIconLPw(
8573                    packageName, userId);
8574        }
8575    }
8576
8577    private boolean isCallerSameApp(String packageName, int uid) {
8578        PackageParser.Package pkg = mPackages.get(packageName);
8579        return pkg != null
8580                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8581    }
8582
8583    @Override
8584    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8585        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8586            return ParceledListSlice.emptyList();
8587        }
8588        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8589    }
8590
8591    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8592        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8593
8594        // reader
8595        synchronized (mPackages) {
8596            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8597            final int userId = UserHandle.getCallingUserId();
8598            while (i.hasNext()) {
8599                final PackageParser.Package p = i.next();
8600                if (p.applicationInfo == null) continue;
8601
8602                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8603                        && !p.applicationInfo.isDirectBootAware();
8604                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8605                        && p.applicationInfo.isDirectBootAware();
8606
8607                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8608                        && (!mSafeMode || isSystemApp(p))
8609                        && (matchesUnaware || matchesAware)) {
8610                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8611                    if (ps != null) {
8612                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8613                                ps.readUserState(userId), userId);
8614                        if (ai != null) {
8615                            finalList.add(ai);
8616                        }
8617                    }
8618                }
8619            }
8620        }
8621
8622        return finalList;
8623    }
8624
8625    @Override
8626    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8627        if (!sUserManager.exists(userId)) return null;
8628        flags = updateFlagsForComponent(flags, userId, name);
8629        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8630        // reader
8631        synchronized (mPackages) {
8632            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8633            PackageSetting ps = provider != null
8634                    ? mSettings.mPackages.get(provider.owner.packageName)
8635                    : null;
8636            if (ps != null) {
8637                final boolean isInstantApp = ps.getInstantApp(userId);
8638                // normal application; filter out instant application provider
8639                if (instantAppPkgName == null && isInstantApp) {
8640                    return null;
8641                }
8642                // instant application; filter out other instant applications
8643                if (instantAppPkgName != null
8644                        && isInstantApp
8645                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8646                    return null;
8647                }
8648                // instant application; filter out non-exposed provider
8649                if (instantAppPkgName != null
8650                        && !isInstantApp
8651                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8652                    return null;
8653                }
8654                // provider not enabled
8655                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8656                    return null;
8657                }
8658                return PackageParser.generateProviderInfo(
8659                        provider, flags, ps.readUserState(userId), userId);
8660            }
8661            return null;
8662        }
8663    }
8664
8665    /**
8666     * @deprecated
8667     */
8668    @Deprecated
8669    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8670        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8671            return;
8672        }
8673        // reader
8674        synchronized (mPackages) {
8675            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8676                    .entrySet().iterator();
8677            final int userId = UserHandle.getCallingUserId();
8678            while (i.hasNext()) {
8679                Map.Entry<String, PackageParser.Provider> entry = i.next();
8680                PackageParser.Provider p = entry.getValue();
8681                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8682
8683                if (ps != null && p.syncable
8684                        && (!mSafeMode || (p.info.applicationInfo.flags
8685                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8686                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8687                            ps.readUserState(userId), userId);
8688                    if (info != null) {
8689                        outNames.add(entry.getKey());
8690                        outInfo.add(info);
8691                    }
8692                }
8693            }
8694        }
8695    }
8696
8697    @Override
8698    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8699            int uid, int flags, String metaDataKey) {
8700        final int callingUid = Binder.getCallingUid();
8701        final int userId = processName != null ? UserHandle.getUserId(uid)
8702                : UserHandle.getCallingUserId();
8703        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8704        flags = updateFlagsForComponent(flags, userId, processName);
8705        ArrayList<ProviderInfo> finalList = null;
8706        // reader
8707        synchronized (mPackages) {
8708            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8709            while (i.hasNext()) {
8710                final PackageParser.Provider p = i.next();
8711                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8712                if (ps != null && p.info.authority != null
8713                        && (processName == null
8714                                || (p.info.processName.equals(processName)
8715                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8716                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8717
8718                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8719                    // parameter.
8720                    if (metaDataKey != null
8721                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8722                        continue;
8723                    }
8724                    final ComponentName component =
8725                            new ComponentName(p.info.packageName, p.info.name);
8726                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8727                        continue;
8728                    }
8729                    if (finalList == null) {
8730                        finalList = new ArrayList<ProviderInfo>(3);
8731                    }
8732                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8733                            ps.readUserState(userId), userId);
8734                    if (info != null) {
8735                        finalList.add(info);
8736                    }
8737                }
8738            }
8739        }
8740
8741        if (finalList != null) {
8742            Collections.sort(finalList, mProviderInitOrderSorter);
8743            return new ParceledListSlice<ProviderInfo>(finalList);
8744        }
8745
8746        return ParceledListSlice.emptyList();
8747    }
8748
8749    @Override
8750    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8751        // reader
8752        synchronized (mPackages) {
8753            final int callingUid = Binder.getCallingUid();
8754            final int callingUserId = UserHandle.getUserId(callingUid);
8755            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8756            if (ps == null) return null;
8757            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8758                return null;
8759            }
8760            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8761            return PackageParser.generateInstrumentationInfo(i, flags);
8762        }
8763    }
8764
8765    @Override
8766    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8767            String targetPackage, int flags) {
8768        final int callingUid = Binder.getCallingUid();
8769        final int callingUserId = UserHandle.getUserId(callingUid);
8770        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8771        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8772            return ParceledListSlice.emptyList();
8773        }
8774        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8775    }
8776
8777    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8778            int flags) {
8779        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8780
8781        // reader
8782        synchronized (mPackages) {
8783            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8784            while (i.hasNext()) {
8785                final PackageParser.Instrumentation p = i.next();
8786                if (targetPackage == null
8787                        || targetPackage.equals(p.info.targetPackage)) {
8788                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8789                            flags);
8790                    if (ii != null) {
8791                        finalList.add(ii);
8792                    }
8793                }
8794            }
8795        }
8796
8797        return finalList;
8798    }
8799
8800    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8801        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8802        try {
8803            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8804        } finally {
8805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8806        }
8807    }
8808
8809    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8810        final File[] files = dir.listFiles();
8811        if (ArrayUtils.isEmpty(files)) {
8812            Log.d(TAG, "No files in app dir " + dir);
8813            return;
8814        }
8815
8816        if (DEBUG_PACKAGE_SCANNING) {
8817            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8818                    + " flags=0x" + Integer.toHexString(parseFlags));
8819        }
8820        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8821                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8822                mParallelPackageParserCallback);
8823
8824        // Submit files for parsing in parallel
8825        int fileCount = 0;
8826        for (File file : files) {
8827            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8828                    && !PackageInstallerService.isStageName(file.getName());
8829            if (!isPackage) {
8830                // Ignore entries which are not packages
8831                continue;
8832            }
8833            parallelPackageParser.submit(file, parseFlags);
8834            fileCount++;
8835        }
8836
8837        // Process results one by one
8838        for (; fileCount > 0; fileCount--) {
8839            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8840            Throwable throwable = parseResult.throwable;
8841            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8842
8843            if (throwable == null) {
8844                // Static shared libraries have synthetic package names
8845                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8846                    renameStaticSharedLibraryPackage(parseResult.pkg);
8847                }
8848                try {
8849                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8850                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8851                                currentTime, null);
8852                    }
8853                } catch (PackageManagerException e) {
8854                    errorCode = e.error;
8855                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8856                }
8857            } else if (throwable instanceof PackageParser.PackageParserException) {
8858                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8859                        throwable;
8860                errorCode = e.error;
8861                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8862            } else {
8863                throw new IllegalStateException("Unexpected exception occurred while parsing "
8864                        + parseResult.scanFile, throwable);
8865            }
8866
8867            // Delete invalid userdata apps
8868            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8869                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8870                logCriticalInfo(Log.WARN,
8871                        "Deleting invalid package at " + parseResult.scanFile);
8872                removeCodePathLI(parseResult.scanFile);
8873            }
8874        }
8875        parallelPackageParser.close();
8876    }
8877
8878    private static File getSettingsProblemFile() {
8879        File dataDir = Environment.getDataDirectory();
8880        File systemDir = new File(dataDir, "system");
8881        File fname = new File(systemDir, "uiderrors.txt");
8882        return fname;
8883    }
8884
8885    static void reportSettingsProblem(int priority, String msg) {
8886        logCriticalInfo(priority, msg);
8887    }
8888
8889    public static void logCriticalInfo(int priority, String msg) {
8890        Slog.println(priority, TAG, msg);
8891        EventLogTags.writePmCriticalInfo(msg);
8892        try {
8893            File fname = getSettingsProblemFile();
8894            FileOutputStream out = new FileOutputStream(fname, true);
8895            PrintWriter pw = new FastPrintWriter(out);
8896            SimpleDateFormat formatter = new SimpleDateFormat();
8897            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8898            pw.println(dateString + ": " + msg);
8899            pw.close();
8900            FileUtils.setPermissions(
8901                    fname.toString(),
8902                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8903                    -1, -1);
8904        } catch (java.io.IOException e) {
8905        }
8906    }
8907
8908    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8909        if (srcFile.isDirectory()) {
8910            final File baseFile = new File(pkg.baseCodePath);
8911            long maxModifiedTime = baseFile.lastModified();
8912            if (pkg.splitCodePaths != null) {
8913                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8914                    final File splitFile = new File(pkg.splitCodePaths[i]);
8915                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8916                }
8917            }
8918            return maxModifiedTime;
8919        }
8920        return srcFile.lastModified();
8921    }
8922
8923    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8924            final int policyFlags) throws PackageManagerException {
8925        // When upgrading from pre-N MR1, verify the package time stamp using the package
8926        // directory and not the APK file.
8927        final long lastModifiedTime = mIsPreNMR1Upgrade
8928                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8929        if (ps != null
8930                && ps.codePath.equals(srcFile)
8931                && ps.timeStamp == lastModifiedTime
8932                && !isCompatSignatureUpdateNeeded(pkg)
8933                && !isRecoverSignatureUpdateNeeded(pkg)) {
8934            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8935            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8936            ArraySet<PublicKey> signingKs;
8937            synchronized (mPackages) {
8938                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8939            }
8940            if (ps.signatures.mSignatures != null
8941                    && ps.signatures.mSignatures.length != 0
8942                    && signingKs != null) {
8943                // Optimization: reuse the existing cached certificates
8944                // if the package appears to be unchanged.
8945                pkg.mSignatures = ps.signatures.mSignatures;
8946                pkg.mSigningKeys = signingKs;
8947                return;
8948            }
8949
8950            Slog.w(TAG, "PackageSetting for " + ps.name
8951                    + " is missing signatures.  Collecting certs again to recover them.");
8952        } else {
8953            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8954        }
8955
8956        try {
8957            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8958            PackageParser.collectCertificates(pkg, policyFlags);
8959        } catch (PackageParserException e) {
8960            throw PackageManagerException.from(e);
8961        } finally {
8962            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8963        }
8964    }
8965
8966    /**
8967     *  Traces a package scan.
8968     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8969     */
8970    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8971            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8972        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8973        try {
8974            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8975        } finally {
8976            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8977        }
8978    }
8979
8980    /**
8981     *  Scans a package and returns the newly parsed package.
8982     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8983     */
8984    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8985            long currentTime, UserHandle user) throws PackageManagerException {
8986        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8987        PackageParser pp = new PackageParser();
8988        pp.setSeparateProcesses(mSeparateProcesses);
8989        pp.setOnlyCoreApps(mOnlyCore);
8990        pp.setDisplayMetrics(mMetrics);
8991        pp.setCallback(mPackageParserCallback);
8992
8993        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8994            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8995        }
8996
8997        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8998        final PackageParser.Package pkg;
8999        try {
9000            pkg = pp.parsePackage(scanFile, parseFlags);
9001        } catch (PackageParserException e) {
9002            throw PackageManagerException.from(e);
9003        } finally {
9004            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9005        }
9006
9007        // Static shared libraries have synthetic package names
9008        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9009            renameStaticSharedLibraryPackage(pkg);
9010        }
9011
9012        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9013    }
9014
9015    /**
9016     *  Scans a package and returns the newly parsed package.
9017     *  @throws PackageManagerException on a parse error.
9018     */
9019    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9020            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9021            throws PackageManagerException {
9022        // If the package has children and this is the first dive in the function
9023        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9024        // packages (parent and children) would be successfully scanned before the
9025        // actual scan since scanning mutates internal state and we want to atomically
9026        // install the package and its children.
9027        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9028            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9029                scanFlags |= SCAN_CHECK_ONLY;
9030            }
9031        } else {
9032            scanFlags &= ~SCAN_CHECK_ONLY;
9033        }
9034
9035        // Scan the parent
9036        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9037                scanFlags, currentTime, user);
9038
9039        // Scan the children
9040        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9041        for (int i = 0; i < childCount; i++) {
9042            PackageParser.Package childPackage = pkg.childPackages.get(i);
9043            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9044                    currentTime, user);
9045        }
9046
9047
9048        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9049            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9050        }
9051
9052        return scannedPkg;
9053    }
9054
9055    /**
9056     *  Scans a package and returns the newly parsed package.
9057     *  @throws PackageManagerException on a parse error.
9058     */
9059    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9060            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9061            throws PackageManagerException {
9062        PackageSetting ps = null;
9063        PackageSetting updatedPkg;
9064        // reader
9065        synchronized (mPackages) {
9066            // Look to see if we already know about this package.
9067            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9068            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9069                // This package has been renamed to its original name.  Let's
9070                // use that.
9071                ps = mSettings.getPackageLPr(oldName);
9072            }
9073            // If there was no original package, see one for the real package name.
9074            if (ps == null) {
9075                ps = mSettings.getPackageLPr(pkg.packageName);
9076            }
9077            // Check to see if this package could be hiding/updating a system
9078            // package.  Must look for it either under the original or real
9079            // package name depending on our state.
9080            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9081            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9082
9083            // If this is a package we don't know about on the system partition, we
9084            // may need to remove disabled child packages on the system partition
9085            // or may need to not add child packages if the parent apk is updated
9086            // on the data partition and no longer defines this child package.
9087            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9088                // If this is a parent package for an updated system app and this system
9089                // app got an OTA update which no longer defines some of the child packages
9090                // we have to prune them from the disabled system packages.
9091                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9092                if (disabledPs != null) {
9093                    final int scannedChildCount = (pkg.childPackages != null)
9094                            ? pkg.childPackages.size() : 0;
9095                    final int disabledChildCount = disabledPs.childPackageNames != null
9096                            ? disabledPs.childPackageNames.size() : 0;
9097                    for (int i = 0; i < disabledChildCount; i++) {
9098                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9099                        boolean disabledPackageAvailable = false;
9100                        for (int j = 0; j < scannedChildCount; j++) {
9101                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9102                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9103                                disabledPackageAvailable = true;
9104                                break;
9105                            }
9106                         }
9107                         if (!disabledPackageAvailable) {
9108                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9109                         }
9110                    }
9111                }
9112            }
9113        }
9114
9115        final boolean isUpdatedPkg = updatedPkg != null;
9116        final boolean isUpdatedSystemPkg = isUpdatedPkg
9117                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9118        boolean isUpdatedPkgBetter = false;
9119        // First check if this is a system package that may involve an update
9120        if (isUpdatedSystemPkg) {
9121            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9122            // it needs to drop FLAG_PRIVILEGED.
9123            if (locationIsPrivileged(scanFile)) {
9124                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9125            } else {
9126                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9127            }
9128
9129            if (ps != null && !ps.codePath.equals(scanFile)) {
9130                // The path has changed from what was last scanned...  check the
9131                // version of the new path against what we have stored to determine
9132                // what to do.
9133                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9134                if (pkg.mVersionCode <= ps.versionCode) {
9135                    // The system package has been updated and the code path does not match
9136                    // Ignore entry. Skip it.
9137                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9138                            + " ignored: updated version " + ps.versionCode
9139                            + " better than this " + pkg.mVersionCode);
9140                    if (!updatedPkg.codePath.equals(scanFile)) {
9141                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9142                                + ps.name + " changing from " + updatedPkg.codePathString
9143                                + " to " + scanFile);
9144                        updatedPkg.codePath = scanFile;
9145                        updatedPkg.codePathString = scanFile.toString();
9146                        updatedPkg.resourcePath = scanFile;
9147                        updatedPkg.resourcePathString = scanFile.toString();
9148                    }
9149                    updatedPkg.pkg = pkg;
9150                    updatedPkg.versionCode = pkg.mVersionCode;
9151
9152                    // Update the disabled system child packages to point to the package too.
9153                    final int childCount = updatedPkg.childPackageNames != null
9154                            ? updatedPkg.childPackageNames.size() : 0;
9155                    for (int i = 0; i < childCount; i++) {
9156                        String childPackageName = updatedPkg.childPackageNames.get(i);
9157                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9158                                childPackageName);
9159                        if (updatedChildPkg != null) {
9160                            updatedChildPkg.pkg = pkg;
9161                            updatedChildPkg.versionCode = pkg.mVersionCode;
9162                        }
9163                    }
9164                } else {
9165                    // The current app on the system partition is better than
9166                    // what we have updated to on the data partition; switch
9167                    // back to the system partition version.
9168                    // At this point, its safely assumed that package installation for
9169                    // apps in system partition will go through. If not there won't be a working
9170                    // version of the app
9171                    // writer
9172                    synchronized (mPackages) {
9173                        // Just remove the loaded entries from package lists.
9174                        mPackages.remove(ps.name);
9175                    }
9176
9177                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9178                            + " reverting from " + ps.codePathString
9179                            + ": new version " + pkg.mVersionCode
9180                            + " better than installed " + ps.versionCode);
9181
9182                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9183                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9184                    synchronized (mInstallLock) {
9185                        args.cleanUpResourcesLI();
9186                    }
9187                    synchronized (mPackages) {
9188                        mSettings.enableSystemPackageLPw(ps.name);
9189                    }
9190                    isUpdatedPkgBetter = true;
9191                }
9192            }
9193        }
9194
9195        String resourcePath = null;
9196        String baseResourcePath = null;
9197        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9198            if (ps != null && ps.resourcePathString != null) {
9199                resourcePath = ps.resourcePathString;
9200                baseResourcePath = ps.resourcePathString;
9201            } else {
9202                // Should not happen at all. Just log an error.
9203                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9204            }
9205        } else {
9206            resourcePath = pkg.codePath;
9207            baseResourcePath = pkg.baseCodePath;
9208        }
9209
9210        // Set application objects path explicitly.
9211        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9212        pkg.setApplicationInfoCodePath(pkg.codePath);
9213        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9214        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9215        pkg.setApplicationInfoResourcePath(resourcePath);
9216        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9217        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9218
9219        // throw an exception if we have an update to a system application, but, it's not more
9220        // recent than the package we've already scanned
9221        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9222            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9223                    + scanFile + " ignored: updated version " + ps.versionCode
9224                    + " better than this " + pkg.mVersionCode);
9225        }
9226
9227        if (isUpdatedPkg) {
9228            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9229            // initially
9230            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9231
9232            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9233            // flag set initially
9234            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9235                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9236            }
9237        }
9238
9239        // Verify certificates against what was last scanned
9240        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9241
9242        /*
9243         * A new system app appeared, but we already had a non-system one of the
9244         * same name installed earlier.
9245         */
9246        boolean shouldHideSystemApp = false;
9247        if (!isUpdatedPkg && ps != null
9248                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9249            /*
9250             * Check to make sure the signatures match first. If they don't,
9251             * wipe the installed application and its data.
9252             */
9253            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9254                    != PackageManager.SIGNATURE_MATCH) {
9255                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9256                        + " signatures don't match existing userdata copy; removing");
9257                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9258                        "scanPackageInternalLI")) {
9259                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9260                }
9261                ps = null;
9262            } else {
9263                /*
9264                 * If the newly-added system app is an older version than the
9265                 * already installed version, hide it. It will be scanned later
9266                 * and re-added like an update.
9267                 */
9268                if (pkg.mVersionCode <= ps.versionCode) {
9269                    shouldHideSystemApp = true;
9270                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9271                            + " but new version " + pkg.mVersionCode + " better than installed "
9272                            + ps.versionCode + "; hiding system");
9273                } else {
9274                    /*
9275                     * The newly found system app is a newer version that the
9276                     * one previously installed. Simply remove the
9277                     * already-installed application and replace it with our own
9278                     * while keeping the application data.
9279                     */
9280                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9281                            + " reverting from " + ps.codePathString + ": new version "
9282                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9283                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9284                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9285                    synchronized (mInstallLock) {
9286                        args.cleanUpResourcesLI();
9287                    }
9288                }
9289            }
9290        }
9291
9292        // The apk is forward locked (not public) if its code and resources
9293        // are kept in different files. (except for app in either system or
9294        // vendor path).
9295        // TODO grab this value from PackageSettings
9296        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9297            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9298                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9299            }
9300        }
9301
9302        final int userId = ((user == null) ? 0 : user.getIdentifier());
9303        if (ps != null && ps.getInstantApp(userId)) {
9304            scanFlags |= SCAN_AS_INSTANT_APP;
9305        }
9306
9307        // Note that we invoke the following method only if we are about to unpack an application
9308        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9309                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9310
9311        /*
9312         * If the system app should be overridden by a previously installed
9313         * data, hide the system app now and let the /data/app scan pick it up
9314         * again.
9315         */
9316        if (shouldHideSystemApp) {
9317            synchronized (mPackages) {
9318                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9319            }
9320        }
9321
9322        return scannedPkg;
9323    }
9324
9325    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9326        // Derive the new package synthetic package name
9327        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9328                + pkg.staticSharedLibVersion);
9329    }
9330
9331    private static String fixProcessName(String defProcessName,
9332            String processName) {
9333        if (processName == null) {
9334            return defProcessName;
9335        }
9336        return processName;
9337    }
9338
9339    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9340            throws PackageManagerException {
9341        if (pkgSetting.signatures.mSignatures != null) {
9342            // Already existing package. Make sure signatures match
9343            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9344                    == PackageManager.SIGNATURE_MATCH;
9345            if (!match) {
9346                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9347                        == PackageManager.SIGNATURE_MATCH;
9348            }
9349            if (!match) {
9350                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9351                        == PackageManager.SIGNATURE_MATCH;
9352            }
9353            if (!match) {
9354                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9355                        + pkg.packageName + " signatures do not match the "
9356                        + "previously installed version; ignoring!");
9357            }
9358        }
9359
9360        // Check for shared user signatures
9361        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9362            // Already existing package. Make sure signatures match
9363            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9364                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9365            if (!match) {
9366                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9367                        == PackageManager.SIGNATURE_MATCH;
9368            }
9369            if (!match) {
9370                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9371                        == PackageManager.SIGNATURE_MATCH;
9372            }
9373            if (!match) {
9374                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9375                        "Package " + pkg.packageName
9376                        + " has no signatures that match those in shared user "
9377                        + pkgSetting.sharedUser.name + "; ignoring!");
9378            }
9379        }
9380    }
9381
9382    /**
9383     * Enforces that only the system UID or root's UID can call a method exposed
9384     * via Binder.
9385     *
9386     * @param message used as message if SecurityException is thrown
9387     * @throws SecurityException if the caller is not system or root
9388     */
9389    private static final void enforceSystemOrRoot(String message) {
9390        final int uid = Binder.getCallingUid();
9391        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9392            throw new SecurityException(message);
9393        }
9394    }
9395
9396    @Override
9397    public void performFstrimIfNeeded() {
9398        enforceSystemOrRoot("Only the system can request fstrim");
9399
9400        // Before everything else, see whether we need to fstrim.
9401        try {
9402            IStorageManager sm = PackageHelper.getStorageManager();
9403            if (sm != null) {
9404                boolean doTrim = false;
9405                final long interval = android.provider.Settings.Global.getLong(
9406                        mContext.getContentResolver(),
9407                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9408                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9409                if (interval > 0) {
9410                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9411                    if (timeSinceLast > interval) {
9412                        doTrim = true;
9413                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9414                                + "; running immediately");
9415                    }
9416                }
9417                if (doTrim) {
9418                    final boolean dexOptDialogShown;
9419                    synchronized (mPackages) {
9420                        dexOptDialogShown = mDexOptDialogShown;
9421                    }
9422                    if (!isFirstBoot() && dexOptDialogShown) {
9423                        try {
9424                            ActivityManager.getService().showBootMessage(
9425                                    mContext.getResources().getString(
9426                                            R.string.android_upgrading_fstrim), true);
9427                        } catch (RemoteException e) {
9428                        }
9429                    }
9430                    sm.runMaintenance();
9431                }
9432            } else {
9433                Slog.e(TAG, "storageManager service unavailable!");
9434            }
9435        } catch (RemoteException e) {
9436            // Can't happen; StorageManagerService is local
9437        }
9438    }
9439
9440    @Override
9441    public void updatePackagesIfNeeded() {
9442        enforceSystemOrRoot("Only the system can request package update");
9443
9444        // We need to re-extract after an OTA.
9445        boolean causeUpgrade = isUpgrade();
9446
9447        // First boot or factory reset.
9448        // Note: we also handle devices that are upgrading to N right now as if it is their
9449        //       first boot, as they do not have profile data.
9450        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9451
9452        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9453        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9454
9455        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9456            return;
9457        }
9458
9459        List<PackageParser.Package> pkgs;
9460        synchronized (mPackages) {
9461            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9462        }
9463
9464        final long startTime = System.nanoTime();
9465        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9466                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9467                    false /* bootComplete */);
9468
9469        final int elapsedTimeSeconds =
9470                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9471
9472        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9473        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9474        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9475        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9476        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9477    }
9478
9479    /*
9480     * Return the prebuilt profile path given a package base code path.
9481     */
9482    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9483        return pkg.baseCodePath + ".prof";
9484    }
9485
9486    /**
9487     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9488     * containing statistics about the invocation. The array consists of three elements,
9489     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9490     * and {@code numberOfPackagesFailed}.
9491     */
9492    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9493            String compilerFilter, boolean bootComplete) {
9494
9495        int numberOfPackagesVisited = 0;
9496        int numberOfPackagesOptimized = 0;
9497        int numberOfPackagesSkipped = 0;
9498        int numberOfPackagesFailed = 0;
9499        final int numberOfPackagesToDexopt = pkgs.size();
9500
9501        for (PackageParser.Package pkg : pkgs) {
9502            numberOfPackagesVisited++;
9503
9504            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9505                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9506                // that are already compiled.
9507                File profileFile = new File(getPrebuildProfilePath(pkg));
9508                // Copy profile if it exists.
9509                if (profileFile.exists()) {
9510                    try {
9511                        // We could also do this lazily before calling dexopt in
9512                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9513                        // is that we don't have a good way to say "do this only once".
9514                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9515                                pkg.applicationInfo.uid, pkg.packageName)) {
9516                            Log.e(TAG, "Installer failed to copy system profile!");
9517                        }
9518                    } catch (Exception e) {
9519                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9520                                e);
9521                    }
9522                }
9523            }
9524
9525            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9526                if (DEBUG_DEXOPT) {
9527                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9528                }
9529                numberOfPackagesSkipped++;
9530                continue;
9531            }
9532
9533            if (DEBUG_DEXOPT) {
9534                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9535                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9536            }
9537
9538            if (showDialog) {
9539                try {
9540                    ActivityManager.getService().showBootMessage(
9541                            mContext.getResources().getString(R.string.android_upgrading_apk,
9542                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9543                } catch (RemoteException e) {
9544                }
9545                synchronized (mPackages) {
9546                    mDexOptDialogShown = true;
9547                }
9548            }
9549
9550            // If the OTA updates a system app which was previously preopted to a non-preopted state
9551            // the app might end up being verified at runtime. That's because by default the apps
9552            // are verify-profile but for preopted apps there's no profile.
9553            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9554            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9555            // filter (by default 'quicken').
9556            // Note that at this stage unused apps are already filtered.
9557            if (isSystemApp(pkg) &&
9558                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9559                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9560                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9561            }
9562
9563            // checkProfiles is false to avoid merging profiles during boot which
9564            // might interfere with background compilation (b/28612421).
9565            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9566            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9567            // trade-off worth doing to save boot time work.
9568            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9569            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9570                    pkg.packageName,
9571                    compilerFilter,
9572                    dexoptFlags));
9573
9574            if (pkg.isSystemApp()) {
9575                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9576                // too much boot after an OTA.
9577                int secondaryDexoptFlags = dexoptFlags |
9578                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9579                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9580                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9581                        pkg.packageName,
9582                        compilerFilter,
9583                        secondaryDexoptFlags));
9584            }
9585
9586            // TODO(shubhamajmera): Record secondary dexopt stats.
9587            switch (primaryDexOptStaus) {
9588                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9589                    numberOfPackagesOptimized++;
9590                    break;
9591                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9592                    numberOfPackagesSkipped++;
9593                    break;
9594                case PackageDexOptimizer.DEX_OPT_FAILED:
9595                    numberOfPackagesFailed++;
9596                    break;
9597                default:
9598                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9599                    break;
9600            }
9601        }
9602
9603        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9604                numberOfPackagesFailed };
9605    }
9606
9607    @Override
9608    public void notifyPackageUse(String packageName, int reason) {
9609        synchronized (mPackages) {
9610            final int callingUid = Binder.getCallingUid();
9611            final int callingUserId = UserHandle.getUserId(callingUid);
9612            if (getInstantAppPackageName(callingUid) != null) {
9613                if (!isCallerSameApp(packageName, callingUid)) {
9614                    return;
9615                }
9616            } else {
9617                if (isInstantApp(packageName, callingUserId)) {
9618                    return;
9619                }
9620            }
9621            final PackageParser.Package p = mPackages.get(packageName);
9622            if (p == null) {
9623                return;
9624            }
9625            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9626        }
9627    }
9628
9629    @Override
9630    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9631        int userId = UserHandle.getCallingUserId();
9632        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9633        if (ai == null) {
9634            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9635                + loadingPackageName + ", user=" + userId);
9636            return;
9637        }
9638        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9639    }
9640
9641    @Override
9642    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9643            IDexModuleRegisterCallback callback) {
9644        int userId = UserHandle.getCallingUserId();
9645        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9646        DexManager.RegisterDexModuleResult result;
9647        if (ai == null) {
9648            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9649                     " calling user. package=" + packageName + ", user=" + userId);
9650            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9651        } else {
9652            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9653        }
9654
9655        if (callback != null) {
9656            mHandler.post(() -> {
9657                try {
9658                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9659                } catch (RemoteException e) {
9660                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9661                }
9662            });
9663        }
9664    }
9665
9666    /**
9667     * Ask the package manager to perform a dex-opt with the given compiler filter.
9668     *
9669     * Note: exposed only for the shell command to allow moving packages explicitly to a
9670     *       definite state.
9671     */
9672    @Override
9673    public boolean performDexOptMode(String packageName,
9674            boolean checkProfiles, String targetCompilerFilter, boolean force,
9675            boolean bootComplete, String splitName) {
9676        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9677                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9678                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9679        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9680                splitName, flags));
9681    }
9682
9683    /**
9684     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9685     * secondary dex files belonging to the given package.
9686     *
9687     * Note: exposed only for the shell command to allow moving packages explicitly to a
9688     *       definite state.
9689     */
9690    @Override
9691    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9692            boolean force) {
9693        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9694                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9695                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9696                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9697        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9698    }
9699
9700    /*package*/ boolean performDexOpt(DexoptOptions options) {
9701        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9702            return false;
9703        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9704            return false;
9705        }
9706
9707        if (options.isDexoptOnlySecondaryDex()) {
9708            return mDexManager.dexoptSecondaryDex(options);
9709        } else {
9710            int dexoptStatus = performDexOptWithStatus(options);
9711            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9712        }
9713    }
9714
9715    /**
9716     * Perform dexopt on the given package and return one of following result:
9717     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9718     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9719     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9720     */
9721    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9722        return performDexOptTraced(options);
9723    }
9724
9725    private int performDexOptTraced(DexoptOptions options) {
9726        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9727        try {
9728            return performDexOptInternal(options);
9729        } finally {
9730            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9731        }
9732    }
9733
9734    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9735    // if the package can now be considered up to date for the given filter.
9736    private int performDexOptInternal(DexoptOptions options) {
9737        PackageParser.Package p;
9738        synchronized (mPackages) {
9739            p = mPackages.get(options.getPackageName());
9740            if (p == null) {
9741                // Package could not be found. Report failure.
9742                return PackageDexOptimizer.DEX_OPT_FAILED;
9743            }
9744            mPackageUsage.maybeWriteAsync(mPackages);
9745            mCompilerStats.maybeWriteAsync();
9746        }
9747        long callingId = Binder.clearCallingIdentity();
9748        try {
9749            synchronized (mInstallLock) {
9750                return performDexOptInternalWithDependenciesLI(p, options);
9751            }
9752        } finally {
9753            Binder.restoreCallingIdentity(callingId);
9754        }
9755    }
9756
9757    public ArraySet<String> getOptimizablePackages() {
9758        ArraySet<String> pkgs = new ArraySet<String>();
9759        synchronized (mPackages) {
9760            for (PackageParser.Package p : mPackages.values()) {
9761                if (PackageDexOptimizer.canOptimizePackage(p)) {
9762                    pkgs.add(p.packageName);
9763                }
9764            }
9765        }
9766        return pkgs;
9767    }
9768
9769    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9770            DexoptOptions options) {
9771        // Select the dex optimizer based on the force parameter.
9772        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9773        //       allocate an object here.
9774        PackageDexOptimizer pdo = options.isForce()
9775                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9776                : mPackageDexOptimizer;
9777
9778        // Dexopt all dependencies first. Note: we ignore the return value and march on
9779        // on errors.
9780        // Note that we are going to call performDexOpt on those libraries as many times as
9781        // they are referenced in packages. When we do a batch of performDexOpt (for example
9782        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9783        // and the first package that uses the library will dexopt it. The
9784        // others will see that the compiled code for the library is up to date.
9785        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9786        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9787        if (!deps.isEmpty()) {
9788            for (PackageParser.Package depPackage : deps) {
9789                // TODO: Analyze and investigate if we (should) profile libraries.
9790                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9791                        getOrCreateCompilerPackageStats(depPackage),
9792                        true /* isUsedByOtherApps */,
9793                        options);
9794            }
9795        }
9796        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9797                getOrCreateCompilerPackageStats(p),
9798                mDexManager.isUsedByOtherApps(p.packageName), options);
9799    }
9800
9801    /**
9802     * Reconcile the information we have about the secondary dex files belonging to
9803     * {@code packagName} and the actual dex files. For all dex files that were
9804     * deleted, update the internal records and delete the generated oat files.
9805     */
9806    @Override
9807    public void reconcileSecondaryDexFiles(String packageName) {
9808        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9809            return;
9810        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9811            return;
9812        }
9813        mDexManager.reconcileSecondaryDexFiles(packageName);
9814    }
9815
9816    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9817    // a reference there.
9818    /*package*/ DexManager getDexManager() {
9819        return mDexManager;
9820    }
9821
9822    /**
9823     * Execute the background dexopt job immediately.
9824     */
9825    @Override
9826    public boolean runBackgroundDexoptJob() {
9827        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9828            return false;
9829        }
9830        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9831    }
9832
9833    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9834        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9835                || p.usesStaticLibraries != null) {
9836            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9837            Set<String> collectedNames = new HashSet<>();
9838            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9839
9840            retValue.remove(p);
9841
9842            return retValue;
9843        } else {
9844            return Collections.emptyList();
9845        }
9846    }
9847
9848    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9849            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9850        if (!collectedNames.contains(p.packageName)) {
9851            collectedNames.add(p.packageName);
9852            collected.add(p);
9853
9854            if (p.usesLibraries != null) {
9855                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9856                        null, collected, collectedNames);
9857            }
9858            if (p.usesOptionalLibraries != null) {
9859                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9860                        null, collected, collectedNames);
9861            }
9862            if (p.usesStaticLibraries != null) {
9863                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9864                        p.usesStaticLibrariesVersions, collected, collectedNames);
9865            }
9866        }
9867    }
9868
9869    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9870            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9871        final int libNameCount = libs.size();
9872        for (int i = 0; i < libNameCount; i++) {
9873            String libName = libs.get(i);
9874            int version = (versions != null && versions.length == libNameCount)
9875                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9876            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9877            if (libPkg != null) {
9878                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9879            }
9880        }
9881    }
9882
9883    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9884        synchronized (mPackages) {
9885            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9886            if (libEntry != null) {
9887                return mPackages.get(libEntry.apk);
9888            }
9889            return null;
9890        }
9891    }
9892
9893    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9894        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9895        if (versionedLib == null) {
9896            return null;
9897        }
9898        return versionedLib.get(version);
9899    }
9900
9901    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9902        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9903                pkg.staticSharedLibName);
9904        if (versionedLib == null) {
9905            return null;
9906        }
9907        int previousLibVersion = -1;
9908        final int versionCount = versionedLib.size();
9909        for (int i = 0; i < versionCount; i++) {
9910            final int libVersion = versionedLib.keyAt(i);
9911            if (libVersion < pkg.staticSharedLibVersion) {
9912                previousLibVersion = Math.max(previousLibVersion, libVersion);
9913            }
9914        }
9915        if (previousLibVersion >= 0) {
9916            return versionedLib.get(previousLibVersion);
9917        }
9918        return null;
9919    }
9920
9921    public void shutdown() {
9922        mPackageUsage.writeNow(mPackages);
9923        mCompilerStats.writeNow();
9924    }
9925
9926    @Override
9927    public void dumpProfiles(String packageName) {
9928        PackageParser.Package pkg;
9929        synchronized (mPackages) {
9930            pkg = mPackages.get(packageName);
9931            if (pkg == null) {
9932                throw new IllegalArgumentException("Unknown package: " + packageName);
9933            }
9934        }
9935        /* Only the shell, root, or the app user should be able to dump profiles. */
9936        int callingUid = Binder.getCallingUid();
9937        if (callingUid != Process.SHELL_UID &&
9938            callingUid != Process.ROOT_UID &&
9939            callingUid != pkg.applicationInfo.uid) {
9940            throw new SecurityException("dumpProfiles");
9941        }
9942
9943        synchronized (mInstallLock) {
9944            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9945            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9946            try {
9947                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9948                String codePaths = TextUtils.join(";", allCodePaths);
9949                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9950            } catch (InstallerException e) {
9951                Slog.w(TAG, "Failed to dump profiles", e);
9952            }
9953            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9954        }
9955    }
9956
9957    @Override
9958    public void forceDexOpt(String packageName) {
9959        enforceSystemOrRoot("forceDexOpt");
9960
9961        PackageParser.Package pkg;
9962        synchronized (mPackages) {
9963            pkg = mPackages.get(packageName);
9964            if (pkg == null) {
9965                throw new IllegalArgumentException("Unknown package: " + packageName);
9966            }
9967        }
9968
9969        synchronized (mInstallLock) {
9970            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9971
9972            // Whoever is calling forceDexOpt wants a compiled package.
9973            // Don't use profiles since that may cause compilation to be skipped.
9974            final int res = performDexOptInternalWithDependenciesLI(
9975                    pkg,
9976                    new DexoptOptions(packageName,
9977                            getDefaultCompilerFilter(),
9978                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9979
9980            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9981            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9982                throw new IllegalStateException("Failed to dexopt: " + res);
9983            }
9984        }
9985    }
9986
9987    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9988        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9989            Slog.w(TAG, "Unable to update from " + oldPkg.name
9990                    + " to " + newPkg.packageName
9991                    + ": old package not in system partition");
9992            return false;
9993        } else if (mPackages.get(oldPkg.name) != null) {
9994            Slog.w(TAG, "Unable to update from " + oldPkg.name
9995                    + " to " + newPkg.packageName
9996                    + ": old package still exists");
9997            return false;
9998        }
9999        return true;
10000    }
10001
10002    void removeCodePathLI(File codePath) {
10003        if (codePath.isDirectory()) {
10004            try {
10005                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10006            } catch (InstallerException e) {
10007                Slog.w(TAG, "Failed to remove code path", e);
10008            }
10009        } else {
10010            codePath.delete();
10011        }
10012    }
10013
10014    private int[] resolveUserIds(int userId) {
10015        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10016    }
10017
10018    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10019        if (pkg == null) {
10020            Slog.wtf(TAG, "Package was null!", new Throwable());
10021            return;
10022        }
10023        clearAppDataLeafLIF(pkg, userId, flags);
10024        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10025        for (int i = 0; i < childCount; i++) {
10026            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10027        }
10028    }
10029
10030    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10031        final PackageSetting ps;
10032        synchronized (mPackages) {
10033            ps = mSettings.mPackages.get(pkg.packageName);
10034        }
10035        for (int realUserId : resolveUserIds(userId)) {
10036            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10037            try {
10038                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10039                        ceDataInode);
10040            } catch (InstallerException e) {
10041                Slog.w(TAG, String.valueOf(e));
10042            }
10043        }
10044    }
10045
10046    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10047        if (pkg == null) {
10048            Slog.wtf(TAG, "Package was null!", new Throwable());
10049            return;
10050        }
10051        destroyAppDataLeafLIF(pkg, userId, flags);
10052        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10053        for (int i = 0; i < childCount; i++) {
10054            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10055        }
10056    }
10057
10058    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10059        final PackageSetting ps;
10060        synchronized (mPackages) {
10061            ps = mSettings.mPackages.get(pkg.packageName);
10062        }
10063        for (int realUserId : resolveUserIds(userId)) {
10064            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10065            try {
10066                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10067                        ceDataInode);
10068            } catch (InstallerException e) {
10069                Slog.w(TAG, String.valueOf(e));
10070            }
10071            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10072        }
10073    }
10074
10075    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10076        if (pkg == null) {
10077            Slog.wtf(TAG, "Package was null!", new Throwable());
10078            return;
10079        }
10080        destroyAppProfilesLeafLIF(pkg);
10081        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10082        for (int i = 0; i < childCount; i++) {
10083            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10084        }
10085    }
10086
10087    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10088        try {
10089            mInstaller.destroyAppProfiles(pkg.packageName);
10090        } catch (InstallerException e) {
10091            Slog.w(TAG, String.valueOf(e));
10092        }
10093    }
10094
10095    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10096        if (pkg == null) {
10097            Slog.wtf(TAG, "Package was null!", new Throwable());
10098            return;
10099        }
10100        clearAppProfilesLeafLIF(pkg);
10101        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10102        for (int i = 0; i < childCount; i++) {
10103            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10104        }
10105    }
10106
10107    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10108        try {
10109            mInstaller.clearAppProfiles(pkg.packageName);
10110        } catch (InstallerException e) {
10111            Slog.w(TAG, String.valueOf(e));
10112        }
10113    }
10114
10115    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10116            long lastUpdateTime) {
10117        // Set parent install/update time
10118        PackageSetting ps = (PackageSetting) pkg.mExtras;
10119        if (ps != null) {
10120            ps.firstInstallTime = firstInstallTime;
10121            ps.lastUpdateTime = lastUpdateTime;
10122        }
10123        // Set children install/update time
10124        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10125        for (int i = 0; i < childCount; i++) {
10126            PackageParser.Package childPkg = pkg.childPackages.get(i);
10127            ps = (PackageSetting) childPkg.mExtras;
10128            if (ps != null) {
10129                ps.firstInstallTime = firstInstallTime;
10130                ps.lastUpdateTime = lastUpdateTime;
10131            }
10132        }
10133    }
10134
10135    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10136            PackageParser.Package changingLib) {
10137        if (file.path != null) {
10138            usesLibraryFiles.add(file.path);
10139            return;
10140        }
10141        PackageParser.Package p = mPackages.get(file.apk);
10142        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10143            // If we are doing this while in the middle of updating a library apk,
10144            // then we need to make sure to use that new apk for determining the
10145            // dependencies here.  (We haven't yet finished committing the new apk
10146            // to the package manager state.)
10147            if (p == null || p.packageName.equals(changingLib.packageName)) {
10148                p = changingLib;
10149            }
10150        }
10151        if (p != null) {
10152            usesLibraryFiles.addAll(p.getAllCodePaths());
10153            if (p.usesLibraryFiles != null) {
10154                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10155            }
10156        }
10157    }
10158
10159    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10160            PackageParser.Package changingLib) throws PackageManagerException {
10161        if (pkg == null) {
10162            return;
10163        }
10164        ArraySet<String> usesLibraryFiles = null;
10165        if (pkg.usesLibraries != null) {
10166            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10167                    null, null, pkg.packageName, changingLib, true, null);
10168        }
10169        if (pkg.usesStaticLibraries != null) {
10170            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10171                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10172                    pkg.packageName, changingLib, true, usesLibraryFiles);
10173        }
10174        if (pkg.usesOptionalLibraries != null) {
10175            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10176                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10177        }
10178        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10179            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10180        } else {
10181            pkg.usesLibraryFiles = null;
10182        }
10183    }
10184
10185    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10186            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10187            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10188            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10189            throws PackageManagerException {
10190        final int libCount = requestedLibraries.size();
10191        for (int i = 0; i < libCount; i++) {
10192            final String libName = requestedLibraries.get(i);
10193            final int libVersion = requiredVersions != null ? requiredVersions[i]
10194                    : SharedLibraryInfo.VERSION_UNDEFINED;
10195            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10196            if (libEntry == null) {
10197                if (required) {
10198                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10199                            "Package " + packageName + " requires unavailable shared library "
10200                                    + libName + "; failing!");
10201                } else if (DEBUG_SHARED_LIBRARIES) {
10202                    Slog.i(TAG, "Package " + packageName
10203                            + " desires unavailable shared library "
10204                            + libName + "; ignoring!");
10205                }
10206            } else {
10207                if (requiredVersions != null && requiredCertDigests != null) {
10208                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10209                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10210                            "Package " + packageName + " requires unavailable static shared"
10211                                    + " library " + libName + " version "
10212                                    + libEntry.info.getVersion() + "; failing!");
10213                    }
10214
10215                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10216                    if (libPkg == null) {
10217                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10218                                "Package " + packageName + " requires unavailable static shared"
10219                                        + " library; failing!");
10220                    }
10221
10222                    String expectedCertDigest = requiredCertDigests[i];
10223                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10224                                libPkg.mSignatures[0]);
10225                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10226                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10227                                "Package " + packageName + " requires differently signed" +
10228                                        " static shared library; failing!");
10229                    }
10230                }
10231
10232                if (outUsedLibraries == null) {
10233                    outUsedLibraries = new ArraySet<>();
10234                }
10235                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10236            }
10237        }
10238        return outUsedLibraries;
10239    }
10240
10241    private static boolean hasString(List<String> list, List<String> which) {
10242        if (list == null) {
10243            return false;
10244        }
10245        for (int i=list.size()-1; i>=0; i--) {
10246            for (int j=which.size()-1; j>=0; j--) {
10247                if (which.get(j).equals(list.get(i))) {
10248                    return true;
10249                }
10250            }
10251        }
10252        return false;
10253    }
10254
10255    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10256            PackageParser.Package changingPkg) {
10257        ArrayList<PackageParser.Package> res = null;
10258        for (PackageParser.Package pkg : mPackages.values()) {
10259            if (changingPkg != null
10260                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10261                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10262                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10263                            changingPkg.staticSharedLibName)) {
10264                return null;
10265            }
10266            if (res == null) {
10267                res = new ArrayList<>();
10268            }
10269            res.add(pkg);
10270            try {
10271                updateSharedLibrariesLPr(pkg, changingPkg);
10272            } catch (PackageManagerException e) {
10273                // If a system app update or an app and a required lib missing we
10274                // delete the package and for updated system apps keep the data as
10275                // it is better for the user to reinstall than to be in an limbo
10276                // state. Also libs disappearing under an app should never happen
10277                // - just in case.
10278                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10279                    final int flags = pkg.isUpdatedSystemApp()
10280                            ? PackageManager.DELETE_KEEP_DATA : 0;
10281                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10282                            flags , null, true, null);
10283                }
10284                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10285            }
10286        }
10287        return res;
10288    }
10289
10290    /**
10291     * Derive the value of the {@code cpuAbiOverride} based on the provided
10292     * value and an optional stored value from the package settings.
10293     */
10294    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10295        String cpuAbiOverride = null;
10296
10297        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10298            cpuAbiOverride = null;
10299        } else if (abiOverride != null) {
10300            cpuAbiOverride = abiOverride;
10301        } else if (settings != null) {
10302            cpuAbiOverride = settings.cpuAbiOverrideString;
10303        }
10304
10305        return cpuAbiOverride;
10306    }
10307
10308    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10309            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10310                    throws PackageManagerException {
10311        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10312        // If the package has children and this is the first dive in the function
10313        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10314        // whether all packages (parent and children) would be successfully scanned
10315        // before the actual scan since scanning mutates internal state and we want
10316        // to atomically install the package and its children.
10317        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10318            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10319                scanFlags |= SCAN_CHECK_ONLY;
10320            }
10321        } else {
10322            scanFlags &= ~SCAN_CHECK_ONLY;
10323        }
10324
10325        final PackageParser.Package scannedPkg;
10326        try {
10327            // Scan the parent
10328            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10329            // Scan the children
10330            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10331            for (int i = 0; i < childCount; i++) {
10332                PackageParser.Package childPkg = pkg.childPackages.get(i);
10333                scanPackageLI(childPkg, policyFlags,
10334                        scanFlags, currentTime, user);
10335            }
10336        } finally {
10337            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10338        }
10339
10340        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10341            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10342        }
10343
10344        return scannedPkg;
10345    }
10346
10347    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10348            int scanFlags, long currentTime, @Nullable UserHandle user)
10349                    throws PackageManagerException {
10350        boolean success = false;
10351        try {
10352            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10353                    currentTime, user);
10354            success = true;
10355            return res;
10356        } finally {
10357            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10358                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10359                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10360                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10361                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10362            }
10363        }
10364    }
10365
10366    /**
10367     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10368     */
10369    private static boolean apkHasCode(String fileName) {
10370        StrictJarFile jarFile = null;
10371        try {
10372            jarFile = new StrictJarFile(fileName,
10373                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10374            return jarFile.findEntry("classes.dex") != null;
10375        } catch (IOException ignore) {
10376        } finally {
10377            try {
10378                if (jarFile != null) {
10379                    jarFile.close();
10380                }
10381            } catch (IOException ignore) {}
10382        }
10383        return false;
10384    }
10385
10386    /**
10387     * Enforces code policy for the package. This ensures that if an APK has
10388     * declared hasCode="true" in its manifest that the APK actually contains
10389     * code.
10390     *
10391     * @throws PackageManagerException If bytecode could not be found when it should exist
10392     */
10393    private static void assertCodePolicy(PackageParser.Package pkg)
10394            throws PackageManagerException {
10395        final boolean shouldHaveCode =
10396                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10397        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10398            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10399                    "Package " + pkg.baseCodePath + " code is missing");
10400        }
10401
10402        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10403            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10404                final boolean splitShouldHaveCode =
10405                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10406                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10407                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10408                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10409                }
10410            }
10411        }
10412    }
10413
10414    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10415            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10416                    throws PackageManagerException {
10417        if (DEBUG_PACKAGE_SCANNING) {
10418            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10419                Log.d(TAG, "Scanning package " + pkg.packageName);
10420        }
10421
10422        applyPolicy(pkg, policyFlags);
10423
10424        assertPackageIsValid(pkg, policyFlags, scanFlags);
10425
10426        // Initialize package source and resource directories
10427        final File scanFile = new File(pkg.codePath);
10428        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10429        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10430
10431        SharedUserSetting suid = null;
10432        PackageSetting pkgSetting = null;
10433
10434        // Getting the package setting may have a side-effect, so if we
10435        // are only checking if scan would succeed, stash a copy of the
10436        // old setting to restore at the end.
10437        PackageSetting nonMutatedPs = null;
10438
10439        // We keep references to the derived CPU Abis from settings in oder to reuse
10440        // them in the case where we're not upgrading or booting for the first time.
10441        String primaryCpuAbiFromSettings = null;
10442        String secondaryCpuAbiFromSettings = null;
10443
10444        // writer
10445        synchronized (mPackages) {
10446            if (pkg.mSharedUserId != null) {
10447                // SIDE EFFECTS; may potentially allocate a new shared user
10448                suid = mSettings.getSharedUserLPw(
10449                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10450                if (DEBUG_PACKAGE_SCANNING) {
10451                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10452                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10453                                + "): packages=" + suid.packages);
10454                }
10455            }
10456
10457            // Check if we are renaming from an original package name.
10458            PackageSetting origPackage = null;
10459            String realName = null;
10460            if (pkg.mOriginalPackages != null) {
10461                // This package may need to be renamed to a previously
10462                // installed name.  Let's check on that...
10463                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10464                if (pkg.mOriginalPackages.contains(renamed)) {
10465                    // This package had originally been installed as the
10466                    // original name, and we have already taken care of
10467                    // transitioning to the new one.  Just update the new
10468                    // one to continue using the old name.
10469                    realName = pkg.mRealPackage;
10470                    if (!pkg.packageName.equals(renamed)) {
10471                        // Callers into this function may have already taken
10472                        // care of renaming the package; only do it here if
10473                        // it is not already done.
10474                        pkg.setPackageName(renamed);
10475                    }
10476                } else {
10477                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10478                        if ((origPackage = mSettings.getPackageLPr(
10479                                pkg.mOriginalPackages.get(i))) != null) {
10480                            // We do have the package already installed under its
10481                            // original name...  should we use it?
10482                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10483                                // New package is not compatible with original.
10484                                origPackage = null;
10485                                continue;
10486                            } else if (origPackage.sharedUser != null) {
10487                                // Make sure uid is compatible between packages.
10488                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10489                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10490                                            + " to " + pkg.packageName + ": old uid "
10491                                            + origPackage.sharedUser.name
10492                                            + " differs from " + pkg.mSharedUserId);
10493                                    origPackage = null;
10494                                    continue;
10495                                }
10496                                // TODO: Add case when shared user id is added [b/28144775]
10497                            } else {
10498                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10499                                        + pkg.packageName + " to old name " + origPackage.name);
10500                            }
10501                            break;
10502                        }
10503                    }
10504                }
10505            }
10506
10507            if (mTransferedPackages.contains(pkg.packageName)) {
10508                Slog.w(TAG, "Package " + pkg.packageName
10509                        + " was transferred to another, but its .apk remains");
10510            }
10511
10512            // See comments in nonMutatedPs declaration
10513            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10514                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10515                if (foundPs != null) {
10516                    nonMutatedPs = new PackageSetting(foundPs);
10517                }
10518            }
10519
10520            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10521                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10522                if (foundPs != null) {
10523                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10524                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10525                }
10526            }
10527
10528            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10529            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10530                PackageManagerService.reportSettingsProblem(Log.WARN,
10531                        "Package " + pkg.packageName + " shared user changed from "
10532                                + (pkgSetting.sharedUser != null
10533                                        ? pkgSetting.sharedUser.name : "<nothing>")
10534                                + " to "
10535                                + (suid != null ? suid.name : "<nothing>")
10536                                + "; replacing with new");
10537                pkgSetting = null;
10538            }
10539            final PackageSetting oldPkgSetting =
10540                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10541            final PackageSetting disabledPkgSetting =
10542                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10543
10544            String[] usesStaticLibraries = null;
10545            if (pkg.usesStaticLibraries != null) {
10546                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10547                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10548            }
10549
10550            if (pkgSetting == null) {
10551                final String parentPackageName = (pkg.parentPackage != null)
10552                        ? pkg.parentPackage.packageName : null;
10553                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10554                // REMOVE SharedUserSetting from method; update in a separate call
10555                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10556                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10557                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10558                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10559                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10560                        true /*allowInstall*/, instantApp, parentPackageName,
10561                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10562                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10563                // SIDE EFFECTS; updates system state; move elsewhere
10564                if (origPackage != null) {
10565                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10566                }
10567                mSettings.addUserToSettingLPw(pkgSetting);
10568            } else {
10569                // REMOVE SharedUserSetting from method; update in a separate call.
10570                //
10571                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10572                // secondaryCpuAbi are not known at this point so we always update them
10573                // to null here, only to reset them at a later point.
10574                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10575                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10576                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10577                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10578                        UserManagerService.getInstance(), usesStaticLibraries,
10579                        pkg.usesStaticLibrariesVersions);
10580            }
10581            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10582            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10583
10584            // SIDE EFFECTS; modifies system state; move elsewhere
10585            if (pkgSetting.origPackage != null) {
10586                // If we are first transitioning from an original package,
10587                // fix up the new package's name now.  We need to do this after
10588                // looking up the package under its new name, so getPackageLP
10589                // can take care of fiddling things correctly.
10590                pkg.setPackageName(origPackage.name);
10591
10592                // File a report about this.
10593                String msg = "New package " + pkgSetting.realName
10594                        + " renamed to replace old package " + pkgSetting.name;
10595                reportSettingsProblem(Log.WARN, msg);
10596
10597                // Make a note of it.
10598                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10599                    mTransferedPackages.add(origPackage.name);
10600                }
10601
10602                // No longer need to retain this.
10603                pkgSetting.origPackage = null;
10604            }
10605
10606            // SIDE EFFECTS; modifies system state; move elsewhere
10607            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10608                // Make a note of it.
10609                mTransferedPackages.add(pkg.packageName);
10610            }
10611
10612            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10613                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10614            }
10615
10616            if ((scanFlags & SCAN_BOOTING) == 0
10617                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10618                // Check all shared libraries and map to their actual file path.
10619                // We only do this here for apps not on a system dir, because those
10620                // are the only ones that can fail an install due to this.  We
10621                // will take care of the system apps by updating all of their
10622                // library paths after the scan is done. Also during the initial
10623                // scan don't update any libs as we do this wholesale after all
10624                // apps are scanned to avoid dependency based scanning.
10625                updateSharedLibrariesLPr(pkg, null);
10626            }
10627
10628            if (mFoundPolicyFile) {
10629                SELinuxMMAC.assignSeInfoValue(pkg);
10630            }
10631            pkg.applicationInfo.uid = pkgSetting.appId;
10632            pkg.mExtras = pkgSetting;
10633
10634
10635            // Static shared libs have same package with different versions where
10636            // we internally use a synthetic package name to allow multiple versions
10637            // of the same package, therefore we need to compare signatures against
10638            // the package setting for the latest library version.
10639            PackageSetting signatureCheckPs = pkgSetting;
10640            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10641                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10642                if (libraryEntry != null) {
10643                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10644                }
10645            }
10646
10647            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10648                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10649                    // We just determined the app is signed correctly, so bring
10650                    // over the latest parsed certs.
10651                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10652                } else {
10653                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10654                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10655                                "Package " + pkg.packageName + " upgrade keys do not match the "
10656                                + "previously installed version");
10657                    } else {
10658                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10659                        String msg = "System package " + pkg.packageName
10660                                + " signature changed; retaining data.";
10661                        reportSettingsProblem(Log.WARN, msg);
10662                    }
10663                }
10664            } else {
10665                try {
10666                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10667                    verifySignaturesLP(signatureCheckPs, pkg);
10668                    // We just determined the app is signed correctly, so bring
10669                    // over the latest parsed certs.
10670                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10671                } catch (PackageManagerException e) {
10672                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10673                        throw e;
10674                    }
10675                    // The signature has changed, but this package is in the system
10676                    // image...  let's recover!
10677                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10678                    // However...  if this package is part of a shared user, but it
10679                    // doesn't match the signature of the shared user, let's fail.
10680                    // What this means is that you can't change the signatures
10681                    // associated with an overall shared user, which doesn't seem all
10682                    // that unreasonable.
10683                    if (signatureCheckPs.sharedUser != null) {
10684                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10685                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10686                            throw new PackageManagerException(
10687                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10688                                    "Signature mismatch for shared user: "
10689                                            + pkgSetting.sharedUser);
10690                        }
10691                    }
10692                    // File a report about this.
10693                    String msg = "System package " + pkg.packageName
10694                            + " signature changed; retaining data.";
10695                    reportSettingsProblem(Log.WARN, msg);
10696                }
10697            }
10698
10699            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10700                // This package wants to adopt ownership of permissions from
10701                // another package.
10702                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10703                    final String origName = pkg.mAdoptPermissions.get(i);
10704                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10705                    if (orig != null) {
10706                        if (verifyPackageUpdateLPr(orig, pkg)) {
10707                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10708                                    + pkg.packageName);
10709                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10710                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10711                        }
10712                    }
10713                }
10714            }
10715        }
10716
10717        pkg.applicationInfo.processName = fixProcessName(
10718                pkg.applicationInfo.packageName,
10719                pkg.applicationInfo.processName);
10720
10721        if (pkg != mPlatformPackage) {
10722            // Get all of our default paths setup
10723            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10724        }
10725
10726        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10727
10728        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10729            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10730                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10731                final boolean extractNativeLibs = !pkg.isLibrary();
10732                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10733                        mAppLib32InstallDir);
10734                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10735
10736                // Some system apps still use directory structure for native libraries
10737                // in which case we might end up not detecting abi solely based on apk
10738                // structure. Try to detect abi based on directory structure.
10739                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10740                        pkg.applicationInfo.primaryCpuAbi == null) {
10741                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10742                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10743                }
10744            } else {
10745                // This is not a first boot or an upgrade, don't bother deriving the
10746                // ABI during the scan. Instead, trust the value that was stored in the
10747                // package setting.
10748                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10749                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10750
10751                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10752
10753                if (DEBUG_ABI_SELECTION) {
10754                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10755                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10756                        pkg.applicationInfo.secondaryCpuAbi);
10757                }
10758            }
10759        } else {
10760            if ((scanFlags & SCAN_MOVE) != 0) {
10761                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10762                // but we already have this packages package info in the PackageSetting. We just
10763                // use that and derive the native library path based on the new codepath.
10764                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10765                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10766            }
10767
10768            // Set native library paths again. For moves, the path will be updated based on the
10769            // ABIs we've determined above. For non-moves, the path will be updated based on the
10770            // ABIs we determined during compilation, but the path will depend on the final
10771            // package path (after the rename away from the stage path).
10772            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10773        }
10774
10775        // This is a special case for the "system" package, where the ABI is
10776        // dictated by the zygote configuration (and init.rc). We should keep track
10777        // of this ABI so that we can deal with "normal" applications that run under
10778        // the same UID correctly.
10779        if (mPlatformPackage == pkg) {
10780            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10781                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10782        }
10783
10784        // If there's a mismatch between the abi-override in the package setting
10785        // and the abiOverride specified for the install. Warn about this because we
10786        // would've already compiled the app without taking the package setting into
10787        // account.
10788        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10789            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10790                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10791                        " for package " + pkg.packageName);
10792            }
10793        }
10794
10795        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10796        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10797        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10798
10799        // Copy the derived override back to the parsed package, so that we can
10800        // update the package settings accordingly.
10801        pkg.cpuAbiOverride = cpuAbiOverride;
10802
10803        if (DEBUG_ABI_SELECTION) {
10804            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10805                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10806                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10807        }
10808
10809        // Push the derived path down into PackageSettings so we know what to
10810        // clean up at uninstall time.
10811        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10812
10813        if (DEBUG_ABI_SELECTION) {
10814            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10815                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10816                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10817        }
10818
10819        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10820        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10821            // We don't do this here during boot because we can do it all
10822            // at once after scanning all existing packages.
10823            //
10824            // We also do this *before* we perform dexopt on this package, so that
10825            // we can avoid redundant dexopts, and also to make sure we've got the
10826            // code and package path correct.
10827            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10828        }
10829
10830        if (mFactoryTest && pkg.requestedPermissions.contains(
10831                android.Manifest.permission.FACTORY_TEST)) {
10832            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10833        }
10834
10835        if (isSystemApp(pkg)) {
10836            pkgSetting.isOrphaned = true;
10837        }
10838
10839        // Take care of first install / last update times.
10840        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10841        if (currentTime != 0) {
10842            if (pkgSetting.firstInstallTime == 0) {
10843                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10844            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10845                pkgSetting.lastUpdateTime = currentTime;
10846            }
10847        } else if (pkgSetting.firstInstallTime == 0) {
10848            // We need *something*.  Take time time stamp of the file.
10849            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10850        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10851            if (scanFileTime != pkgSetting.timeStamp) {
10852                // A package on the system image has changed; consider this
10853                // to be an update.
10854                pkgSetting.lastUpdateTime = scanFileTime;
10855            }
10856        }
10857        pkgSetting.setTimeStamp(scanFileTime);
10858
10859        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10860            if (nonMutatedPs != null) {
10861                synchronized (mPackages) {
10862                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10863                }
10864            }
10865        } else {
10866            final int userId = user == null ? 0 : user.getIdentifier();
10867            // Modify state for the given package setting
10868            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10869                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10870            if (pkgSetting.getInstantApp(userId)) {
10871                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10872            }
10873        }
10874        return pkg;
10875    }
10876
10877    /**
10878     * Applies policy to the parsed package based upon the given policy flags.
10879     * Ensures the package is in a good state.
10880     * <p>
10881     * Implementation detail: This method must NOT have any side effect. It would
10882     * ideally be static, but, it requires locks to read system state.
10883     */
10884    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10885        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10886            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10887            if (pkg.applicationInfo.isDirectBootAware()) {
10888                // we're direct boot aware; set for all components
10889                for (PackageParser.Service s : pkg.services) {
10890                    s.info.encryptionAware = s.info.directBootAware = true;
10891                }
10892                for (PackageParser.Provider p : pkg.providers) {
10893                    p.info.encryptionAware = p.info.directBootAware = true;
10894                }
10895                for (PackageParser.Activity a : pkg.activities) {
10896                    a.info.encryptionAware = a.info.directBootAware = true;
10897                }
10898                for (PackageParser.Activity r : pkg.receivers) {
10899                    r.info.encryptionAware = r.info.directBootAware = true;
10900                }
10901            }
10902            if (compressedFileExists(pkg.baseCodePath)) {
10903                pkg.isStub = true;
10904            }
10905        } else {
10906            // Only allow system apps to be flagged as core apps.
10907            pkg.coreApp = false;
10908            // clear flags not applicable to regular apps
10909            pkg.applicationInfo.privateFlags &=
10910                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10911            pkg.applicationInfo.privateFlags &=
10912                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10913        }
10914        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10915
10916        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10917            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10918        }
10919
10920        if (!isSystemApp(pkg)) {
10921            // Only system apps can use these features.
10922            pkg.mOriginalPackages = null;
10923            pkg.mRealPackage = null;
10924            pkg.mAdoptPermissions = null;
10925        }
10926    }
10927
10928    /**
10929     * Asserts the parsed package is valid according to the given policy. If the
10930     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10931     * <p>
10932     * Implementation detail: This method must NOT have any side effects. It would
10933     * ideally be static, but, it requires locks to read system state.
10934     *
10935     * @throws PackageManagerException If the package fails any of the validation checks
10936     */
10937    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10938            throws PackageManagerException {
10939        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10940            assertCodePolicy(pkg);
10941        }
10942
10943        if (pkg.applicationInfo.getCodePath() == null ||
10944                pkg.applicationInfo.getResourcePath() == null) {
10945            // Bail out. The resource and code paths haven't been set.
10946            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10947                    "Code and resource paths haven't been set correctly");
10948        }
10949
10950        // Make sure we're not adding any bogus keyset info
10951        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10952        ksms.assertScannedPackageValid(pkg);
10953
10954        synchronized (mPackages) {
10955            // The special "android" package can only be defined once
10956            if (pkg.packageName.equals("android")) {
10957                if (mAndroidApplication != null) {
10958                    Slog.w(TAG, "*************************************************");
10959                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10960                    Slog.w(TAG, " codePath=" + pkg.codePath);
10961                    Slog.w(TAG, "*************************************************");
10962                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10963                            "Core android package being redefined.  Skipping.");
10964                }
10965            }
10966
10967            // A package name must be unique; don't allow duplicates
10968            if (mPackages.containsKey(pkg.packageName)) {
10969                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10970                        "Application package " + pkg.packageName
10971                        + " already installed.  Skipping duplicate.");
10972            }
10973
10974            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10975                // Static libs have a synthetic package name containing the version
10976                // but we still want the base name to be unique.
10977                if (mPackages.containsKey(pkg.manifestPackageName)) {
10978                    throw new PackageManagerException(
10979                            "Duplicate static shared lib provider package");
10980                }
10981
10982                // Static shared libraries should have at least O target SDK
10983                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10984                    throw new PackageManagerException(
10985                            "Packages declaring static-shared libs must target O SDK or higher");
10986                }
10987
10988                // Package declaring static a shared lib cannot be instant apps
10989                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10990                    throw new PackageManagerException(
10991                            "Packages declaring static-shared libs cannot be instant apps");
10992                }
10993
10994                // Package declaring static a shared lib cannot be renamed since the package
10995                // name is synthetic and apps can't code around package manager internals.
10996                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10997                    throw new PackageManagerException(
10998                            "Packages declaring static-shared libs cannot be renamed");
10999                }
11000
11001                // Package declaring static a shared lib cannot declare child packages
11002                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11003                    throw new PackageManagerException(
11004                            "Packages declaring static-shared libs cannot have child packages");
11005                }
11006
11007                // Package declaring static a shared lib cannot declare dynamic libs
11008                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11009                    throw new PackageManagerException(
11010                            "Packages declaring static-shared libs cannot declare dynamic libs");
11011                }
11012
11013                // Package declaring static a shared lib cannot declare shared users
11014                if (pkg.mSharedUserId != null) {
11015                    throw new PackageManagerException(
11016                            "Packages declaring static-shared libs cannot declare shared users");
11017                }
11018
11019                // Static shared libs cannot declare activities
11020                if (!pkg.activities.isEmpty()) {
11021                    throw new PackageManagerException(
11022                            "Static shared libs cannot declare activities");
11023                }
11024
11025                // Static shared libs cannot declare services
11026                if (!pkg.services.isEmpty()) {
11027                    throw new PackageManagerException(
11028                            "Static shared libs cannot declare services");
11029                }
11030
11031                // Static shared libs cannot declare providers
11032                if (!pkg.providers.isEmpty()) {
11033                    throw new PackageManagerException(
11034                            "Static shared libs cannot declare content providers");
11035                }
11036
11037                // Static shared libs cannot declare receivers
11038                if (!pkg.receivers.isEmpty()) {
11039                    throw new PackageManagerException(
11040                            "Static shared libs cannot declare broadcast receivers");
11041                }
11042
11043                // Static shared libs cannot declare permission groups
11044                if (!pkg.permissionGroups.isEmpty()) {
11045                    throw new PackageManagerException(
11046                            "Static shared libs cannot declare permission groups");
11047                }
11048
11049                // Static shared libs cannot declare permissions
11050                if (!pkg.permissions.isEmpty()) {
11051                    throw new PackageManagerException(
11052                            "Static shared libs cannot declare permissions");
11053                }
11054
11055                // Static shared libs cannot declare protected broadcasts
11056                if (pkg.protectedBroadcasts != null) {
11057                    throw new PackageManagerException(
11058                            "Static shared libs cannot declare protected broadcasts");
11059                }
11060
11061                // Static shared libs cannot be overlay targets
11062                if (pkg.mOverlayTarget != null) {
11063                    throw new PackageManagerException(
11064                            "Static shared libs cannot be overlay targets");
11065                }
11066
11067                // The version codes must be ordered as lib versions
11068                int minVersionCode = Integer.MIN_VALUE;
11069                int maxVersionCode = Integer.MAX_VALUE;
11070
11071                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11072                        pkg.staticSharedLibName);
11073                if (versionedLib != null) {
11074                    final int versionCount = versionedLib.size();
11075                    for (int i = 0; i < versionCount; i++) {
11076                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11077                        final int libVersionCode = libInfo.getDeclaringPackage()
11078                                .getVersionCode();
11079                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11080                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11081                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11082                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11083                        } else {
11084                            minVersionCode = maxVersionCode = libVersionCode;
11085                            break;
11086                        }
11087                    }
11088                }
11089                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11090                    throw new PackageManagerException("Static shared"
11091                            + " lib version codes must be ordered as lib versions");
11092                }
11093            }
11094
11095            // Only privileged apps and updated privileged apps can add child packages.
11096            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11097                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11098                    throw new PackageManagerException("Only privileged apps can add child "
11099                            + "packages. Ignoring package " + pkg.packageName);
11100                }
11101                final int childCount = pkg.childPackages.size();
11102                for (int i = 0; i < childCount; i++) {
11103                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11104                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11105                            childPkg.packageName)) {
11106                        throw new PackageManagerException("Can't override child of "
11107                                + "another disabled app. Ignoring package " + pkg.packageName);
11108                    }
11109                }
11110            }
11111
11112            // If we're only installing presumed-existing packages, require that the
11113            // scanned APK is both already known and at the path previously established
11114            // for it.  Previously unknown packages we pick up normally, but if we have an
11115            // a priori expectation about this package's install presence, enforce it.
11116            // With a singular exception for new system packages. When an OTA contains
11117            // a new system package, we allow the codepath to change from a system location
11118            // to the user-installed location. If we don't allow this change, any newer,
11119            // user-installed version of the application will be ignored.
11120            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11121                if (mExpectingBetter.containsKey(pkg.packageName)) {
11122                    logCriticalInfo(Log.WARN,
11123                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11124                } else {
11125                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11126                    if (known != null) {
11127                        if (DEBUG_PACKAGE_SCANNING) {
11128                            Log.d(TAG, "Examining " + pkg.codePath
11129                                    + " and requiring known paths " + known.codePathString
11130                                    + " & " + known.resourcePathString);
11131                        }
11132                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11133                                || !pkg.applicationInfo.getResourcePath().equals(
11134                                        known.resourcePathString)) {
11135                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11136                                    "Application package " + pkg.packageName
11137                                    + " found at " + pkg.applicationInfo.getCodePath()
11138                                    + " but expected at " + known.codePathString
11139                                    + "; ignoring.");
11140                        }
11141                    }
11142                }
11143            }
11144
11145            // Verify that this new package doesn't have any content providers
11146            // that conflict with existing packages.  Only do this if the
11147            // package isn't already installed, since we don't want to break
11148            // things that are installed.
11149            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11150                final int N = pkg.providers.size();
11151                int i;
11152                for (i=0; i<N; i++) {
11153                    PackageParser.Provider p = pkg.providers.get(i);
11154                    if (p.info.authority != null) {
11155                        String names[] = p.info.authority.split(";");
11156                        for (int j = 0; j < names.length; j++) {
11157                            if (mProvidersByAuthority.containsKey(names[j])) {
11158                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11159                                final String otherPackageName =
11160                                        ((other != null && other.getComponentName() != null) ?
11161                                                other.getComponentName().getPackageName() : "?");
11162                                throw new PackageManagerException(
11163                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11164                                        "Can't install because provider name " + names[j]
11165                                                + " (in package " + pkg.applicationInfo.packageName
11166                                                + ") is already used by " + otherPackageName);
11167                            }
11168                        }
11169                    }
11170                }
11171            }
11172        }
11173    }
11174
11175    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11176            int type, String declaringPackageName, int declaringVersionCode) {
11177        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11178        if (versionedLib == null) {
11179            versionedLib = new SparseArray<>();
11180            mSharedLibraries.put(name, versionedLib);
11181            if (type == SharedLibraryInfo.TYPE_STATIC) {
11182                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11183            }
11184        } else if (versionedLib.indexOfKey(version) >= 0) {
11185            return false;
11186        }
11187        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11188                version, type, declaringPackageName, declaringVersionCode);
11189        versionedLib.put(version, libEntry);
11190        return true;
11191    }
11192
11193    private boolean removeSharedLibraryLPw(String name, int version) {
11194        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11195        if (versionedLib == null) {
11196            return false;
11197        }
11198        final int libIdx = versionedLib.indexOfKey(version);
11199        if (libIdx < 0) {
11200            return false;
11201        }
11202        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11203        versionedLib.remove(version);
11204        if (versionedLib.size() <= 0) {
11205            mSharedLibraries.remove(name);
11206            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11207                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11208                        .getPackageName());
11209            }
11210        }
11211        return true;
11212    }
11213
11214    /**
11215     * Adds a scanned package to the system. When this method is finished, the package will
11216     * be available for query, resolution, etc...
11217     */
11218    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11219            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11220        final String pkgName = pkg.packageName;
11221        if (mCustomResolverComponentName != null &&
11222                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11223            setUpCustomResolverActivity(pkg);
11224        }
11225
11226        if (pkg.packageName.equals("android")) {
11227            synchronized (mPackages) {
11228                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11229                    // Set up information for our fall-back user intent resolution activity.
11230                    mPlatformPackage = pkg;
11231                    pkg.mVersionCode = mSdkVersion;
11232                    mAndroidApplication = pkg.applicationInfo;
11233                    if (!mResolverReplaced) {
11234                        mResolveActivity.applicationInfo = mAndroidApplication;
11235                        mResolveActivity.name = ResolverActivity.class.getName();
11236                        mResolveActivity.packageName = mAndroidApplication.packageName;
11237                        mResolveActivity.processName = "system:ui";
11238                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11239                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11240                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11241                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11242                        mResolveActivity.exported = true;
11243                        mResolveActivity.enabled = true;
11244                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11245                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11246                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11247                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11248                                | ActivityInfo.CONFIG_ORIENTATION
11249                                | ActivityInfo.CONFIG_KEYBOARD
11250                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11251                        mResolveInfo.activityInfo = mResolveActivity;
11252                        mResolveInfo.priority = 0;
11253                        mResolveInfo.preferredOrder = 0;
11254                        mResolveInfo.match = 0;
11255                        mResolveComponentName = new ComponentName(
11256                                mAndroidApplication.packageName, mResolveActivity.name);
11257                    }
11258                }
11259            }
11260        }
11261
11262        ArrayList<PackageParser.Package> clientLibPkgs = null;
11263        // writer
11264        synchronized (mPackages) {
11265            boolean hasStaticSharedLibs = false;
11266
11267            // Any app can add new static shared libraries
11268            if (pkg.staticSharedLibName != null) {
11269                // Static shared libs don't allow renaming as they have synthetic package
11270                // names to allow install of multiple versions, so use name from manifest.
11271                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11272                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11273                        pkg.manifestPackageName, pkg.mVersionCode)) {
11274                    hasStaticSharedLibs = true;
11275                } else {
11276                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11277                                + pkg.staticSharedLibName + " already exists; skipping");
11278                }
11279                // Static shared libs cannot be updated once installed since they
11280                // use synthetic package name which includes the version code, so
11281                // not need to update other packages's shared lib dependencies.
11282            }
11283
11284            if (!hasStaticSharedLibs
11285                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11286                // Only system apps can add new dynamic shared libraries.
11287                if (pkg.libraryNames != null) {
11288                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11289                        String name = pkg.libraryNames.get(i);
11290                        boolean allowed = false;
11291                        if (pkg.isUpdatedSystemApp()) {
11292                            // New library entries can only be added through the
11293                            // system image.  This is important to get rid of a lot
11294                            // of nasty edge cases: for example if we allowed a non-
11295                            // system update of the app to add a library, then uninstalling
11296                            // the update would make the library go away, and assumptions
11297                            // we made such as through app install filtering would now
11298                            // have allowed apps on the device which aren't compatible
11299                            // with it.  Better to just have the restriction here, be
11300                            // conservative, and create many fewer cases that can negatively
11301                            // impact the user experience.
11302                            final PackageSetting sysPs = mSettings
11303                                    .getDisabledSystemPkgLPr(pkg.packageName);
11304                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11305                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11306                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11307                                        allowed = true;
11308                                        break;
11309                                    }
11310                                }
11311                            }
11312                        } else {
11313                            allowed = true;
11314                        }
11315                        if (allowed) {
11316                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11317                                    SharedLibraryInfo.VERSION_UNDEFINED,
11318                                    SharedLibraryInfo.TYPE_DYNAMIC,
11319                                    pkg.packageName, pkg.mVersionCode)) {
11320                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11321                                        + name + " already exists; skipping");
11322                            }
11323                        } else {
11324                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11325                                    + name + " that is not declared on system image; skipping");
11326                        }
11327                    }
11328
11329                    if ((scanFlags & SCAN_BOOTING) == 0) {
11330                        // If we are not booting, we need to update any applications
11331                        // that are clients of our shared library.  If we are booting,
11332                        // this will all be done once the scan is complete.
11333                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11334                    }
11335                }
11336            }
11337        }
11338
11339        if ((scanFlags & SCAN_BOOTING) != 0) {
11340            // No apps can run during boot scan, so they don't need to be frozen
11341        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11342            // Caller asked to not kill app, so it's probably not frozen
11343        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11344            // Caller asked us to ignore frozen check for some reason; they
11345            // probably didn't know the package name
11346        } else {
11347            // We're doing major surgery on this package, so it better be frozen
11348            // right now to keep it from launching
11349            checkPackageFrozen(pkgName);
11350        }
11351
11352        // Also need to kill any apps that are dependent on the library.
11353        if (clientLibPkgs != null) {
11354            for (int i=0; i<clientLibPkgs.size(); i++) {
11355                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11356                killApplication(clientPkg.applicationInfo.packageName,
11357                        clientPkg.applicationInfo.uid, "update lib");
11358            }
11359        }
11360
11361        // writer
11362        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11363
11364        synchronized (mPackages) {
11365            // We don't expect installation to fail beyond this point
11366
11367            // Add the new setting to mSettings
11368            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11369            // Add the new setting to mPackages
11370            mPackages.put(pkg.applicationInfo.packageName, pkg);
11371            // Make sure we don't accidentally delete its data.
11372            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11373            while (iter.hasNext()) {
11374                PackageCleanItem item = iter.next();
11375                if (pkgName.equals(item.packageName)) {
11376                    iter.remove();
11377                }
11378            }
11379
11380            // Add the package's KeySets to the global KeySetManagerService
11381            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11382            ksms.addScannedPackageLPw(pkg);
11383
11384            int N = pkg.providers.size();
11385            StringBuilder r = null;
11386            int i;
11387            for (i=0; i<N; i++) {
11388                PackageParser.Provider p = pkg.providers.get(i);
11389                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11390                        p.info.processName);
11391                mProviders.addProvider(p);
11392                p.syncable = p.info.isSyncable;
11393                if (p.info.authority != null) {
11394                    String names[] = p.info.authority.split(";");
11395                    p.info.authority = null;
11396                    for (int j = 0; j < names.length; j++) {
11397                        if (j == 1 && p.syncable) {
11398                            // We only want the first authority for a provider to possibly be
11399                            // syncable, so if we already added this provider using a different
11400                            // authority clear the syncable flag. We copy the provider before
11401                            // changing it because the mProviders object contains a reference
11402                            // to a provider that we don't want to change.
11403                            // Only do this for the second authority since the resulting provider
11404                            // object can be the same for all future authorities for this provider.
11405                            p = new PackageParser.Provider(p);
11406                            p.syncable = false;
11407                        }
11408                        if (!mProvidersByAuthority.containsKey(names[j])) {
11409                            mProvidersByAuthority.put(names[j], p);
11410                            if (p.info.authority == null) {
11411                                p.info.authority = names[j];
11412                            } else {
11413                                p.info.authority = p.info.authority + ";" + names[j];
11414                            }
11415                            if (DEBUG_PACKAGE_SCANNING) {
11416                                if (chatty)
11417                                    Log.d(TAG, "Registered content provider: " + names[j]
11418                                            + ", className = " + p.info.name + ", isSyncable = "
11419                                            + p.info.isSyncable);
11420                            }
11421                        } else {
11422                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11423                            Slog.w(TAG, "Skipping provider name " + names[j] +
11424                                    " (in package " + pkg.applicationInfo.packageName +
11425                                    "): name already used by "
11426                                    + ((other != null && other.getComponentName() != null)
11427                                            ? other.getComponentName().getPackageName() : "?"));
11428                        }
11429                    }
11430                }
11431                if (chatty) {
11432                    if (r == null) {
11433                        r = new StringBuilder(256);
11434                    } else {
11435                        r.append(' ');
11436                    }
11437                    r.append(p.info.name);
11438                }
11439            }
11440            if (r != null) {
11441                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11442            }
11443
11444            N = pkg.services.size();
11445            r = null;
11446            for (i=0; i<N; i++) {
11447                PackageParser.Service s = pkg.services.get(i);
11448                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11449                        s.info.processName);
11450                mServices.addService(s);
11451                if (chatty) {
11452                    if (r == null) {
11453                        r = new StringBuilder(256);
11454                    } else {
11455                        r.append(' ');
11456                    }
11457                    r.append(s.info.name);
11458                }
11459            }
11460            if (r != null) {
11461                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11462            }
11463
11464            N = pkg.receivers.size();
11465            r = null;
11466            for (i=0; i<N; i++) {
11467                PackageParser.Activity a = pkg.receivers.get(i);
11468                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11469                        a.info.processName);
11470                mReceivers.addActivity(a, "receiver");
11471                if (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_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11482            }
11483
11484            N = pkg.activities.size();
11485            r = null;
11486            for (i=0; i<N; i++) {
11487                PackageParser.Activity a = pkg.activities.get(i);
11488                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11489                        a.info.processName);
11490                mActivities.addActivity(a, "activity");
11491                if (chatty) {
11492                    if (r == null) {
11493                        r = new StringBuilder(256);
11494                    } else {
11495                        r.append(' ');
11496                    }
11497                    r.append(a.info.name);
11498                }
11499            }
11500            if (r != null) {
11501                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11502            }
11503
11504            N = pkg.permissionGroups.size();
11505            r = null;
11506            for (i=0; i<N; i++) {
11507                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11508                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11509                final String curPackageName = cur == null ? null : cur.info.packageName;
11510                // Dont allow ephemeral apps to define new permission groups.
11511                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11512                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11513                            + pg.info.packageName
11514                            + " ignored: instant apps cannot define new permission groups.");
11515                    continue;
11516                }
11517                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11518                if (cur == null || isPackageUpdate) {
11519                    mPermissionGroups.put(pg.info.name, pg);
11520                    if (chatty) {
11521                        if (r == null) {
11522                            r = new StringBuilder(256);
11523                        } else {
11524                            r.append(' ');
11525                        }
11526                        if (isPackageUpdate) {
11527                            r.append("UPD:");
11528                        }
11529                        r.append(pg.info.name);
11530                    }
11531                } else {
11532                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11533                            + pg.info.packageName + " ignored: original from "
11534                            + cur.info.packageName);
11535                    if (chatty) {
11536                        if (r == null) {
11537                            r = new StringBuilder(256);
11538                        } else {
11539                            r.append(' ');
11540                        }
11541                        r.append("DUP:");
11542                        r.append(pg.info.name);
11543                    }
11544                }
11545            }
11546            if (r != null) {
11547                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11548            }
11549
11550            N = pkg.permissions.size();
11551            r = null;
11552            for (i=0; i<N; i++) {
11553                PackageParser.Permission p = pkg.permissions.get(i);
11554
11555                // Dont allow ephemeral apps to define new permissions.
11556                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11557                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11558                            + p.info.packageName
11559                            + " ignored: instant apps cannot define new permissions.");
11560                    continue;
11561                }
11562
11563                // Assume by default that we did not install this permission into the system.
11564                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11565
11566                // Now that permission groups have a special meaning, we ignore permission
11567                // groups for legacy apps to prevent unexpected behavior. In particular,
11568                // permissions for one app being granted to someone just because they happen
11569                // to be in a group defined by another app (before this had no implications).
11570                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11571                    p.group = mPermissionGroups.get(p.info.group);
11572                    // Warn for a permission in an unknown group.
11573                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11574                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11575                                + p.info.packageName + " in an unknown group " + p.info.group);
11576                    }
11577                }
11578
11579                ArrayMap<String, BasePermission> permissionMap =
11580                        p.tree ? mSettings.mPermissionTrees
11581                                : mSettings.mPermissions;
11582                BasePermission bp = permissionMap.get(p.info.name);
11583
11584                // Allow system apps to redefine non-system permissions
11585                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11586                    final boolean currentOwnerIsSystem = (bp.perm != null
11587                            && isSystemApp(bp.perm.owner));
11588                    if (isSystemApp(p.owner)) {
11589                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11590                            // It's a built-in permission and no owner, take ownership now
11591                            bp.packageSetting = pkgSetting;
11592                            bp.perm = p;
11593                            bp.uid = pkg.applicationInfo.uid;
11594                            bp.sourcePackage = p.info.packageName;
11595                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11596                        } else if (!currentOwnerIsSystem) {
11597                            String msg = "New decl " + p.owner + " of permission  "
11598                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11599                            reportSettingsProblem(Log.WARN, msg);
11600                            bp = null;
11601                        }
11602                    }
11603                }
11604
11605                if (bp == null) {
11606                    bp = new BasePermission(p.info.name, p.info.packageName,
11607                            BasePermission.TYPE_NORMAL);
11608                    permissionMap.put(p.info.name, bp);
11609                }
11610
11611                if (bp.perm == null) {
11612                    if (bp.sourcePackage == null
11613                            || bp.sourcePackage.equals(p.info.packageName)) {
11614                        BasePermission tree = findPermissionTreeLP(p.info.name);
11615                        if (tree == null
11616                                || tree.sourcePackage.equals(p.info.packageName)) {
11617                            bp.packageSetting = pkgSetting;
11618                            bp.perm = p;
11619                            bp.uid = pkg.applicationInfo.uid;
11620                            bp.sourcePackage = p.info.packageName;
11621                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11622                            if (chatty) {
11623                                if (r == null) {
11624                                    r = new StringBuilder(256);
11625                                } else {
11626                                    r.append(' ');
11627                                }
11628                                r.append(p.info.name);
11629                            }
11630                        } else {
11631                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11632                                    + p.info.packageName + " ignored: base tree "
11633                                    + tree.name + " is from package "
11634                                    + tree.sourcePackage);
11635                        }
11636                    } else {
11637                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11638                                + p.info.packageName + " ignored: original from "
11639                                + bp.sourcePackage);
11640                    }
11641                } else if (chatty) {
11642                    if (r == null) {
11643                        r = new StringBuilder(256);
11644                    } else {
11645                        r.append(' ');
11646                    }
11647                    r.append("DUP:");
11648                    r.append(p.info.name);
11649                }
11650                if (bp.perm == p) {
11651                    bp.protectionLevel = p.info.protectionLevel;
11652                }
11653            }
11654
11655            if (r != null) {
11656                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11657            }
11658
11659            N = pkg.instrumentation.size();
11660            r = null;
11661            for (i=0; i<N; i++) {
11662                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11663                a.info.packageName = pkg.applicationInfo.packageName;
11664                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11665                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11666                a.info.splitNames = pkg.splitNames;
11667                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11668                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11669                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11670                a.info.dataDir = pkg.applicationInfo.dataDir;
11671                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11672                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11673                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11674                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11675                mInstrumentation.put(a.getComponentName(), a);
11676                if (chatty) {
11677                    if (r == null) {
11678                        r = new StringBuilder(256);
11679                    } else {
11680                        r.append(' ');
11681                    }
11682                    r.append(a.info.name);
11683                }
11684            }
11685            if (r != null) {
11686                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11687            }
11688
11689            if (pkg.protectedBroadcasts != null) {
11690                N = pkg.protectedBroadcasts.size();
11691                synchronized (mProtectedBroadcasts) {
11692                    for (i = 0; i < N; i++) {
11693                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11694                    }
11695                }
11696            }
11697        }
11698
11699        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11700    }
11701
11702    /**
11703     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11704     * is derived purely on the basis of the contents of {@code scanFile} and
11705     * {@code cpuAbiOverride}.
11706     *
11707     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11708     */
11709    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11710                                 String cpuAbiOverride, boolean extractLibs,
11711                                 File appLib32InstallDir)
11712            throws PackageManagerException {
11713        // Give ourselves some initial paths; we'll come back for another
11714        // pass once we've determined ABI below.
11715        setNativeLibraryPaths(pkg, appLib32InstallDir);
11716
11717        // We would never need to extract libs for forward-locked and external packages,
11718        // since the container service will do it for us. We shouldn't attempt to
11719        // extract libs from system app when it was not updated.
11720        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11721                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11722            extractLibs = false;
11723        }
11724
11725        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11726        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11727
11728        NativeLibraryHelper.Handle handle = null;
11729        try {
11730            handle = NativeLibraryHelper.Handle.create(pkg);
11731            // TODO(multiArch): This can be null for apps that didn't go through the
11732            // usual installation process. We can calculate it again, like we
11733            // do during install time.
11734            //
11735            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11736            // unnecessary.
11737            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11738
11739            // Null out the abis so that they can be recalculated.
11740            pkg.applicationInfo.primaryCpuAbi = null;
11741            pkg.applicationInfo.secondaryCpuAbi = null;
11742            if (isMultiArch(pkg.applicationInfo)) {
11743                // Warn if we've set an abiOverride for multi-lib packages..
11744                // By definition, we need to copy both 32 and 64 bit libraries for
11745                // such packages.
11746                if (pkg.cpuAbiOverride != null
11747                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11748                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11749                }
11750
11751                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11752                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11753                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11754                    if (extractLibs) {
11755                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11756                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11757                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11758                                useIsaSpecificSubdirs);
11759                    } else {
11760                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11761                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11762                    }
11763                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11764                }
11765
11766                // Shared library native code should be in the APK zip aligned
11767                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11768                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11769                            "Shared library native lib extraction not supported");
11770                }
11771
11772                maybeThrowExceptionForMultiArchCopy(
11773                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11774
11775                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11776                    if (extractLibs) {
11777                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11778                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11779                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11780                                useIsaSpecificSubdirs);
11781                    } else {
11782                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11783                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11784                    }
11785                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11786                }
11787
11788                maybeThrowExceptionForMultiArchCopy(
11789                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11790
11791                if (abi64 >= 0) {
11792                    // Shared library native libs should be in the APK zip aligned
11793                    if (extractLibs && pkg.isLibrary()) {
11794                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11795                                "Shared library native lib extraction not supported");
11796                    }
11797                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11798                }
11799
11800                if (abi32 >= 0) {
11801                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11802                    if (abi64 >= 0) {
11803                        if (pkg.use32bitAbi) {
11804                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11805                            pkg.applicationInfo.primaryCpuAbi = abi;
11806                        } else {
11807                            pkg.applicationInfo.secondaryCpuAbi = abi;
11808                        }
11809                    } else {
11810                        pkg.applicationInfo.primaryCpuAbi = abi;
11811                    }
11812                }
11813            } else {
11814                String[] abiList = (cpuAbiOverride != null) ?
11815                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11816
11817                // Enable gross and lame hacks for apps that are built with old
11818                // SDK tools. We must scan their APKs for renderscript bitcode and
11819                // not launch them if it's present. Don't bother checking on devices
11820                // that don't have 64 bit support.
11821                boolean needsRenderScriptOverride = false;
11822                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11823                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11824                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11825                    needsRenderScriptOverride = true;
11826                }
11827
11828                final int copyRet;
11829                if (extractLibs) {
11830                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11831                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11832                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11833                } else {
11834                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11835                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11836                }
11837                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11838
11839                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11840                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11841                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11842                }
11843
11844                if (copyRet >= 0) {
11845                    // Shared libraries that have native libs must be multi-architecture
11846                    if (pkg.isLibrary()) {
11847                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11848                                "Shared library with native libs must be multiarch");
11849                    }
11850                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11851                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11852                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11853                } else if (needsRenderScriptOverride) {
11854                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11855                }
11856            }
11857        } catch (IOException ioe) {
11858            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11859        } finally {
11860            IoUtils.closeQuietly(handle);
11861        }
11862
11863        // Now that we've calculated the ABIs and determined if it's an internal app,
11864        // we will go ahead and populate the nativeLibraryPath.
11865        setNativeLibraryPaths(pkg, appLib32InstallDir);
11866    }
11867
11868    /**
11869     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11870     * i.e, so that all packages can be run inside a single process if required.
11871     *
11872     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11873     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11874     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11875     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11876     * updating a package that belongs to a shared user.
11877     *
11878     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11879     * adds unnecessary complexity.
11880     */
11881    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11882            PackageParser.Package scannedPackage) {
11883        String requiredInstructionSet = null;
11884        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11885            requiredInstructionSet = VMRuntime.getInstructionSet(
11886                     scannedPackage.applicationInfo.primaryCpuAbi);
11887        }
11888
11889        PackageSetting requirer = null;
11890        for (PackageSetting ps : packagesForUser) {
11891            // If packagesForUser contains scannedPackage, we skip it. This will happen
11892            // when scannedPackage is an update of an existing package. Without this check,
11893            // we will never be able to change the ABI of any package belonging to a shared
11894            // user, even if it's compatible with other packages.
11895            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11896                if (ps.primaryCpuAbiString == null) {
11897                    continue;
11898                }
11899
11900                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11901                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11902                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11903                    // this but there's not much we can do.
11904                    String errorMessage = "Instruction set mismatch, "
11905                            + ((requirer == null) ? "[caller]" : requirer)
11906                            + " requires " + requiredInstructionSet + " whereas " + ps
11907                            + " requires " + instructionSet;
11908                    Slog.w(TAG, errorMessage);
11909                }
11910
11911                if (requiredInstructionSet == null) {
11912                    requiredInstructionSet = instructionSet;
11913                    requirer = ps;
11914                }
11915            }
11916        }
11917
11918        if (requiredInstructionSet != null) {
11919            String adjustedAbi;
11920            if (requirer != null) {
11921                // requirer != null implies that either scannedPackage was null or that scannedPackage
11922                // did not require an ABI, in which case we have to adjust scannedPackage to match
11923                // the ABI of the set (which is the same as requirer's ABI)
11924                adjustedAbi = requirer.primaryCpuAbiString;
11925                if (scannedPackage != null) {
11926                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11927                }
11928            } else {
11929                // requirer == null implies that we're updating all ABIs in the set to
11930                // match scannedPackage.
11931                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11932            }
11933
11934            for (PackageSetting ps : packagesForUser) {
11935                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11936                    if (ps.primaryCpuAbiString != null) {
11937                        continue;
11938                    }
11939
11940                    ps.primaryCpuAbiString = adjustedAbi;
11941                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11942                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11943                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11944                        if (DEBUG_ABI_SELECTION) {
11945                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11946                                    + " (requirer="
11947                                    + (requirer != null ? requirer.pkg : "null")
11948                                    + ", scannedPackage="
11949                                    + (scannedPackage != null ? scannedPackage : "null")
11950                                    + ")");
11951                        }
11952                        try {
11953                            mInstaller.rmdex(ps.codePathString,
11954                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11955                        } catch (InstallerException ignored) {
11956                        }
11957                    }
11958                }
11959            }
11960        }
11961    }
11962
11963    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11964        synchronized (mPackages) {
11965            mResolverReplaced = true;
11966            // Set up information for custom user intent resolution activity.
11967            mResolveActivity.applicationInfo = pkg.applicationInfo;
11968            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11969            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11970            mResolveActivity.processName = pkg.applicationInfo.packageName;
11971            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11972            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11973                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11974            mResolveActivity.theme = 0;
11975            mResolveActivity.exported = true;
11976            mResolveActivity.enabled = true;
11977            mResolveInfo.activityInfo = mResolveActivity;
11978            mResolveInfo.priority = 0;
11979            mResolveInfo.preferredOrder = 0;
11980            mResolveInfo.match = 0;
11981            mResolveComponentName = mCustomResolverComponentName;
11982            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11983                    mResolveComponentName);
11984        }
11985    }
11986
11987    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11988        if (installerActivity == null) {
11989            if (DEBUG_EPHEMERAL) {
11990                Slog.d(TAG, "Clear ephemeral installer activity");
11991            }
11992            mInstantAppInstallerActivity = null;
11993            return;
11994        }
11995
11996        if (DEBUG_EPHEMERAL) {
11997            Slog.d(TAG, "Set ephemeral installer activity: "
11998                    + installerActivity.getComponentName());
11999        }
12000        // Set up information for ephemeral installer activity
12001        mInstantAppInstallerActivity = installerActivity;
12002        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12003                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12004        mInstantAppInstallerActivity.exported = true;
12005        mInstantAppInstallerActivity.enabled = true;
12006        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12007        mInstantAppInstallerInfo.priority = 0;
12008        mInstantAppInstallerInfo.preferredOrder = 1;
12009        mInstantAppInstallerInfo.isDefault = true;
12010        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12011                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12012    }
12013
12014    private static String calculateBundledApkRoot(final String codePathString) {
12015        final File codePath = new File(codePathString);
12016        final File codeRoot;
12017        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12018            codeRoot = Environment.getRootDirectory();
12019        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12020            codeRoot = Environment.getOemDirectory();
12021        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12022            codeRoot = Environment.getVendorDirectory();
12023        } else {
12024            // Unrecognized code path; take its top real segment as the apk root:
12025            // e.g. /something/app/blah.apk => /something
12026            try {
12027                File f = codePath.getCanonicalFile();
12028                File parent = f.getParentFile();    // non-null because codePath is a file
12029                File tmp;
12030                while ((tmp = parent.getParentFile()) != null) {
12031                    f = parent;
12032                    parent = tmp;
12033                }
12034                codeRoot = f;
12035                Slog.w(TAG, "Unrecognized code path "
12036                        + codePath + " - using " + codeRoot);
12037            } catch (IOException e) {
12038                // Can't canonicalize the code path -- shenanigans?
12039                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12040                return Environment.getRootDirectory().getPath();
12041            }
12042        }
12043        return codeRoot.getPath();
12044    }
12045
12046    /**
12047     * Derive and set the location of native libraries for the given package,
12048     * which varies depending on where and how the package was installed.
12049     */
12050    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12051        final ApplicationInfo info = pkg.applicationInfo;
12052        final String codePath = pkg.codePath;
12053        final File codeFile = new File(codePath);
12054        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12055        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12056
12057        info.nativeLibraryRootDir = null;
12058        info.nativeLibraryRootRequiresIsa = false;
12059        info.nativeLibraryDir = null;
12060        info.secondaryNativeLibraryDir = null;
12061
12062        if (isApkFile(codeFile)) {
12063            // Monolithic install
12064            if (bundledApp) {
12065                // If "/system/lib64/apkname" exists, assume that is the per-package
12066                // native library directory to use; otherwise use "/system/lib/apkname".
12067                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12068                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12069                        getPrimaryInstructionSet(info));
12070
12071                // This is a bundled system app so choose the path based on the ABI.
12072                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12073                // is just the default path.
12074                final String apkName = deriveCodePathName(codePath);
12075                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12076                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12077                        apkName).getAbsolutePath();
12078
12079                if (info.secondaryCpuAbi != null) {
12080                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12081                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12082                            secondaryLibDir, apkName).getAbsolutePath();
12083                }
12084            } else if (asecApp) {
12085                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12086                        .getAbsolutePath();
12087            } else {
12088                final String apkName = deriveCodePathName(codePath);
12089                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12090                        .getAbsolutePath();
12091            }
12092
12093            info.nativeLibraryRootRequiresIsa = false;
12094            info.nativeLibraryDir = info.nativeLibraryRootDir;
12095        } else {
12096            // Cluster install
12097            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12098            info.nativeLibraryRootRequiresIsa = true;
12099
12100            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12101                    getPrimaryInstructionSet(info)).getAbsolutePath();
12102
12103            if (info.secondaryCpuAbi != null) {
12104                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12105                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12106            }
12107        }
12108    }
12109
12110    /**
12111     * Calculate the abis and roots for a bundled app. These can uniquely
12112     * be determined from the contents of the system partition, i.e whether
12113     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12114     * of this information, and instead assume that the system was built
12115     * sensibly.
12116     */
12117    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12118                                           PackageSetting pkgSetting) {
12119        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12120
12121        // If "/system/lib64/apkname" exists, assume that is the per-package
12122        // native library directory to use; otherwise use "/system/lib/apkname".
12123        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12124        setBundledAppAbi(pkg, apkRoot, apkName);
12125        // pkgSetting might be null during rescan following uninstall of updates
12126        // to a bundled app, so accommodate that possibility.  The settings in
12127        // that case will be established later from the parsed package.
12128        //
12129        // If the settings aren't null, sync them up with what we've just derived.
12130        // note that apkRoot isn't stored in the package settings.
12131        if (pkgSetting != null) {
12132            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12133            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12134        }
12135    }
12136
12137    /**
12138     * Deduces the ABI of a bundled app and sets the relevant fields on the
12139     * parsed pkg object.
12140     *
12141     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12142     *        under which system libraries are installed.
12143     * @param apkName the name of the installed package.
12144     */
12145    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12146        final File codeFile = new File(pkg.codePath);
12147
12148        final boolean has64BitLibs;
12149        final boolean has32BitLibs;
12150        if (isApkFile(codeFile)) {
12151            // Monolithic install
12152            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12153            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12154        } else {
12155            // Cluster install
12156            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12157            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12158                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12159                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12160                has64BitLibs = (new File(rootDir, isa)).exists();
12161            } else {
12162                has64BitLibs = false;
12163            }
12164            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12165                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12166                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12167                has32BitLibs = (new File(rootDir, isa)).exists();
12168            } else {
12169                has32BitLibs = false;
12170            }
12171        }
12172
12173        if (has64BitLibs && !has32BitLibs) {
12174            // The package has 64 bit libs, but not 32 bit libs. Its primary
12175            // ABI should be 64 bit. We can safely assume here that the bundled
12176            // native libraries correspond to the most preferred ABI in the list.
12177
12178            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12179            pkg.applicationInfo.secondaryCpuAbi = null;
12180        } else if (has32BitLibs && !has64BitLibs) {
12181            // The package has 32 bit libs but not 64 bit libs. Its primary
12182            // ABI should be 32 bit.
12183
12184            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12185            pkg.applicationInfo.secondaryCpuAbi = null;
12186        } else if (has32BitLibs && has64BitLibs) {
12187            // The application has both 64 and 32 bit bundled libraries. We check
12188            // here that the app declares multiArch support, and warn if it doesn't.
12189            //
12190            // We will be lenient here and record both ABIs. The primary will be the
12191            // ABI that's higher on the list, i.e, a device that's configured to prefer
12192            // 64 bit apps will see a 64 bit primary ABI,
12193
12194            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12195                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12196            }
12197
12198            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12199                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12200                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12201            } else {
12202                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12203                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12204            }
12205        } else {
12206            pkg.applicationInfo.primaryCpuAbi = null;
12207            pkg.applicationInfo.secondaryCpuAbi = null;
12208        }
12209    }
12210
12211    private void killApplication(String pkgName, int appId, String reason) {
12212        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12213    }
12214
12215    private void killApplication(String pkgName, int appId, int userId, String reason) {
12216        // Request the ActivityManager to kill the process(only for existing packages)
12217        // so that we do not end up in a confused state while the user is still using the older
12218        // version of the application while the new one gets installed.
12219        final long token = Binder.clearCallingIdentity();
12220        try {
12221            IActivityManager am = ActivityManager.getService();
12222            if (am != null) {
12223                try {
12224                    am.killApplication(pkgName, appId, userId, reason);
12225                } catch (RemoteException e) {
12226                }
12227            }
12228        } finally {
12229            Binder.restoreCallingIdentity(token);
12230        }
12231    }
12232
12233    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12234        // Remove the parent package setting
12235        PackageSetting ps = (PackageSetting) pkg.mExtras;
12236        if (ps != null) {
12237            removePackageLI(ps, chatty);
12238        }
12239        // Remove the child package setting
12240        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12241        for (int i = 0; i < childCount; i++) {
12242            PackageParser.Package childPkg = pkg.childPackages.get(i);
12243            ps = (PackageSetting) childPkg.mExtras;
12244            if (ps != null) {
12245                removePackageLI(ps, chatty);
12246            }
12247        }
12248    }
12249
12250    void removePackageLI(PackageSetting ps, boolean chatty) {
12251        if (DEBUG_INSTALL) {
12252            if (chatty)
12253                Log.d(TAG, "Removing package " + ps.name);
12254        }
12255
12256        // writer
12257        synchronized (mPackages) {
12258            mPackages.remove(ps.name);
12259            final PackageParser.Package pkg = ps.pkg;
12260            if (pkg != null) {
12261                cleanPackageDataStructuresLILPw(pkg, chatty);
12262            }
12263        }
12264    }
12265
12266    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12267        if (DEBUG_INSTALL) {
12268            if (chatty)
12269                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12270        }
12271
12272        // writer
12273        synchronized (mPackages) {
12274            // Remove the parent package
12275            mPackages.remove(pkg.applicationInfo.packageName);
12276            cleanPackageDataStructuresLILPw(pkg, chatty);
12277
12278            // Remove the child packages
12279            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12280            for (int i = 0; i < childCount; i++) {
12281                PackageParser.Package childPkg = pkg.childPackages.get(i);
12282                mPackages.remove(childPkg.applicationInfo.packageName);
12283                cleanPackageDataStructuresLILPw(childPkg, chatty);
12284            }
12285        }
12286    }
12287
12288    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12289        int N = pkg.providers.size();
12290        StringBuilder r = null;
12291        int i;
12292        for (i=0; i<N; i++) {
12293            PackageParser.Provider p = pkg.providers.get(i);
12294            mProviders.removeProvider(p);
12295            if (p.info.authority == null) {
12296
12297                /* There was another ContentProvider with this authority when
12298                 * this app was installed so this authority is null,
12299                 * Ignore it as we don't have to unregister the provider.
12300                 */
12301                continue;
12302            }
12303            String names[] = p.info.authority.split(";");
12304            for (int j = 0; j < names.length; j++) {
12305                if (mProvidersByAuthority.get(names[j]) == p) {
12306                    mProvidersByAuthority.remove(names[j]);
12307                    if (DEBUG_REMOVE) {
12308                        if (chatty)
12309                            Log.d(TAG, "Unregistered content provider: " + names[j]
12310                                    + ", className = " + p.info.name + ", isSyncable = "
12311                                    + p.info.isSyncable);
12312                    }
12313                }
12314            }
12315            if (DEBUG_REMOVE && chatty) {
12316                if (r == null) {
12317                    r = new StringBuilder(256);
12318                } else {
12319                    r.append(' ');
12320                }
12321                r.append(p.info.name);
12322            }
12323        }
12324        if (r != null) {
12325            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12326        }
12327
12328        N = pkg.services.size();
12329        r = null;
12330        for (i=0; i<N; i++) {
12331            PackageParser.Service s = pkg.services.get(i);
12332            mServices.removeService(s);
12333            if (chatty) {
12334                if (r == null) {
12335                    r = new StringBuilder(256);
12336                } else {
12337                    r.append(' ');
12338                }
12339                r.append(s.info.name);
12340            }
12341        }
12342        if (r != null) {
12343            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12344        }
12345
12346        N = pkg.receivers.size();
12347        r = null;
12348        for (i=0; i<N; i++) {
12349            PackageParser.Activity a = pkg.receivers.get(i);
12350            mReceivers.removeActivity(a, "receiver");
12351            if (DEBUG_REMOVE && chatty) {
12352                if (r == null) {
12353                    r = new StringBuilder(256);
12354                } else {
12355                    r.append(' ');
12356                }
12357                r.append(a.info.name);
12358            }
12359        }
12360        if (r != null) {
12361            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12362        }
12363
12364        N = pkg.activities.size();
12365        r = null;
12366        for (i=0; i<N; i++) {
12367            PackageParser.Activity a = pkg.activities.get(i);
12368            mActivities.removeActivity(a, "activity");
12369            if (DEBUG_REMOVE && chatty) {
12370                if (r == null) {
12371                    r = new StringBuilder(256);
12372                } else {
12373                    r.append(' ');
12374                }
12375                r.append(a.info.name);
12376            }
12377        }
12378        if (r != null) {
12379            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12380        }
12381
12382        N = pkg.permissions.size();
12383        r = null;
12384        for (i=0; i<N; i++) {
12385            PackageParser.Permission p = pkg.permissions.get(i);
12386            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12387            if (bp == null) {
12388                bp = mSettings.mPermissionTrees.get(p.info.name);
12389            }
12390            if (bp != null && bp.perm == p) {
12391                bp.perm = null;
12392                if (DEBUG_REMOVE && chatty) {
12393                    if (r == null) {
12394                        r = new StringBuilder(256);
12395                    } else {
12396                        r.append(' ');
12397                    }
12398                    r.append(p.info.name);
12399                }
12400            }
12401            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12402                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12403                if (appOpPkgs != null) {
12404                    appOpPkgs.remove(pkg.packageName);
12405                }
12406            }
12407        }
12408        if (r != null) {
12409            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12410        }
12411
12412        N = pkg.requestedPermissions.size();
12413        r = null;
12414        for (i=0; i<N; i++) {
12415            String perm = pkg.requestedPermissions.get(i);
12416            BasePermission bp = mSettings.mPermissions.get(perm);
12417            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12418                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12419                if (appOpPkgs != null) {
12420                    appOpPkgs.remove(pkg.packageName);
12421                    if (appOpPkgs.isEmpty()) {
12422                        mAppOpPermissionPackages.remove(perm);
12423                    }
12424                }
12425            }
12426        }
12427        if (r != null) {
12428            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12429        }
12430
12431        N = pkg.instrumentation.size();
12432        r = null;
12433        for (i=0; i<N; i++) {
12434            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12435            mInstrumentation.remove(a.getComponentName());
12436            if (DEBUG_REMOVE && chatty) {
12437                if (r == null) {
12438                    r = new StringBuilder(256);
12439                } else {
12440                    r.append(' ');
12441                }
12442                r.append(a.info.name);
12443            }
12444        }
12445        if (r != null) {
12446            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12447        }
12448
12449        r = null;
12450        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12451            // Only system apps can hold shared libraries.
12452            if (pkg.libraryNames != null) {
12453                for (i = 0; i < pkg.libraryNames.size(); i++) {
12454                    String name = pkg.libraryNames.get(i);
12455                    if (removeSharedLibraryLPw(name, 0)) {
12456                        if (DEBUG_REMOVE && chatty) {
12457                            if (r == null) {
12458                                r = new StringBuilder(256);
12459                            } else {
12460                                r.append(' ');
12461                            }
12462                            r.append(name);
12463                        }
12464                    }
12465                }
12466            }
12467        }
12468
12469        r = null;
12470
12471        // Any package can hold static shared libraries.
12472        if (pkg.staticSharedLibName != null) {
12473            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12474                if (DEBUG_REMOVE && chatty) {
12475                    if (r == null) {
12476                        r = new StringBuilder(256);
12477                    } else {
12478                        r.append(' ');
12479                    }
12480                    r.append(pkg.staticSharedLibName);
12481                }
12482            }
12483        }
12484
12485        if (r != null) {
12486            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12487        }
12488    }
12489
12490    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12491        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12492            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12493                return true;
12494            }
12495        }
12496        return false;
12497    }
12498
12499    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12500    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12501    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12502
12503    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12504        // Update the parent permissions
12505        updatePermissionsLPw(pkg.packageName, pkg, flags);
12506        // Update the child permissions
12507        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12508        for (int i = 0; i < childCount; i++) {
12509            PackageParser.Package childPkg = pkg.childPackages.get(i);
12510            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12511        }
12512    }
12513
12514    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12515            int flags) {
12516        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12517        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12518    }
12519
12520    private void updatePermissionsLPw(String changingPkg,
12521            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12522        // Make sure there are no dangling permission trees.
12523        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12524        while (it.hasNext()) {
12525            final BasePermission bp = it.next();
12526            if (bp.packageSetting == null) {
12527                // We may not yet have parsed the package, so just see if
12528                // we still know about its settings.
12529                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12530            }
12531            if (bp.packageSetting == null) {
12532                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12533                        + " from package " + bp.sourcePackage);
12534                it.remove();
12535            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12536                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12537                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12538                            + " from package " + bp.sourcePackage);
12539                    flags |= UPDATE_PERMISSIONS_ALL;
12540                    it.remove();
12541                }
12542            }
12543        }
12544
12545        // Make sure all dynamic permissions have been assigned to a package,
12546        // and make sure there are no dangling permissions.
12547        it = mSettings.mPermissions.values().iterator();
12548        while (it.hasNext()) {
12549            final BasePermission bp = it.next();
12550            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12551                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12552                        + bp.name + " pkg=" + bp.sourcePackage
12553                        + " info=" + bp.pendingInfo);
12554                if (bp.packageSetting == null && bp.pendingInfo != null) {
12555                    final BasePermission tree = findPermissionTreeLP(bp.name);
12556                    if (tree != null && tree.perm != null) {
12557                        bp.packageSetting = tree.packageSetting;
12558                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12559                                new PermissionInfo(bp.pendingInfo));
12560                        bp.perm.info.packageName = tree.perm.info.packageName;
12561                        bp.perm.info.name = bp.name;
12562                        bp.uid = tree.uid;
12563                    }
12564                }
12565            }
12566            if (bp.packageSetting == null) {
12567                // We may not yet have parsed the package, so just see if
12568                // we still know about its settings.
12569                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12570            }
12571            if (bp.packageSetting == null) {
12572                Slog.w(TAG, "Removing dangling permission: " + bp.name
12573                        + " from package " + bp.sourcePackage);
12574                it.remove();
12575            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12576                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12577                    Slog.i(TAG, "Removing old permission: " + bp.name
12578                            + " from package " + bp.sourcePackage);
12579                    flags |= UPDATE_PERMISSIONS_ALL;
12580                    it.remove();
12581                }
12582            }
12583        }
12584
12585        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12586        // Now update the permissions for all packages, in particular
12587        // replace the granted permissions of the system packages.
12588        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12589            for (PackageParser.Package pkg : mPackages.values()) {
12590                if (pkg != pkgInfo) {
12591                    // Only replace for packages on requested volume
12592                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12593                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12594                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12595                    grantPermissionsLPw(pkg, replace, changingPkg);
12596                }
12597            }
12598        }
12599
12600        if (pkgInfo != null) {
12601            // Only replace for packages on requested volume
12602            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12603            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12604                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12605            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12606        }
12607        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12608    }
12609
12610    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12611            String packageOfInterest) {
12612        // IMPORTANT: There are two types of permissions: install and runtime.
12613        // Install time permissions are granted when the app is installed to
12614        // all device users and users added in the future. Runtime permissions
12615        // are granted at runtime explicitly to specific users. Normal and signature
12616        // protected permissions are install time permissions. Dangerous permissions
12617        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12618        // otherwise they are runtime permissions. This function does not manage
12619        // runtime permissions except for the case an app targeting Lollipop MR1
12620        // being upgraded to target a newer SDK, in which case dangerous permissions
12621        // are transformed from install time to runtime ones.
12622
12623        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12624        if (ps == null) {
12625            return;
12626        }
12627
12628        PermissionsState permissionsState = ps.getPermissionsState();
12629        PermissionsState origPermissions = permissionsState;
12630
12631        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12632
12633        boolean runtimePermissionsRevoked = false;
12634        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12635
12636        boolean changedInstallPermission = false;
12637
12638        if (replace) {
12639            ps.installPermissionsFixed = false;
12640            if (!ps.isSharedUser()) {
12641                origPermissions = new PermissionsState(permissionsState);
12642                permissionsState.reset();
12643            } else {
12644                // We need to know only about runtime permission changes since the
12645                // calling code always writes the install permissions state but
12646                // the runtime ones are written only if changed. The only cases of
12647                // changed runtime permissions here are promotion of an install to
12648                // runtime and revocation of a runtime from a shared user.
12649                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12650                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12651                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12652                    runtimePermissionsRevoked = true;
12653                }
12654            }
12655        }
12656
12657        permissionsState.setGlobalGids(mGlobalGids);
12658
12659        final int N = pkg.requestedPermissions.size();
12660        for (int i=0; i<N; i++) {
12661            final String name = pkg.requestedPermissions.get(i);
12662            final BasePermission bp = mSettings.mPermissions.get(name);
12663            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12664                    >= Build.VERSION_CODES.M;
12665
12666            if (DEBUG_INSTALL) {
12667                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12668            }
12669
12670            if (bp == null || bp.packageSetting == null) {
12671                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12672                    if (DEBUG_PERMISSIONS) {
12673                        Slog.i(TAG, "Unknown permission " + name
12674                                + " in package " + pkg.packageName);
12675                    }
12676                }
12677                continue;
12678            }
12679
12680
12681            // Limit ephemeral apps to ephemeral allowed permissions.
12682            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12683                if (DEBUG_PERMISSIONS) {
12684                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12685                            + pkg.packageName);
12686                }
12687                continue;
12688            }
12689
12690            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12691                if (DEBUG_PERMISSIONS) {
12692                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12693                            + pkg.packageName);
12694                }
12695                continue;
12696            }
12697
12698            final String perm = bp.name;
12699            boolean allowedSig = false;
12700            int grant = GRANT_DENIED;
12701
12702            // Keep track of app op permissions.
12703            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12704                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12705                if (pkgs == null) {
12706                    pkgs = new ArraySet<>();
12707                    mAppOpPermissionPackages.put(bp.name, pkgs);
12708                }
12709                pkgs.add(pkg.packageName);
12710            }
12711
12712            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12713            switch (level) {
12714                case PermissionInfo.PROTECTION_NORMAL: {
12715                    // For all apps normal permissions are install time ones.
12716                    grant = GRANT_INSTALL;
12717                } break;
12718
12719                case PermissionInfo.PROTECTION_DANGEROUS: {
12720                    // If a permission review is required for legacy apps we represent
12721                    // their permissions as always granted runtime ones since we need
12722                    // to keep the review required permission flag per user while an
12723                    // install permission's state is shared across all users.
12724                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12725                        // For legacy apps dangerous permissions are install time ones.
12726                        grant = GRANT_INSTALL;
12727                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12728                        // For legacy apps that became modern, install becomes runtime.
12729                        grant = GRANT_UPGRADE;
12730                    } else if (mPromoteSystemApps
12731                            && isSystemApp(ps)
12732                            && mExistingSystemPackages.contains(ps.name)) {
12733                        // For legacy system apps, install becomes runtime.
12734                        // We cannot check hasInstallPermission() for system apps since those
12735                        // permissions were granted implicitly and not persisted pre-M.
12736                        grant = GRANT_UPGRADE;
12737                    } else {
12738                        // For modern apps keep runtime permissions unchanged.
12739                        grant = GRANT_RUNTIME;
12740                    }
12741                } break;
12742
12743                case PermissionInfo.PROTECTION_SIGNATURE: {
12744                    // For all apps signature permissions are install time ones.
12745                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12746                    if (allowedSig) {
12747                        grant = GRANT_INSTALL;
12748                    }
12749                } break;
12750            }
12751
12752            if (DEBUG_PERMISSIONS) {
12753                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12754            }
12755
12756            if (grant != GRANT_DENIED) {
12757                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12758                    // If this is an existing, non-system package, then
12759                    // we can't add any new permissions to it.
12760                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12761                        // Except...  if this is a permission that was added
12762                        // to the platform (note: need to only do this when
12763                        // updating the platform).
12764                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12765                            grant = GRANT_DENIED;
12766                        }
12767                    }
12768                }
12769
12770                switch (grant) {
12771                    case GRANT_INSTALL: {
12772                        // Revoke this as runtime permission to handle the case of
12773                        // a runtime permission being downgraded to an install one.
12774                        // Also in permission review mode we keep dangerous permissions
12775                        // for legacy apps
12776                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12777                            if (origPermissions.getRuntimePermissionState(
12778                                    bp.name, userId) != null) {
12779                                // Revoke the runtime permission and clear the flags.
12780                                origPermissions.revokeRuntimePermission(bp, userId);
12781                                origPermissions.updatePermissionFlags(bp, userId,
12782                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12783                                // If we revoked a permission permission, we have to write.
12784                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12785                                        changedRuntimePermissionUserIds, userId);
12786                            }
12787                        }
12788                        // Grant an install permission.
12789                        if (permissionsState.grantInstallPermission(bp) !=
12790                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12791                            changedInstallPermission = true;
12792                        }
12793                    } break;
12794
12795                    case GRANT_RUNTIME: {
12796                        // Grant previously granted runtime permissions.
12797                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12798                            PermissionState permissionState = origPermissions
12799                                    .getRuntimePermissionState(bp.name, userId);
12800                            int flags = permissionState != null
12801                                    ? permissionState.getFlags() : 0;
12802                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12803                                // Don't propagate the permission in a permission review mode if
12804                                // the former was revoked, i.e. marked to not propagate on upgrade.
12805                                // Note that in a permission review mode install permissions are
12806                                // represented as constantly granted runtime ones since we need to
12807                                // keep a per user state associated with the permission. Also the
12808                                // revoke on upgrade flag is no longer applicable and is reset.
12809                                final boolean revokeOnUpgrade = (flags & PackageManager
12810                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12811                                if (revokeOnUpgrade) {
12812                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12813                                    // Since we changed the flags, we have to write.
12814                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12815                                            changedRuntimePermissionUserIds, userId);
12816                                }
12817                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12818                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12819                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12820                                        // If we cannot put the permission as it was,
12821                                        // we have to write.
12822                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12823                                                changedRuntimePermissionUserIds, userId);
12824                                    }
12825                                }
12826
12827                                // If the app supports runtime permissions no need for a review.
12828                                if (mPermissionReviewRequired
12829                                        && appSupportsRuntimePermissions
12830                                        && (flags & PackageManager
12831                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12832                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12833                                    // Since we changed the flags, we have to write.
12834                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12835                                            changedRuntimePermissionUserIds, userId);
12836                                }
12837                            } else if (mPermissionReviewRequired
12838                                    && !appSupportsRuntimePermissions) {
12839                                // For legacy apps that need a permission review, every new
12840                                // runtime permission is granted but it is pending a review.
12841                                // We also need to review only platform defined runtime
12842                                // permissions as these are the only ones the platform knows
12843                                // how to disable the API to simulate revocation as legacy
12844                                // apps don't expect to run with revoked permissions.
12845                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12846                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12847                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12848                                        // We changed the flags, hence have to write.
12849                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12850                                                changedRuntimePermissionUserIds, userId);
12851                                    }
12852                                }
12853                                if (permissionsState.grantRuntimePermission(bp, userId)
12854                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12855                                    // We changed the permission, hence have to write.
12856                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12857                                            changedRuntimePermissionUserIds, userId);
12858                                }
12859                            }
12860                            // Propagate the permission flags.
12861                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12862                        }
12863                    } break;
12864
12865                    case GRANT_UPGRADE: {
12866                        // Grant runtime permissions for a previously held install permission.
12867                        PermissionState permissionState = origPermissions
12868                                .getInstallPermissionState(bp.name);
12869                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12870
12871                        if (origPermissions.revokeInstallPermission(bp)
12872                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12873                            // We will be transferring the permission flags, so clear them.
12874                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12875                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12876                            changedInstallPermission = true;
12877                        }
12878
12879                        // If the permission is not to be promoted to runtime we ignore it and
12880                        // also its other flags as they are not applicable to install permissions.
12881                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12882                            for (int userId : currentUserIds) {
12883                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12884                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12885                                    // Transfer the permission flags.
12886                                    permissionsState.updatePermissionFlags(bp, userId,
12887                                            flags, flags);
12888                                    // If we granted the permission, we have to write.
12889                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12890                                            changedRuntimePermissionUserIds, userId);
12891                                }
12892                            }
12893                        }
12894                    } break;
12895
12896                    default: {
12897                        if (packageOfInterest == null
12898                                || packageOfInterest.equals(pkg.packageName)) {
12899                            if (DEBUG_PERMISSIONS) {
12900                                Slog.i(TAG, "Not granting permission " + perm
12901                                        + " to package " + pkg.packageName
12902                                        + " because it was previously installed without");
12903                            }
12904                        }
12905                    } break;
12906                }
12907            } else {
12908                if (permissionsState.revokeInstallPermission(bp) !=
12909                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12910                    // Also drop the permission flags.
12911                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12912                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12913                    changedInstallPermission = true;
12914                    Slog.i(TAG, "Un-granting permission " + perm
12915                            + " from package " + pkg.packageName
12916                            + " (protectionLevel=" + bp.protectionLevel
12917                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12918                            + ")");
12919                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12920                    // Don't print warning for app op permissions, since it is fine for them
12921                    // not to be granted, there is a UI for the user to decide.
12922                    if (DEBUG_PERMISSIONS
12923                            && (packageOfInterest == null
12924                                    || packageOfInterest.equals(pkg.packageName))) {
12925                        Slog.i(TAG, "Not granting permission " + perm
12926                                + " to package " + pkg.packageName
12927                                + " (protectionLevel=" + bp.protectionLevel
12928                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12929                                + ")");
12930                    }
12931                }
12932            }
12933        }
12934
12935        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12936                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12937            // This is the first that we have heard about this package, so the
12938            // permissions we have now selected are fixed until explicitly
12939            // changed.
12940            ps.installPermissionsFixed = true;
12941        }
12942
12943        // Persist the runtime permissions state for users with changes. If permissions
12944        // were revoked because no app in the shared user declares them we have to
12945        // write synchronously to avoid losing runtime permissions state.
12946        for (int userId : changedRuntimePermissionUserIds) {
12947            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12948        }
12949    }
12950
12951    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12952        boolean allowed = false;
12953        final int NP = PackageParser.NEW_PERMISSIONS.length;
12954        for (int ip=0; ip<NP; ip++) {
12955            final PackageParser.NewPermissionInfo npi
12956                    = PackageParser.NEW_PERMISSIONS[ip];
12957            if (npi.name.equals(perm)
12958                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12959                allowed = true;
12960                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12961                        + pkg.packageName);
12962                break;
12963            }
12964        }
12965        return allowed;
12966    }
12967
12968    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12969            BasePermission bp, PermissionsState origPermissions) {
12970        boolean privilegedPermission = (bp.protectionLevel
12971                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12972        boolean privappPermissionsDisable =
12973                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12974        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12975        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12976        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12977                && !platformPackage && platformPermission) {
12978            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12979                    .getPrivAppPermissions(pkg.packageName);
12980            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12981            if (!whitelisted) {
12982                Slog.w(TAG, "Privileged permission " + perm + " for package "
12983                        + pkg.packageName + " - not in privapp-permissions whitelist");
12984                // Only report violations for apps on system image
12985                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12986                    if (mPrivappPermissionsViolations == null) {
12987                        mPrivappPermissionsViolations = new ArraySet<>();
12988                    }
12989                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12990                }
12991                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12992                    return false;
12993                }
12994            }
12995        }
12996        boolean allowed = (compareSignatures(
12997                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12998                        == PackageManager.SIGNATURE_MATCH)
12999                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13000                        == PackageManager.SIGNATURE_MATCH);
13001        if (!allowed && privilegedPermission) {
13002            if (isSystemApp(pkg)) {
13003                // For updated system applications, a system permission
13004                // is granted only if it had been defined by the original application.
13005                if (pkg.isUpdatedSystemApp()) {
13006                    final PackageSetting sysPs = mSettings
13007                            .getDisabledSystemPkgLPr(pkg.packageName);
13008                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13009                        // If the original was granted this permission, we take
13010                        // that grant decision as read and propagate it to the
13011                        // update.
13012                        if (sysPs.isPrivileged()) {
13013                            allowed = true;
13014                        }
13015                    } else {
13016                        // The system apk may have been updated with an older
13017                        // version of the one on the data partition, but which
13018                        // granted a new system permission that it didn't have
13019                        // before.  In this case we do want to allow the app to
13020                        // now get the new permission if the ancestral apk is
13021                        // privileged to get it.
13022                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13023                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13024                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13025                                    allowed = true;
13026                                    break;
13027                                }
13028                            }
13029                        }
13030                        // Also if a privileged parent package on the system image or any of
13031                        // its children requested a privileged permission, the updated child
13032                        // packages can also get the permission.
13033                        if (pkg.parentPackage != null) {
13034                            final PackageSetting disabledSysParentPs = mSettings
13035                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13036                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13037                                    && disabledSysParentPs.isPrivileged()) {
13038                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13039                                    allowed = true;
13040                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13041                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13042                                    for (int i = 0; i < count; i++) {
13043                                        PackageParser.Package disabledSysChildPkg =
13044                                                disabledSysParentPs.pkg.childPackages.get(i);
13045                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13046                                                perm)) {
13047                                            allowed = true;
13048                                            break;
13049                                        }
13050                                    }
13051                                }
13052                            }
13053                        }
13054                    }
13055                } else {
13056                    allowed = isPrivilegedApp(pkg);
13057                }
13058            }
13059        }
13060        if (!allowed) {
13061            if (!allowed && (bp.protectionLevel
13062                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13063                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13064                // If this was a previously normal/dangerous permission that got moved
13065                // to a system permission as part of the runtime permission redesign, then
13066                // we still want to blindly grant it to old apps.
13067                allowed = true;
13068            }
13069            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13070                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13071                // If this permission is to be granted to the system installer and
13072                // this app is an installer, then it gets the permission.
13073                allowed = true;
13074            }
13075            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13076                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13077                // If this permission is to be granted to the system verifier and
13078                // this app is a verifier, then it gets the permission.
13079                allowed = true;
13080            }
13081            if (!allowed && (bp.protectionLevel
13082                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13083                    && isSystemApp(pkg)) {
13084                // Any pre-installed system app is allowed to get this permission.
13085                allowed = true;
13086            }
13087            if (!allowed && (bp.protectionLevel
13088                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13089                // For development permissions, a development permission
13090                // is granted only if it was already granted.
13091                allowed = origPermissions.hasInstallPermission(perm);
13092            }
13093            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13094                    && pkg.packageName.equals(mSetupWizardPackage)) {
13095                // If this permission is to be granted to the system setup wizard and
13096                // this app is a setup wizard, then it gets the permission.
13097                allowed = true;
13098            }
13099        }
13100        return allowed;
13101    }
13102
13103    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13104        final int permCount = pkg.requestedPermissions.size();
13105        for (int j = 0; j < permCount; j++) {
13106            String requestedPermission = pkg.requestedPermissions.get(j);
13107            if (permission.equals(requestedPermission)) {
13108                return true;
13109            }
13110        }
13111        return false;
13112    }
13113
13114    final class ActivityIntentResolver
13115            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13116        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13117                boolean defaultOnly, int userId) {
13118            if (!sUserManager.exists(userId)) return null;
13119            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13120            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13121        }
13122
13123        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13124                int userId) {
13125            if (!sUserManager.exists(userId)) return null;
13126            mFlags = flags;
13127            return super.queryIntent(intent, resolvedType,
13128                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13129                    userId);
13130        }
13131
13132        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13133                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13134            if (!sUserManager.exists(userId)) return null;
13135            if (packageActivities == null) {
13136                return null;
13137            }
13138            mFlags = flags;
13139            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13140            final int N = packageActivities.size();
13141            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13142                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13143
13144            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13145            for (int i = 0; i < N; ++i) {
13146                intentFilters = packageActivities.get(i).intents;
13147                if (intentFilters != null && intentFilters.size() > 0) {
13148                    PackageParser.ActivityIntentInfo[] array =
13149                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13150                    intentFilters.toArray(array);
13151                    listCut.add(array);
13152                }
13153            }
13154            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13155        }
13156
13157        /**
13158         * Finds a privileged activity that matches the specified activity names.
13159         */
13160        private PackageParser.Activity findMatchingActivity(
13161                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13162            for (PackageParser.Activity sysActivity : activityList) {
13163                if (sysActivity.info.name.equals(activityInfo.name)) {
13164                    return sysActivity;
13165                }
13166                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13167                    return sysActivity;
13168                }
13169                if (sysActivity.info.targetActivity != null) {
13170                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13171                        return sysActivity;
13172                    }
13173                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13174                        return sysActivity;
13175                    }
13176                }
13177            }
13178            return null;
13179        }
13180
13181        public class IterGenerator<E> {
13182            public Iterator<E> generate(ActivityIntentInfo info) {
13183                return null;
13184            }
13185        }
13186
13187        public class ActionIterGenerator extends IterGenerator<String> {
13188            @Override
13189            public Iterator<String> generate(ActivityIntentInfo info) {
13190                return info.actionsIterator();
13191            }
13192        }
13193
13194        public class CategoriesIterGenerator extends IterGenerator<String> {
13195            @Override
13196            public Iterator<String> generate(ActivityIntentInfo info) {
13197                return info.categoriesIterator();
13198            }
13199        }
13200
13201        public class SchemesIterGenerator extends IterGenerator<String> {
13202            @Override
13203            public Iterator<String> generate(ActivityIntentInfo info) {
13204                return info.schemesIterator();
13205            }
13206        }
13207
13208        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13209            @Override
13210            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13211                return info.authoritiesIterator();
13212            }
13213        }
13214
13215        /**
13216         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13217         * MODIFIED. Do not pass in a list that should not be changed.
13218         */
13219        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13220                IterGenerator<T> generator, Iterator<T> searchIterator) {
13221            // loop through the set of actions; every one must be found in the intent filter
13222            while (searchIterator.hasNext()) {
13223                // we must have at least one filter in the list to consider a match
13224                if (intentList.size() == 0) {
13225                    break;
13226                }
13227
13228                final T searchAction = searchIterator.next();
13229
13230                // loop through the set of intent filters
13231                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13232                while (intentIter.hasNext()) {
13233                    final ActivityIntentInfo intentInfo = intentIter.next();
13234                    boolean selectionFound = false;
13235
13236                    // loop through the intent filter's selection criteria; at least one
13237                    // of them must match the searched criteria
13238                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13239                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13240                        final T intentSelection = intentSelectionIter.next();
13241                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13242                            selectionFound = true;
13243                            break;
13244                        }
13245                    }
13246
13247                    // the selection criteria wasn't found in this filter's set; this filter
13248                    // is not a potential match
13249                    if (!selectionFound) {
13250                        intentIter.remove();
13251                    }
13252                }
13253            }
13254        }
13255
13256        private boolean isProtectedAction(ActivityIntentInfo filter) {
13257            final Iterator<String> actionsIter = filter.actionsIterator();
13258            while (actionsIter != null && actionsIter.hasNext()) {
13259                final String filterAction = actionsIter.next();
13260                if (PROTECTED_ACTIONS.contains(filterAction)) {
13261                    return true;
13262                }
13263            }
13264            return false;
13265        }
13266
13267        /**
13268         * Adjusts the priority of the given intent filter according to policy.
13269         * <p>
13270         * <ul>
13271         * <li>The priority for non privileged applications is capped to '0'</li>
13272         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13273         * <li>The priority for unbundled updates to privileged applications is capped to the
13274         *      priority defined on the system partition</li>
13275         * </ul>
13276         * <p>
13277         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13278         * allowed to obtain any priority on any action.
13279         */
13280        private void adjustPriority(
13281                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13282            // nothing to do; priority is fine as-is
13283            if (intent.getPriority() <= 0) {
13284                return;
13285            }
13286
13287            final ActivityInfo activityInfo = intent.activity.info;
13288            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13289
13290            final boolean privilegedApp =
13291                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13292            if (!privilegedApp) {
13293                // non-privileged applications can never define a priority >0
13294                if (DEBUG_FILTERS) {
13295                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13296                            + " package: " + applicationInfo.packageName
13297                            + " activity: " + intent.activity.className
13298                            + " origPrio: " + intent.getPriority());
13299                }
13300                intent.setPriority(0);
13301                return;
13302            }
13303
13304            if (systemActivities == null) {
13305                // the system package is not disabled; we're parsing the system partition
13306                if (isProtectedAction(intent)) {
13307                    if (mDeferProtectedFilters) {
13308                        // We can't deal with these just yet. No component should ever obtain a
13309                        // >0 priority for a protected actions, with ONE exception -- the setup
13310                        // wizard. The setup wizard, however, cannot be known until we're able to
13311                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13312                        // until all intent filters have been processed. Chicken, meet egg.
13313                        // Let the filter temporarily have a high priority and rectify the
13314                        // priorities after all system packages have been scanned.
13315                        mProtectedFilters.add(intent);
13316                        if (DEBUG_FILTERS) {
13317                            Slog.i(TAG, "Protected action; save for later;"
13318                                    + " package: " + applicationInfo.packageName
13319                                    + " activity: " + intent.activity.className
13320                                    + " origPrio: " + intent.getPriority());
13321                        }
13322                        return;
13323                    } else {
13324                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13325                            Slog.i(TAG, "No setup wizard;"
13326                                + " All protected intents capped to priority 0");
13327                        }
13328                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13329                            if (DEBUG_FILTERS) {
13330                                Slog.i(TAG, "Found setup wizard;"
13331                                    + " allow priority " + intent.getPriority() + ";"
13332                                    + " package: " + intent.activity.info.packageName
13333                                    + " activity: " + intent.activity.className
13334                                    + " priority: " + intent.getPriority());
13335                            }
13336                            // setup wizard gets whatever it wants
13337                            return;
13338                        }
13339                        if (DEBUG_FILTERS) {
13340                            Slog.i(TAG, "Protected action; cap priority to 0;"
13341                                    + " package: " + intent.activity.info.packageName
13342                                    + " activity: " + intent.activity.className
13343                                    + " origPrio: " + intent.getPriority());
13344                        }
13345                        intent.setPriority(0);
13346                        return;
13347                    }
13348                }
13349                // privileged apps on the system image get whatever priority they request
13350                return;
13351            }
13352
13353            // privileged app unbundled update ... try to find the same activity
13354            final PackageParser.Activity foundActivity =
13355                    findMatchingActivity(systemActivities, activityInfo);
13356            if (foundActivity == null) {
13357                // this is a new activity; it cannot obtain >0 priority
13358                if (DEBUG_FILTERS) {
13359                    Slog.i(TAG, "New activity; cap priority to 0;"
13360                            + " package: " + applicationInfo.packageName
13361                            + " activity: " + intent.activity.className
13362                            + " origPrio: " + intent.getPriority());
13363                }
13364                intent.setPriority(0);
13365                return;
13366            }
13367
13368            // found activity, now check for filter equivalence
13369
13370            // a shallow copy is enough; we modify the list, not its contents
13371            final List<ActivityIntentInfo> intentListCopy =
13372                    new ArrayList<>(foundActivity.intents);
13373            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13374
13375            // find matching action subsets
13376            final Iterator<String> actionsIterator = intent.actionsIterator();
13377            if (actionsIterator != null) {
13378                getIntentListSubset(
13379                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13380                if (intentListCopy.size() == 0) {
13381                    // no more intents to match; we're not equivalent
13382                    if (DEBUG_FILTERS) {
13383                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13384                                + " package: " + applicationInfo.packageName
13385                                + " activity: " + intent.activity.className
13386                                + " origPrio: " + intent.getPriority());
13387                    }
13388                    intent.setPriority(0);
13389                    return;
13390                }
13391            }
13392
13393            // find matching category subsets
13394            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13395            if (categoriesIterator != null) {
13396                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13397                        categoriesIterator);
13398                if (intentListCopy.size() == 0) {
13399                    // no more intents to match; we're not equivalent
13400                    if (DEBUG_FILTERS) {
13401                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13402                                + " package: " + applicationInfo.packageName
13403                                + " activity: " + intent.activity.className
13404                                + " origPrio: " + intent.getPriority());
13405                    }
13406                    intent.setPriority(0);
13407                    return;
13408                }
13409            }
13410
13411            // find matching schemes subsets
13412            final Iterator<String> schemesIterator = intent.schemesIterator();
13413            if (schemesIterator != null) {
13414                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13415                        schemesIterator);
13416                if (intentListCopy.size() == 0) {
13417                    // no more intents to match; we're not equivalent
13418                    if (DEBUG_FILTERS) {
13419                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13420                                + " package: " + applicationInfo.packageName
13421                                + " activity: " + intent.activity.className
13422                                + " origPrio: " + intent.getPriority());
13423                    }
13424                    intent.setPriority(0);
13425                    return;
13426                }
13427            }
13428
13429            // find matching authorities subsets
13430            final Iterator<IntentFilter.AuthorityEntry>
13431                    authoritiesIterator = intent.authoritiesIterator();
13432            if (authoritiesIterator != null) {
13433                getIntentListSubset(intentListCopy,
13434                        new AuthoritiesIterGenerator(),
13435                        authoritiesIterator);
13436                if (intentListCopy.size() == 0) {
13437                    // no more intents to match; we're not equivalent
13438                    if (DEBUG_FILTERS) {
13439                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13440                                + " package: " + applicationInfo.packageName
13441                                + " activity: " + intent.activity.className
13442                                + " origPrio: " + intent.getPriority());
13443                    }
13444                    intent.setPriority(0);
13445                    return;
13446                }
13447            }
13448
13449            // we found matching filter(s); app gets the max priority of all intents
13450            int cappedPriority = 0;
13451            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13452                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13453            }
13454            if (intent.getPriority() > cappedPriority) {
13455                if (DEBUG_FILTERS) {
13456                    Slog.i(TAG, "Found matching filter(s);"
13457                            + " cap priority to " + cappedPriority + ";"
13458                            + " package: " + applicationInfo.packageName
13459                            + " activity: " + intent.activity.className
13460                            + " origPrio: " + intent.getPriority());
13461                }
13462                intent.setPriority(cappedPriority);
13463                return;
13464            }
13465            // all this for nothing; the requested priority was <= what was on the system
13466        }
13467
13468        public final void addActivity(PackageParser.Activity a, String type) {
13469            mActivities.put(a.getComponentName(), a);
13470            if (DEBUG_SHOW_INFO)
13471                Log.v(
13472                TAG, "  " + type + " " +
13473                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13474            if (DEBUG_SHOW_INFO)
13475                Log.v(TAG, "    Class=" + a.info.name);
13476            final int NI = a.intents.size();
13477            for (int j=0; j<NI; j++) {
13478                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13479                if ("activity".equals(type)) {
13480                    final PackageSetting ps =
13481                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13482                    final List<PackageParser.Activity> systemActivities =
13483                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13484                    adjustPriority(systemActivities, intent);
13485                }
13486                if (DEBUG_SHOW_INFO) {
13487                    Log.v(TAG, "    IntentFilter:");
13488                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13489                }
13490                if (!intent.debugCheck()) {
13491                    Log.w(TAG, "==> For Activity " + a.info.name);
13492                }
13493                addFilter(intent);
13494            }
13495        }
13496
13497        public final void removeActivity(PackageParser.Activity a, String type) {
13498            mActivities.remove(a.getComponentName());
13499            if (DEBUG_SHOW_INFO) {
13500                Log.v(TAG, "  " + type + " "
13501                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13502                                : a.info.name) + ":");
13503                Log.v(TAG, "    Class=" + a.info.name);
13504            }
13505            final int NI = a.intents.size();
13506            for (int j=0; j<NI; j++) {
13507                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13508                if (DEBUG_SHOW_INFO) {
13509                    Log.v(TAG, "    IntentFilter:");
13510                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13511                }
13512                removeFilter(intent);
13513            }
13514        }
13515
13516        @Override
13517        protected boolean allowFilterResult(
13518                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13519            ActivityInfo filterAi = filter.activity.info;
13520            for (int i=dest.size()-1; i>=0; i--) {
13521                ActivityInfo destAi = dest.get(i).activityInfo;
13522                if (destAi.name == filterAi.name
13523                        && destAi.packageName == filterAi.packageName) {
13524                    return false;
13525                }
13526            }
13527            return true;
13528        }
13529
13530        @Override
13531        protected ActivityIntentInfo[] newArray(int size) {
13532            return new ActivityIntentInfo[size];
13533        }
13534
13535        @Override
13536        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13537            if (!sUserManager.exists(userId)) return true;
13538            PackageParser.Package p = filter.activity.owner;
13539            if (p != null) {
13540                PackageSetting ps = (PackageSetting)p.mExtras;
13541                if (ps != null) {
13542                    // System apps are never considered stopped for purposes of
13543                    // filtering, because there may be no way for the user to
13544                    // actually re-launch them.
13545                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13546                            && ps.getStopped(userId);
13547                }
13548            }
13549            return false;
13550        }
13551
13552        @Override
13553        protected boolean isPackageForFilter(String packageName,
13554                PackageParser.ActivityIntentInfo info) {
13555            return packageName.equals(info.activity.owner.packageName);
13556        }
13557
13558        @Override
13559        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13560                int match, int userId) {
13561            if (!sUserManager.exists(userId)) return null;
13562            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13563                return null;
13564            }
13565            final PackageParser.Activity activity = info.activity;
13566            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13567            if (ps == null) {
13568                return null;
13569            }
13570            final PackageUserState userState = ps.readUserState(userId);
13571            ActivityInfo ai =
13572                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13573            if (ai == null) {
13574                return null;
13575            }
13576            final boolean matchExplicitlyVisibleOnly =
13577                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13578            final boolean matchVisibleToInstantApp =
13579                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13580            final boolean componentVisible =
13581                    matchVisibleToInstantApp
13582                    && info.isVisibleToInstantApp()
13583                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13584            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13585            // throw out filters that aren't visible to ephemeral apps
13586            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13587                return null;
13588            }
13589            // throw out instant app filters if we're not explicitly requesting them
13590            if (!matchInstantApp && userState.instantApp) {
13591                return null;
13592            }
13593            // throw out instant app filters if updates are available; will trigger
13594            // instant app resolution
13595            if (userState.instantApp && ps.isUpdateAvailable()) {
13596                return null;
13597            }
13598            final ResolveInfo res = new ResolveInfo();
13599            res.activityInfo = ai;
13600            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13601                res.filter = info;
13602            }
13603            if (info != null) {
13604                res.handleAllWebDataURI = info.handleAllWebDataURI();
13605            }
13606            res.priority = info.getPriority();
13607            res.preferredOrder = activity.owner.mPreferredOrder;
13608            //System.out.println("Result: " + res.activityInfo.className +
13609            //                   " = " + res.priority);
13610            res.match = match;
13611            res.isDefault = info.hasDefault;
13612            res.labelRes = info.labelRes;
13613            res.nonLocalizedLabel = info.nonLocalizedLabel;
13614            if (userNeedsBadging(userId)) {
13615                res.noResourceId = true;
13616            } else {
13617                res.icon = info.icon;
13618            }
13619            res.iconResourceId = info.icon;
13620            res.system = res.activityInfo.applicationInfo.isSystemApp();
13621            res.isInstantAppAvailable = userState.instantApp;
13622            return res;
13623        }
13624
13625        @Override
13626        protected void sortResults(List<ResolveInfo> results) {
13627            Collections.sort(results, mResolvePrioritySorter);
13628        }
13629
13630        @Override
13631        protected void dumpFilter(PrintWriter out, String prefix,
13632                PackageParser.ActivityIntentInfo filter) {
13633            out.print(prefix); out.print(
13634                    Integer.toHexString(System.identityHashCode(filter.activity)));
13635                    out.print(' ');
13636                    filter.activity.printComponentShortName(out);
13637                    out.print(" filter ");
13638                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13639        }
13640
13641        @Override
13642        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13643            return filter.activity;
13644        }
13645
13646        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13647            PackageParser.Activity activity = (PackageParser.Activity)label;
13648            out.print(prefix); out.print(
13649                    Integer.toHexString(System.identityHashCode(activity)));
13650                    out.print(' ');
13651                    activity.printComponentShortName(out);
13652            if (count > 1) {
13653                out.print(" ("); out.print(count); out.print(" filters)");
13654            }
13655            out.println();
13656        }
13657
13658        // Keys are String (activity class name), values are Activity.
13659        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13660                = new ArrayMap<ComponentName, PackageParser.Activity>();
13661        private int mFlags;
13662    }
13663
13664    private final class ServiceIntentResolver
13665            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13666        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13667                boolean defaultOnly, int userId) {
13668            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13669            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13670        }
13671
13672        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13673                int userId) {
13674            if (!sUserManager.exists(userId)) return null;
13675            mFlags = flags;
13676            return super.queryIntent(intent, resolvedType,
13677                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13678                    userId);
13679        }
13680
13681        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13682                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13683            if (!sUserManager.exists(userId)) return null;
13684            if (packageServices == null) {
13685                return null;
13686            }
13687            mFlags = flags;
13688            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13689            final int N = packageServices.size();
13690            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13691                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13692
13693            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13694            for (int i = 0; i < N; ++i) {
13695                intentFilters = packageServices.get(i).intents;
13696                if (intentFilters != null && intentFilters.size() > 0) {
13697                    PackageParser.ServiceIntentInfo[] array =
13698                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13699                    intentFilters.toArray(array);
13700                    listCut.add(array);
13701                }
13702            }
13703            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13704        }
13705
13706        public final void addService(PackageParser.Service s) {
13707            mServices.put(s.getComponentName(), s);
13708            if (DEBUG_SHOW_INFO) {
13709                Log.v(TAG, "  "
13710                        + (s.info.nonLocalizedLabel != null
13711                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13712                Log.v(TAG, "    Class=" + s.info.name);
13713            }
13714            final int NI = s.intents.size();
13715            int j;
13716            for (j=0; j<NI; j++) {
13717                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13718                if (DEBUG_SHOW_INFO) {
13719                    Log.v(TAG, "    IntentFilter:");
13720                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13721                }
13722                if (!intent.debugCheck()) {
13723                    Log.w(TAG, "==> For Service " + s.info.name);
13724                }
13725                addFilter(intent);
13726            }
13727        }
13728
13729        public final void removeService(PackageParser.Service s) {
13730            mServices.remove(s.getComponentName());
13731            if (DEBUG_SHOW_INFO) {
13732                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13733                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13734                Log.v(TAG, "    Class=" + s.info.name);
13735            }
13736            final int NI = s.intents.size();
13737            int j;
13738            for (j=0; j<NI; j++) {
13739                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13740                if (DEBUG_SHOW_INFO) {
13741                    Log.v(TAG, "    IntentFilter:");
13742                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13743                }
13744                removeFilter(intent);
13745            }
13746        }
13747
13748        @Override
13749        protected boolean allowFilterResult(
13750                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13751            ServiceInfo filterSi = filter.service.info;
13752            for (int i=dest.size()-1; i>=0; i--) {
13753                ServiceInfo destAi = dest.get(i).serviceInfo;
13754                if (destAi.name == filterSi.name
13755                        && destAi.packageName == filterSi.packageName) {
13756                    return false;
13757                }
13758            }
13759            return true;
13760        }
13761
13762        @Override
13763        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13764            return new PackageParser.ServiceIntentInfo[size];
13765        }
13766
13767        @Override
13768        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13769            if (!sUserManager.exists(userId)) return true;
13770            PackageParser.Package p = filter.service.owner;
13771            if (p != null) {
13772                PackageSetting ps = (PackageSetting)p.mExtras;
13773                if (ps != null) {
13774                    // System apps are never considered stopped for purposes of
13775                    // filtering, because there may be no way for the user to
13776                    // actually re-launch them.
13777                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13778                            && ps.getStopped(userId);
13779                }
13780            }
13781            return false;
13782        }
13783
13784        @Override
13785        protected boolean isPackageForFilter(String packageName,
13786                PackageParser.ServiceIntentInfo info) {
13787            return packageName.equals(info.service.owner.packageName);
13788        }
13789
13790        @Override
13791        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13792                int match, int userId) {
13793            if (!sUserManager.exists(userId)) return null;
13794            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13795            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13796                return null;
13797            }
13798            final PackageParser.Service service = info.service;
13799            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13800            if (ps == null) {
13801                return null;
13802            }
13803            final PackageUserState userState = ps.readUserState(userId);
13804            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13805                    userState, userId);
13806            if (si == null) {
13807                return null;
13808            }
13809            final boolean matchVisibleToInstantApp =
13810                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13811            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13812            // throw out filters that aren't visible to ephemeral apps
13813            if (matchVisibleToInstantApp
13814                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13815                return null;
13816            }
13817            // throw out ephemeral filters if we're not explicitly requesting them
13818            if (!isInstantApp && userState.instantApp) {
13819                return null;
13820            }
13821            // throw out instant app filters if updates are available; will trigger
13822            // instant app resolution
13823            if (userState.instantApp && ps.isUpdateAvailable()) {
13824                return null;
13825            }
13826            final ResolveInfo res = new ResolveInfo();
13827            res.serviceInfo = si;
13828            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13829                res.filter = filter;
13830            }
13831            res.priority = info.getPriority();
13832            res.preferredOrder = service.owner.mPreferredOrder;
13833            res.match = match;
13834            res.isDefault = info.hasDefault;
13835            res.labelRes = info.labelRes;
13836            res.nonLocalizedLabel = info.nonLocalizedLabel;
13837            res.icon = info.icon;
13838            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13839            return res;
13840        }
13841
13842        @Override
13843        protected void sortResults(List<ResolveInfo> results) {
13844            Collections.sort(results, mResolvePrioritySorter);
13845        }
13846
13847        @Override
13848        protected void dumpFilter(PrintWriter out, String prefix,
13849                PackageParser.ServiceIntentInfo filter) {
13850            out.print(prefix); out.print(
13851                    Integer.toHexString(System.identityHashCode(filter.service)));
13852                    out.print(' ');
13853                    filter.service.printComponentShortName(out);
13854                    out.print(" filter ");
13855                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13856        }
13857
13858        @Override
13859        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13860            return filter.service;
13861        }
13862
13863        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13864            PackageParser.Service service = (PackageParser.Service)label;
13865            out.print(prefix); out.print(
13866                    Integer.toHexString(System.identityHashCode(service)));
13867                    out.print(' ');
13868                    service.printComponentShortName(out);
13869            if (count > 1) {
13870                out.print(" ("); out.print(count); out.print(" filters)");
13871            }
13872            out.println();
13873        }
13874
13875//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13876//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13877//            final List<ResolveInfo> retList = Lists.newArrayList();
13878//            while (i.hasNext()) {
13879//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13880//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13881//                    retList.add(resolveInfo);
13882//                }
13883//            }
13884//            return retList;
13885//        }
13886
13887        // Keys are String (activity class name), values are Activity.
13888        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13889                = new ArrayMap<ComponentName, PackageParser.Service>();
13890        private int mFlags;
13891    }
13892
13893    private final class ProviderIntentResolver
13894            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13895        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13896                boolean defaultOnly, int userId) {
13897            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13898            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13899        }
13900
13901        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13902                int userId) {
13903            if (!sUserManager.exists(userId))
13904                return null;
13905            mFlags = flags;
13906            return super.queryIntent(intent, resolvedType,
13907                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13908                    userId);
13909        }
13910
13911        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13912                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13913            if (!sUserManager.exists(userId))
13914                return null;
13915            if (packageProviders == null) {
13916                return null;
13917            }
13918            mFlags = flags;
13919            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13920            final int N = packageProviders.size();
13921            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13922                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13923
13924            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13925            for (int i = 0; i < N; ++i) {
13926                intentFilters = packageProviders.get(i).intents;
13927                if (intentFilters != null && intentFilters.size() > 0) {
13928                    PackageParser.ProviderIntentInfo[] array =
13929                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13930                    intentFilters.toArray(array);
13931                    listCut.add(array);
13932                }
13933            }
13934            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13935        }
13936
13937        public final void addProvider(PackageParser.Provider p) {
13938            if (mProviders.containsKey(p.getComponentName())) {
13939                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13940                return;
13941            }
13942
13943            mProviders.put(p.getComponentName(), p);
13944            if (DEBUG_SHOW_INFO) {
13945                Log.v(TAG, "  "
13946                        + (p.info.nonLocalizedLabel != null
13947                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13948                Log.v(TAG, "    Class=" + p.info.name);
13949            }
13950            final int NI = p.intents.size();
13951            int j;
13952            for (j = 0; j < NI; j++) {
13953                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13954                if (DEBUG_SHOW_INFO) {
13955                    Log.v(TAG, "    IntentFilter:");
13956                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13957                }
13958                if (!intent.debugCheck()) {
13959                    Log.w(TAG, "==> For Provider " + p.info.name);
13960                }
13961                addFilter(intent);
13962            }
13963        }
13964
13965        public final void removeProvider(PackageParser.Provider p) {
13966            mProviders.remove(p.getComponentName());
13967            if (DEBUG_SHOW_INFO) {
13968                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13969                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13970                Log.v(TAG, "    Class=" + p.info.name);
13971            }
13972            final int NI = p.intents.size();
13973            int j;
13974            for (j = 0; j < NI; j++) {
13975                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13976                if (DEBUG_SHOW_INFO) {
13977                    Log.v(TAG, "    IntentFilter:");
13978                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13979                }
13980                removeFilter(intent);
13981            }
13982        }
13983
13984        @Override
13985        protected boolean allowFilterResult(
13986                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13987            ProviderInfo filterPi = filter.provider.info;
13988            for (int i = dest.size() - 1; i >= 0; i--) {
13989                ProviderInfo destPi = dest.get(i).providerInfo;
13990                if (destPi.name == filterPi.name
13991                        && destPi.packageName == filterPi.packageName) {
13992                    return false;
13993                }
13994            }
13995            return true;
13996        }
13997
13998        @Override
13999        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14000            return new PackageParser.ProviderIntentInfo[size];
14001        }
14002
14003        @Override
14004        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14005            if (!sUserManager.exists(userId))
14006                return true;
14007            PackageParser.Package p = filter.provider.owner;
14008            if (p != null) {
14009                PackageSetting ps = (PackageSetting) p.mExtras;
14010                if (ps != null) {
14011                    // System apps are never considered stopped for purposes of
14012                    // filtering, because there may be no way for the user to
14013                    // actually re-launch them.
14014                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14015                            && ps.getStopped(userId);
14016                }
14017            }
14018            return false;
14019        }
14020
14021        @Override
14022        protected boolean isPackageForFilter(String packageName,
14023                PackageParser.ProviderIntentInfo info) {
14024            return packageName.equals(info.provider.owner.packageName);
14025        }
14026
14027        @Override
14028        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14029                int match, int userId) {
14030            if (!sUserManager.exists(userId))
14031                return null;
14032            final PackageParser.ProviderIntentInfo info = filter;
14033            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14034                return null;
14035            }
14036            final PackageParser.Provider provider = info.provider;
14037            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14038            if (ps == null) {
14039                return null;
14040            }
14041            final PackageUserState userState = ps.readUserState(userId);
14042            final boolean matchVisibleToInstantApp =
14043                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14044            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14045            // throw out filters that aren't visible to instant applications
14046            if (matchVisibleToInstantApp
14047                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14048                return null;
14049            }
14050            // throw out instant application filters if we're not explicitly requesting them
14051            if (!isInstantApp && userState.instantApp) {
14052                return null;
14053            }
14054            // throw out instant application filters if updates are available; will trigger
14055            // instant application resolution
14056            if (userState.instantApp && ps.isUpdateAvailable()) {
14057                return null;
14058            }
14059            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14060                    userState, userId);
14061            if (pi == null) {
14062                return null;
14063            }
14064            final ResolveInfo res = new ResolveInfo();
14065            res.providerInfo = pi;
14066            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14067                res.filter = filter;
14068            }
14069            res.priority = info.getPriority();
14070            res.preferredOrder = provider.owner.mPreferredOrder;
14071            res.match = match;
14072            res.isDefault = info.hasDefault;
14073            res.labelRes = info.labelRes;
14074            res.nonLocalizedLabel = info.nonLocalizedLabel;
14075            res.icon = info.icon;
14076            res.system = res.providerInfo.applicationInfo.isSystemApp();
14077            return res;
14078        }
14079
14080        @Override
14081        protected void sortResults(List<ResolveInfo> results) {
14082            Collections.sort(results, mResolvePrioritySorter);
14083        }
14084
14085        @Override
14086        protected void dumpFilter(PrintWriter out, String prefix,
14087                PackageParser.ProviderIntentInfo filter) {
14088            out.print(prefix);
14089            out.print(
14090                    Integer.toHexString(System.identityHashCode(filter.provider)));
14091            out.print(' ');
14092            filter.provider.printComponentShortName(out);
14093            out.print(" filter ");
14094            out.println(Integer.toHexString(System.identityHashCode(filter)));
14095        }
14096
14097        @Override
14098        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14099            return filter.provider;
14100        }
14101
14102        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14103            PackageParser.Provider provider = (PackageParser.Provider)label;
14104            out.print(prefix); out.print(
14105                    Integer.toHexString(System.identityHashCode(provider)));
14106                    out.print(' ');
14107                    provider.printComponentShortName(out);
14108            if (count > 1) {
14109                out.print(" ("); out.print(count); out.print(" filters)");
14110            }
14111            out.println();
14112        }
14113
14114        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14115                = new ArrayMap<ComponentName, PackageParser.Provider>();
14116        private int mFlags;
14117    }
14118
14119    static final class EphemeralIntentResolver
14120            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14121        /**
14122         * The result that has the highest defined order. Ordering applies on a
14123         * per-package basis. Mapping is from package name to Pair of order and
14124         * EphemeralResolveInfo.
14125         * <p>
14126         * NOTE: This is implemented as a field variable for convenience and efficiency.
14127         * By having a field variable, we're able to track filter ordering as soon as
14128         * a non-zero order is defined. Otherwise, multiple loops across the result set
14129         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14130         * this needs to be contained entirely within {@link #filterResults}.
14131         */
14132        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14133
14134        @Override
14135        protected AuxiliaryResolveInfo[] newArray(int size) {
14136            return new AuxiliaryResolveInfo[size];
14137        }
14138
14139        @Override
14140        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14141            return true;
14142        }
14143
14144        @Override
14145        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14146                int userId) {
14147            if (!sUserManager.exists(userId)) {
14148                return null;
14149            }
14150            final String packageName = responseObj.resolveInfo.getPackageName();
14151            final Integer order = responseObj.getOrder();
14152            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14153                    mOrderResult.get(packageName);
14154            // ordering is enabled and this item's order isn't high enough
14155            if (lastOrderResult != null && lastOrderResult.first >= order) {
14156                return null;
14157            }
14158            final InstantAppResolveInfo res = responseObj.resolveInfo;
14159            if (order > 0) {
14160                // non-zero order, enable ordering
14161                mOrderResult.put(packageName, new Pair<>(order, res));
14162            }
14163            return responseObj;
14164        }
14165
14166        @Override
14167        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14168            // only do work if ordering is enabled [most of the time it won't be]
14169            if (mOrderResult.size() == 0) {
14170                return;
14171            }
14172            int resultSize = results.size();
14173            for (int i = 0; i < resultSize; i++) {
14174                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14175                final String packageName = info.getPackageName();
14176                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14177                if (savedInfo == null) {
14178                    // package doesn't having ordering
14179                    continue;
14180                }
14181                if (savedInfo.second == info) {
14182                    // circled back to the highest ordered item; remove from order list
14183                    mOrderResult.remove(savedInfo);
14184                    if (mOrderResult.size() == 0) {
14185                        // no more ordered items
14186                        break;
14187                    }
14188                    continue;
14189                }
14190                // item has a worse order, remove it from the result list
14191                results.remove(i);
14192                resultSize--;
14193                i--;
14194            }
14195        }
14196    }
14197
14198    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14199            new Comparator<ResolveInfo>() {
14200        public int compare(ResolveInfo r1, ResolveInfo r2) {
14201            int v1 = r1.priority;
14202            int v2 = r2.priority;
14203            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14204            if (v1 != v2) {
14205                return (v1 > v2) ? -1 : 1;
14206            }
14207            v1 = r1.preferredOrder;
14208            v2 = r2.preferredOrder;
14209            if (v1 != v2) {
14210                return (v1 > v2) ? -1 : 1;
14211            }
14212            if (r1.isDefault != r2.isDefault) {
14213                return r1.isDefault ? -1 : 1;
14214            }
14215            v1 = r1.match;
14216            v2 = r2.match;
14217            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14218            if (v1 != v2) {
14219                return (v1 > v2) ? -1 : 1;
14220            }
14221            if (r1.system != r2.system) {
14222                return r1.system ? -1 : 1;
14223            }
14224            if (r1.activityInfo != null) {
14225                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14226            }
14227            if (r1.serviceInfo != null) {
14228                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14229            }
14230            if (r1.providerInfo != null) {
14231                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14232            }
14233            return 0;
14234        }
14235    };
14236
14237    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14238            new Comparator<ProviderInfo>() {
14239        public int compare(ProviderInfo p1, ProviderInfo p2) {
14240            final int v1 = p1.initOrder;
14241            final int v2 = p2.initOrder;
14242            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14243        }
14244    };
14245
14246    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14247            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14248            final int[] userIds) {
14249        mHandler.post(new Runnable() {
14250            @Override
14251            public void run() {
14252                try {
14253                    final IActivityManager am = ActivityManager.getService();
14254                    if (am == null) return;
14255                    final int[] resolvedUserIds;
14256                    if (userIds == null) {
14257                        resolvedUserIds = am.getRunningUserIds();
14258                    } else {
14259                        resolvedUserIds = userIds;
14260                    }
14261                    for (int id : resolvedUserIds) {
14262                        final Intent intent = new Intent(action,
14263                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14264                        if (extras != null) {
14265                            intent.putExtras(extras);
14266                        }
14267                        if (targetPkg != null) {
14268                            intent.setPackage(targetPkg);
14269                        }
14270                        // Modify the UID when posting to other users
14271                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14272                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14273                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14274                            intent.putExtra(Intent.EXTRA_UID, uid);
14275                        }
14276                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14277                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14278                        if (DEBUG_BROADCASTS) {
14279                            RuntimeException here = new RuntimeException("here");
14280                            here.fillInStackTrace();
14281                            Slog.d(TAG, "Sending to user " + id + ": "
14282                                    + intent.toShortString(false, true, false, false)
14283                                    + " " + intent.getExtras(), here);
14284                        }
14285                        am.broadcastIntent(null, intent, null, finishedReceiver,
14286                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14287                                null, finishedReceiver != null, false, id);
14288                    }
14289                } catch (RemoteException ex) {
14290                }
14291            }
14292        });
14293    }
14294
14295    /**
14296     * Check if the external storage media is available. This is true if there
14297     * is a mounted external storage medium or if the external storage is
14298     * emulated.
14299     */
14300    private boolean isExternalMediaAvailable() {
14301        return mMediaMounted || Environment.isExternalStorageEmulated();
14302    }
14303
14304    @Override
14305    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14306        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14307            return null;
14308        }
14309        // writer
14310        synchronized (mPackages) {
14311            if (!isExternalMediaAvailable()) {
14312                // If the external storage is no longer mounted at this point,
14313                // the caller may not have been able to delete all of this
14314                // packages files and can not delete any more.  Bail.
14315                return null;
14316            }
14317            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14318            if (lastPackage != null) {
14319                pkgs.remove(lastPackage);
14320            }
14321            if (pkgs.size() > 0) {
14322                return pkgs.get(0);
14323            }
14324        }
14325        return null;
14326    }
14327
14328    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14329        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14330                userId, andCode ? 1 : 0, packageName);
14331        if (mSystemReady) {
14332            msg.sendToTarget();
14333        } else {
14334            if (mPostSystemReadyMessages == null) {
14335                mPostSystemReadyMessages = new ArrayList<>();
14336            }
14337            mPostSystemReadyMessages.add(msg);
14338        }
14339    }
14340
14341    void startCleaningPackages() {
14342        // reader
14343        if (!isExternalMediaAvailable()) {
14344            return;
14345        }
14346        synchronized (mPackages) {
14347            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14348                return;
14349            }
14350        }
14351        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14352        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14353        IActivityManager am = ActivityManager.getService();
14354        if (am != null) {
14355            int dcsUid = -1;
14356            synchronized (mPackages) {
14357                if (!mDefaultContainerWhitelisted) {
14358                    mDefaultContainerWhitelisted = true;
14359                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14360                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14361                }
14362            }
14363            try {
14364                if (dcsUid > 0) {
14365                    am.backgroundWhitelistUid(dcsUid);
14366                }
14367                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14368                        UserHandle.USER_SYSTEM);
14369            } catch (RemoteException e) {
14370            }
14371        }
14372    }
14373
14374    @Override
14375    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14376            int installFlags, String installerPackageName, int userId) {
14377        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14378
14379        final int callingUid = Binder.getCallingUid();
14380        enforceCrossUserPermission(callingUid, userId,
14381                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14382
14383        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14384            try {
14385                if (observer != null) {
14386                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14387                }
14388            } catch (RemoteException re) {
14389            }
14390            return;
14391        }
14392
14393        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14394            installFlags |= PackageManager.INSTALL_FROM_ADB;
14395
14396        } else {
14397            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14398            // about installerPackageName.
14399
14400            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14401            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14402        }
14403
14404        UserHandle user;
14405        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14406            user = UserHandle.ALL;
14407        } else {
14408            user = new UserHandle(userId);
14409        }
14410
14411        // Only system components can circumvent runtime permissions when installing.
14412        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14413                && mContext.checkCallingOrSelfPermission(Manifest.permission
14414                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14415            throw new SecurityException("You need the "
14416                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14417                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14418        }
14419
14420        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14421                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14422            throw new IllegalArgumentException(
14423                    "New installs into ASEC containers no longer supported");
14424        }
14425
14426        final File originFile = new File(originPath);
14427        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14428
14429        final Message msg = mHandler.obtainMessage(INIT_COPY);
14430        final VerificationInfo verificationInfo = new VerificationInfo(
14431                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14432        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14433                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14434                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14435                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14436        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14437        msg.obj = params;
14438
14439        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14440                System.identityHashCode(msg.obj));
14441        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14442                System.identityHashCode(msg.obj));
14443
14444        mHandler.sendMessage(msg);
14445    }
14446
14447
14448    /**
14449     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14450     * it is acting on behalf on an enterprise or the user).
14451     *
14452     * Note that the ordering of the conditionals in this method is important. The checks we perform
14453     * are as follows, in this order:
14454     *
14455     * 1) If the install is being performed by a system app, we can trust the app to have set the
14456     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14457     *    what it is.
14458     * 2) If the install is being performed by a device or profile owner app, the install reason
14459     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14460     *    set the install reason correctly. If the app targets an older SDK version where install
14461     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14462     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14463     * 3) In all other cases, the install is being performed by a regular app that is neither part
14464     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14465     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14466     *    set to enterprise policy and if so, change it to unknown instead.
14467     */
14468    private int fixUpInstallReason(String installerPackageName, int installerUid,
14469            int installReason) {
14470        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14471                == PERMISSION_GRANTED) {
14472            // If the install is being performed by a system app, we trust that app to have set the
14473            // install reason correctly.
14474            return installReason;
14475        }
14476
14477        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14478            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14479        if (dpm != null) {
14480            ComponentName owner = null;
14481            try {
14482                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14483                if (owner == null) {
14484                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14485                }
14486            } catch (RemoteException e) {
14487            }
14488            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14489                // If the install is being performed by a device or profile owner, the install
14490                // reason should be enterprise policy.
14491                return PackageManager.INSTALL_REASON_POLICY;
14492            }
14493        }
14494
14495        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14496            // If the install is being performed by a regular app (i.e. neither system app nor
14497            // device or profile owner), we have no reason to believe that the app is acting on
14498            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14499            // change it to unknown instead.
14500            return PackageManager.INSTALL_REASON_UNKNOWN;
14501        }
14502
14503        // If the install is being performed by a regular app and the install reason was set to any
14504        // value but enterprise policy, leave the install reason unchanged.
14505        return installReason;
14506    }
14507
14508    void installStage(String packageName, File stagedDir, String stagedCid,
14509            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14510            String installerPackageName, int installerUid, UserHandle user,
14511            Certificate[][] certificates) {
14512        if (DEBUG_EPHEMERAL) {
14513            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14514                Slog.d(TAG, "Ephemeral install of " + packageName);
14515            }
14516        }
14517        final VerificationInfo verificationInfo = new VerificationInfo(
14518                sessionParams.originatingUri, sessionParams.referrerUri,
14519                sessionParams.originatingUid, installerUid);
14520
14521        final OriginInfo origin;
14522        if (stagedDir != null) {
14523            origin = OriginInfo.fromStagedFile(stagedDir);
14524        } else {
14525            origin = OriginInfo.fromStagedContainer(stagedCid);
14526        }
14527
14528        final Message msg = mHandler.obtainMessage(INIT_COPY);
14529        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14530                sessionParams.installReason);
14531        final InstallParams params = new InstallParams(origin, null, observer,
14532                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14533                verificationInfo, user, sessionParams.abiOverride,
14534                sessionParams.grantedRuntimePermissions, certificates, installReason);
14535        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14536        msg.obj = params;
14537
14538        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14539                System.identityHashCode(msg.obj));
14540        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14541                System.identityHashCode(msg.obj));
14542
14543        mHandler.sendMessage(msg);
14544    }
14545
14546    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14547            int userId) {
14548        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14549        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14550
14551        // Send a session commit broadcast
14552        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14553        info.installReason = pkgSetting.getInstallReason(userId);
14554        info.appPackageName = packageName;
14555        sendSessionCommitBroadcast(info, userId);
14556    }
14557
14558    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14559        if (ArrayUtils.isEmpty(userIds)) {
14560            return;
14561        }
14562        Bundle extras = new Bundle(1);
14563        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14564        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14565
14566        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14567                packageName, extras, 0, null, null, userIds);
14568        if (isSystem) {
14569            mHandler.post(() -> {
14570                        for (int userId : userIds) {
14571                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14572                        }
14573                    }
14574            );
14575        }
14576    }
14577
14578    /**
14579     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14580     * automatically without needing an explicit launch.
14581     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14582     */
14583    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14584        // If user is not running, the app didn't miss any broadcast
14585        if (!mUserManagerInternal.isUserRunning(userId)) {
14586            return;
14587        }
14588        final IActivityManager am = ActivityManager.getService();
14589        try {
14590            // Deliver LOCKED_BOOT_COMPLETED first
14591            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14592                    .setPackage(packageName);
14593            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14594            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14595                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14596
14597            // Deliver BOOT_COMPLETED only if user is unlocked
14598            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14599                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14600                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14601                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14602            }
14603        } catch (RemoteException e) {
14604            throw e.rethrowFromSystemServer();
14605        }
14606    }
14607
14608    @Override
14609    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14610            int userId) {
14611        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14612        PackageSetting pkgSetting;
14613        final int callingUid = Binder.getCallingUid();
14614        enforceCrossUserPermission(callingUid, userId,
14615                true /* requireFullPermission */, true /* checkShell */,
14616                "setApplicationHiddenSetting for user " + userId);
14617
14618        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14619            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14620            return false;
14621        }
14622
14623        long callingId = Binder.clearCallingIdentity();
14624        try {
14625            boolean sendAdded = false;
14626            boolean sendRemoved = false;
14627            // writer
14628            synchronized (mPackages) {
14629                pkgSetting = mSettings.mPackages.get(packageName);
14630                if (pkgSetting == null) {
14631                    return false;
14632                }
14633                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14634                    return false;
14635                }
14636                // Do not allow "android" is being disabled
14637                if ("android".equals(packageName)) {
14638                    Slog.w(TAG, "Cannot hide package: android");
14639                    return false;
14640                }
14641                // Cannot hide static shared libs as they are considered
14642                // a part of the using app (emulating static linking). Also
14643                // static libs are installed always on internal storage.
14644                PackageParser.Package pkg = mPackages.get(packageName);
14645                if (pkg != null && pkg.staticSharedLibName != null) {
14646                    Slog.w(TAG, "Cannot hide package: " + packageName
14647                            + " providing static shared library: "
14648                            + pkg.staticSharedLibName);
14649                    return false;
14650                }
14651                // Only allow protected packages to hide themselves.
14652                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14653                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14654                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14655                    return false;
14656                }
14657
14658                if (pkgSetting.getHidden(userId) != hidden) {
14659                    pkgSetting.setHidden(hidden, userId);
14660                    mSettings.writePackageRestrictionsLPr(userId);
14661                    if (hidden) {
14662                        sendRemoved = true;
14663                    } else {
14664                        sendAdded = true;
14665                    }
14666                }
14667            }
14668            if (sendAdded) {
14669                sendPackageAddedForUser(packageName, pkgSetting, userId);
14670                return true;
14671            }
14672            if (sendRemoved) {
14673                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14674                        "hiding pkg");
14675                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14676                return true;
14677            }
14678        } finally {
14679            Binder.restoreCallingIdentity(callingId);
14680        }
14681        return false;
14682    }
14683
14684    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14685            int userId) {
14686        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14687        info.removedPackage = packageName;
14688        info.installerPackageName = pkgSetting.installerPackageName;
14689        info.removedUsers = new int[] {userId};
14690        info.broadcastUsers = new int[] {userId};
14691        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14692        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14693    }
14694
14695    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14696        if (pkgList.length > 0) {
14697            Bundle extras = new Bundle(1);
14698            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14699
14700            sendPackageBroadcast(
14701                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14702                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14703                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14704                    new int[] {userId});
14705        }
14706    }
14707
14708    /**
14709     * Returns true if application is not found or there was an error. Otherwise it returns
14710     * the hidden state of the package for the given user.
14711     */
14712    @Override
14713    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14714        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14715        final int callingUid = Binder.getCallingUid();
14716        enforceCrossUserPermission(callingUid, userId,
14717                true /* requireFullPermission */, false /* checkShell */,
14718                "getApplicationHidden for user " + userId);
14719        PackageSetting ps;
14720        long callingId = Binder.clearCallingIdentity();
14721        try {
14722            // writer
14723            synchronized (mPackages) {
14724                ps = mSettings.mPackages.get(packageName);
14725                if (ps == null) {
14726                    return true;
14727                }
14728                if (filterAppAccessLPr(ps, callingUid, userId)) {
14729                    return true;
14730                }
14731                return ps.getHidden(userId);
14732            }
14733        } finally {
14734            Binder.restoreCallingIdentity(callingId);
14735        }
14736    }
14737
14738    /**
14739     * @hide
14740     */
14741    @Override
14742    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14743            int installReason) {
14744        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14745                null);
14746        PackageSetting pkgSetting;
14747        final int callingUid = Binder.getCallingUid();
14748        enforceCrossUserPermission(callingUid, userId,
14749                true /* requireFullPermission */, true /* checkShell */,
14750                "installExistingPackage for user " + userId);
14751        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14752            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14753        }
14754
14755        long callingId = Binder.clearCallingIdentity();
14756        try {
14757            boolean installed = false;
14758            final boolean instantApp =
14759                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14760            final boolean fullApp =
14761                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14762
14763            // writer
14764            synchronized (mPackages) {
14765                pkgSetting = mSettings.mPackages.get(packageName);
14766                if (pkgSetting == null) {
14767                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14768                }
14769                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14770                    // only allow the existing package to be used if it's installed as a full
14771                    // application for at least one user
14772                    boolean installAllowed = false;
14773                    for (int checkUserId : sUserManager.getUserIds()) {
14774                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14775                        if (installAllowed) {
14776                            break;
14777                        }
14778                    }
14779                    if (!installAllowed) {
14780                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14781                    }
14782                }
14783                if (!pkgSetting.getInstalled(userId)) {
14784                    pkgSetting.setInstalled(true, userId);
14785                    pkgSetting.setHidden(false, userId);
14786                    pkgSetting.setInstallReason(installReason, userId);
14787                    mSettings.writePackageRestrictionsLPr(userId);
14788                    mSettings.writeKernelMappingLPr(pkgSetting);
14789                    installed = true;
14790                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14791                    // upgrade app from instant to full; we don't allow app downgrade
14792                    installed = true;
14793                }
14794                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14795            }
14796
14797            if (installed) {
14798                if (pkgSetting.pkg != null) {
14799                    synchronized (mInstallLock) {
14800                        // We don't need to freeze for a brand new install
14801                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14802                    }
14803                }
14804                sendPackageAddedForUser(packageName, pkgSetting, userId);
14805                synchronized (mPackages) {
14806                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14807                }
14808            }
14809        } finally {
14810            Binder.restoreCallingIdentity(callingId);
14811        }
14812
14813        return PackageManager.INSTALL_SUCCEEDED;
14814    }
14815
14816    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14817            boolean instantApp, boolean fullApp) {
14818        // no state specified; do nothing
14819        if (!instantApp && !fullApp) {
14820            return;
14821        }
14822        if (userId != UserHandle.USER_ALL) {
14823            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14824                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14825            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14826                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14827            }
14828        } else {
14829            for (int currentUserId : sUserManager.getUserIds()) {
14830                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14831                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14832                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14833                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14834                }
14835            }
14836        }
14837    }
14838
14839    boolean isUserRestricted(int userId, String restrictionKey) {
14840        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14841        if (restrictions.getBoolean(restrictionKey, false)) {
14842            Log.w(TAG, "User is restricted: " + restrictionKey);
14843            return true;
14844        }
14845        return false;
14846    }
14847
14848    @Override
14849    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14850            int userId) {
14851        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14852        final int callingUid = Binder.getCallingUid();
14853        enforceCrossUserPermission(callingUid, userId,
14854                true /* requireFullPermission */, true /* checkShell */,
14855                "setPackagesSuspended for user " + userId);
14856
14857        if (ArrayUtils.isEmpty(packageNames)) {
14858            return packageNames;
14859        }
14860
14861        // List of package names for whom the suspended state has changed.
14862        List<String> changedPackages = new ArrayList<>(packageNames.length);
14863        // List of package names for whom the suspended state is not set as requested in this
14864        // method.
14865        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14866        long callingId = Binder.clearCallingIdentity();
14867        try {
14868            for (int i = 0; i < packageNames.length; i++) {
14869                String packageName = packageNames[i];
14870                boolean changed = false;
14871                final int appId;
14872                synchronized (mPackages) {
14873                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14874                    if (pkgSetting == null
14875                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14876                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14877                                + "\". Skipping suspending/un-suspending.");
14878                        unactionedPackages.add(packageName);
14879                        continue;
14880                    }
14881                    appId = pkgSetting.appId;
14882                    if (pkgSetting.getSuspended(userId) != suspended) {
14883                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14884                            unactionedPackages.add(packageName);
14885                            continue;
14886                        }
14887                        pkgSetting.setSuspended(suspended, userId);
14888                        mSettings.writePackageRestrictionsLPr(userId);
14889                        changed = true;
14890                        changedPackages.add(packageName);
14891                    }
14892                }
14893
14894                if (changed && suspended) {
14895                    killApplication(packageName, UserHandle.getUid(userId, appId),
14896                            "suspending package");
14897                }
14898            }
14899        } finally {
14900            Binder.restoreCallingIdentity(callingId);
14901        }
14902
14903        if (!changedPackages.isEmpty()) {
14904            sendPackagesSuspendedForUser(changedPackages.toArray(
14905                    new String[changedPackages.size()]), userId, suspended);
14906        }
14907
14908        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14909    }
14910
14911    @Override
14912    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14913        final int callingUid = Binder.getCallingUid();
14914        enforceCrossUserPermission(callingUid, userId,
14915                true /* requireFullPermission */, false /* checkShell */,
14916                "isPackageSuspendedForUser for user " + userId);
14917        synchronized (mPackages) {
14918            final PackageSetting ps = mSettings.mPackages.get(packageName);
14919            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14920                throw new IllegalArgumentException("Unknown target package: " + packageName);
14921            }
14922            return ps.getSuspended(userId);
14923        }
14924    }
14925
14926    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14927        if (isPackageDeviceAdmin(packageName, userId)) {
14928            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14929                    + "\": has an active device admin");
14930            return false;
14931        }
14932
14933        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14934        if (packageName.equals(activeLauncherPackageName)) {
14935            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14936                    + "\": contains the active launcher");
14937            return false;
14938        }
14939
14940        if (packageName.equals(mRequiredInstallerPackage)) {
14941            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14942                    + "\": required for package installation");
14943            return false;
14944        }
14945
14946        if (packageName.equals(mRequiredUninstallerPackage)) {
14947            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14948                    + "\": required for package uninstallation");
14949            return false;
14950        }
14951
14952        if (packageName.equals(mRequiredVerifierPackage)) {
14953            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14954                    + "\": required for package verification");
14955            return false;
14956        }
14957
14958        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14959            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14960                    + "\": is the default dialer");
14961            return false;
14962        }
14963
14964        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14965            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14966                    + "\": protected package");
14967            return false;
14968        }
14969
14970        // Cannot suspend static shared libs as they are considered
14971        // a part of the using app (emulating static linking). Also
14972        // static libs are installed always on internal storage.
14973        PackageParser.Package pkg = mPackages.get(packageName);
14974        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14975            Slog.w(TAG, "Cannot suspend package: " + packageName
14976                    + " providing static shared library: "
14977                    + pkg.staticSharedLibName);
14978            return false;
14979        }
14980
14981        return true;
14982    }
14983
14984    private String getActiveLauncherPackageName(int userId) {
14985        Intent intent = new Intent(Intent.ACTION_MAIN);
14986        intent.addCategory(Intent.CATEGORY_HOME);
14987        ResolveInfo resolveInfo = resolveIntent(
14988                intent,
14989                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14990                PackageManager.MATCH_DEFAULT_ONLY,
14991                userId);
14992
14993        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14994    }
14995
14996    private String getDefaultDialerPackageName(int userId) {
14997        synchronized (mPackages) {
14998            return mSettings.getDefaultDialerPackageNameLPw(userId);
14999        }
15000    }
15001
15002    @Override
15003    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15004        mContext.enforceCallingOrSelfPermission(
15005                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15006                "Only package verification agents can verify applications");
15007
15008        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15009        final PackageVerificationResponse response = new PackageVerificationResponse(
15010                verificationCode, Binder.getCallingUid());
15011        msg.arg1 = id;
15012        msg.obj = response;
15013        mHandler.sendMessage(msg);
15014    }
15015
15016    @Override
15017    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15018            long millisecondsToDelay) {
15019        mContext.enforceCallingOrSelfPermission(
15020                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15021                "Only package verification agents can extend verification timeouts");
15022
15023        final PackageVerificationState state = mPendingVerification.get(id);
15024        final PackageVerificationResponse response = new PackageVerificationResponse(
15025                verificationCodeAtTimeout, Binder.getCallingUid());
15026
15027        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15028            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15029        }
15030        if (millisecondsToDelay < 0) {
15031            millisecondsToDelay = 0;
15032        }
15033        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15034                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15035            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15036        }
15037
15038        if ((state != null) && !state.timeoutExtended()) {
15039            state.extendTimeout();
15040
15041            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15042            msg.arg1 = id;
15043            msg.obj = response;
15044            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15045        }
15046    }
15047
15048    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15049            int verificationCode, UserHandle user) {
15050        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15051        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15052        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15053        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15054        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15055
15056        mContext.sendBroadcastAsUser(intent, user,
15057                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15058    }
15059
15060    private ComponentName matchComponentForVerifier(String packageName,
15061            List<ResolveInfo> receivers) {
15062        ActivityInfo targetReceiver = null;
15063
15064        final int NR = receivers.size();
15065        for (int i = 0; i < NR; i++) {
15066            final ResolveInfo info = receivers.get(i);
15067            if (info.activityInfo == null) {
15068                continue;
15069            }
15070
15071            if (packageName.equals(info.activityInfo.packageName)) {
15072                targetReceiver = info.activityInfo;
15073                break;
15074            }
15075        }
15076
15077        if (targetReceiver == null) {
15078            return null;
15079        }
15080
15081        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15082    }
15083
15084    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15085            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15086        if (pkgInfo.verifiers.length == 0) {
15087            return null;
15088        }
15089
15090        final int N = pkgInfo.verifiers.length;
15091        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15092        for (int i = 0; i < N; i++) {
15093            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15094
15095            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15096                    receivers);
15097            if (comp == null) {
15098                continue;
15099            }
15100
15101            final int verifierUid = getUidForVerifier(verifierInfo);
15102            if (verifierUid == -1) {
15103                continue;
15104            }
15105
15106            if (DEBUG_VERIFY) {
15107                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15108                        + " with the correct signature");
15109            }
15110            sufficientVerifiers.add(comp);
15111            verificationState.addSufficientVerifier(verifierUid);
15112        }
15113
15114        return sufficientVerifiers;
15115    }
15116
15117    private int getUidForVerifier(VerifierInfo verifierInfo) {
15118        synchronized (mPackages) {
15119            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15120            if (pkg == null) {
15121                return -1;
15122            } else if (pkg.mSignatures.length != 1) {
15123                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15124                        + " has more than one signature; ignoring");
15125                return -1;
15126            }
15127
15128            /*
15129             * If the public key of the package's signature does not match
15130             * our expected public key, then this is a different package and
15131             * we should skip.
15132             */
15133
15134            final byte[] expectedPublicKey;
15135            try {
15136                final Signature verifierSig = pkg.mSignatures[0];
15137                final PublicKey publicKey = verifierSig.getPublicKey();
15138                expectedPublicKey = publicKey.getEncoded();
15139            } catch (CertificateException e) {
15140                return -1;
15141            }
15142
15143            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15144
15145            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15146                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15147                        + " does not have the expected public key; ignoring");
15148                return -1;
15149            }
15150
15151            return pkg.applicationInfo.uid;
15152        }
15153    }
15154
15155    @Override
15156    public void finishPackageInstall(int token, boolean didLaunch) {
15157        enforceSystemOrRoot("Only the system is allowed to finish installs");
15158
15159        if (DEBUG_INSTALL) {
15160            Slog.v(TAG, "BM finishing package install for " + token);
15161        }
15162        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15163
15164        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15165        mHandler.sendMessage(msg);
15166    }
15167
15168    /**
15169     * Get the verification agent timeout.  Used for both the APK verifier and the
15170     * intent filter verifier.
15171     *
15172     * @return verification timeout in milliseconds
15173     */
15174    private long getVerificationTimeout() {
15175        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15176                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15177                DEFAULT_VERIFICATION_TIMEOUT);
15178    }
15179
15180    /**
15181     * Get the default verification agent response code.
15182     *
15183     * @return default verification response code
15184     */
15185    private int getDefaultVerificationResponse(UserHandle user) {
15186        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15187            return PackageManager.VERIFICATION_REJECT;
15188        }
15189        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15190                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15191                DEFAULT_VERIFICATION_RESPONSE);
15192    }
15193
15194    /**
15195     * Check whether or not package verification has been enabled.
15196     *
15197     * @return true if verification should be performed
15198     */
15199    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15200        if (!DEFAULT_VERIFY_ENABLE) {
15201            return false;
15202        }
15203
15204        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15205
15206        // Check if installing from ADB
15207        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15208            // Do not run verification in a test harness environment
15209            if (ActivityManager.isRunningInTestHarness()) {
15210                return false;
15211            }
15212            if (ensureVerifyAppsEnabled) {
15213                return true;
15214            }
15215            // Check if the developer does not want package verification for ADB installs
15216            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15217                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15218                return false;
15219            }
15220        } else {
15221            // only when not installed from ADB, skip verification for instant apps when
15222            // the installer and verifier are the same.
15223            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15224                if (mInstantAppInstallerActivity != null
15225                        && mInstantAppInstallerActivity.packageName.equals(
15226                                mRequiredVerifierPackage)) {
15227                    try {
15228                        mContext.getSystemService(AppOpsManager.class)
15229                                .checkPackage(installerUid, mRequiredVerifierPackage);
15230                        if (DEBUG_VERIFY) {
15231                            Slog.i(TAG, "disable verification for instant app");
15232                        }
15233                        return false;
15234                    } catch (SecurityException ignore) { }
15235                }
15236            }
15237        }
15238
15239        if (ensureVerifyAppsEnabled) {
15240            return true;
15241        }
15242
15243        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15244                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15245    }
15246
15247    @Override
15248    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15249            throws RemoteException {
15250        mContext.enforceCallingOrSelfPermission(
15251                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15252                "Only intentfilter verification agents can verify applications");
15253
15254        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15255        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15256                Binder.getCallingUid(), verificationCode, failedDomains);
15257        msg.arg1 = id;
15258        msg.obj = response;
15259        mHandler.sendMessage(msg);
15260    }
15261
15262    @Override
15263    public int getIntentVerificationStatus(String packageName, int userId) {
15264        final int callingUid = Binder.getCallingUid();
15265        if (getInstantAppPackageName(callingUid) != null) {
15266            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15267        }
15268        synchronized (mPackages) {
15269            final PackageSetting ps = mSettings.mPackages.get(packageName);
15270            if (ps == null
15271                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15272                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15273            }
15274            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15275        }
15276    }
15277
15278    @Override
15279    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15280        mContext.enforceCallingOrSelfPermission(
15281                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15282
15283        boolean result = false;
15284        synchronized (mPackages) {
15285            final PackageSetting ps = mSettings.mPackages.get(packageName);
15286            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15287                return false;
15288            }
15289            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15290        }
15291        if (result) {
15292            scheduleWritePackageRestrictionsLocked(userId);
15293        }
15294        return result;
15295    }
15296
15297    @Override
15298    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15299            String packageName) {
15300        final int callingUid = Binder.getCallingUid();
15301        if (getInstantAppPackageName(callingUid) != null) {
15302            return ParceledListSlice.emptyList();
15303        }
15304        synchronized (mPackages) {
15305            final PackageSetting ps = mSettings.mPackages.get(packageName);
15306            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15307                return ParceledListSlice.emptyList();
15308            }
15309            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15310        }
15311    }
15312
15313    @Override
15314    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15315        if (TextUtils.isEmpty(packageName)) {
15316            return ParceledListSlice.emptyList();
15317        }
15318        final int callingUid = Binder.getCallingUid();
15319        final int callingUserId = UserHandle.getUserId(callingUid);
15320        synchronized (mPackages) {
15321            PackageParser.Package pkg = mPackages.get(packageName);
15322            if (pkg == null || pkg.activities == null) {
15323                return ParceledListSlice.emptyList();
15324            }
15325            if (pkg.mExtras == null) {
15326                return ParceledListSlice.emptyList();
15327            }
15328            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15329            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15330                return ParceledListSlice.emptyList();
15331            }
15332            final int count = pkg.activities.size();
15333            ArrayList<IntentFilter> result = new ArrayList<>();
15334            for (int n=0; n<count; n++) {
15335                PackageParser.Activity activity = pkg.activities.get(n);
15336                if (activity.intents != null && activity.intents.size() > 0) {
15337                    result.addAll(activity.intents);
15338                }
15339            }
15340            return new ParceledListSlice<>(result);
15341        }
15342    }
15343
15344    @Override
15345    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15346        mContext.enforceCallingOrSelfPermission(
15347                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15348
15349        synchronized (mPackages) {
15350            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15351            if (packageName != null) {
15352                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15353                        packageName, userId);
15354            }
15355            return result;
15356        }
15357    }
15358
15359    @Override
15360    public String getDefaultBrowserPackageName(int userId) {
15361        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15362            return null;
15363        }
15364        synchronized (mPackages) {
15365            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15366        }
15367    }
15368
15369    /**
15370     * Get the "allow unknown sources" setting.
15371     *
15372     * @return the current "allow unknown sources" setting
15373     */
15374    private int getUnknownSourcesSettings() {
15375        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15376                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15377                -1);
15378    }
15379
15380    @Override
15381    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15382        final int callingUid = Binder.getCallingUid();
15383        if (getInstantAppPackageName(callingUid) != null) {
15384            return;
15385        }
15386        // writer
15387        synchronized (mPackages) {
15388            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15389            if (targetPackageSetting == null
15390                    || filterAppAccessLPr(
15391                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15392                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15393            }
15394
15395            PackageSetting installerPackageSetting;
15396            if (installerPackageName != null) {
15397                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15398                if (installerPackageSetting == null) {
15399                    throw new IllegalArgumentException("Unknown installer package: "
15400                            + installerPackageName);
15401                }
15402            } else {
15403                installerPackageSetting = null;
15404            }
15405
15406            Signature[] callerSignature;
15407            Object obj = mSettings.getUserIdLPr(callingUid);
15408            if (obj != null) {
15409                if (obj instanceof SharedUserSetting) {
15410                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15411                } else if (obj instanceof PackageSetting) {
15412                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15413                } else {
15414                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15415                }
15416            } else {
15417                throw new SecurityException("Unknown calling UID: " + callingUid);
15418            }
15419
15420            // Verify: can't set installerPackageName to a package that is
15421            // not signed with the same cert as the caller.
15422            if (installerPackageSetting != null) {
15423                if (compareSignatures(callerSignature,
15424                        installerPackageSetting.signatures.mSignatures)
15425                        != PackageManager.SIGNATURE_MATCH) {
15426                    throw new SecurityException(
15427                            "Caller does not have same cert as new installer package "
15428                            + installerPackageName);
15429                }
15430            }
15431
15432            // Verify: if target already has an installer package, it must
15433            // be signed with the same cert as the caller.
15434            if (targetPackageSetting.installerPackageName != null) {
15435                PackageSetting setting = mSettings.mPackages.get(
15436                        targetPackageSetting.installerPackageName);
15437                // If the currently set package isn't valid, then it's always
15438                // okay to change it.
15439                if (setting != null) {
15440                    if (compareSignatures(callerSignature,
15441                            setting.signatures.mSignatures)
15442                            != PackageManager.SIGNATURE_MATCH) {
15443                        throw new SecurityException(
15444                                "Caller does not have same cert as old installer package "
15445                                + targetPackageSetting.installerPackageName);
15446                    }
15447                }
15448            }
15449
15450            // Okay!
15451            targetPackageSetting.installerPackageName = installerPackageName;
15452            if (installerPackageName != null) {
15453                mSettings.mInstallerPackages.add(installerPackageName);
15454            }
15455            scheduleWriteSettingsLocked();
15456        }
15457    }
15458
15459    @Override
15460    public void setApplicationCategoryHint(String packageName, int categoryHint,
15461            String callerPackageName) {
15462        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15463            throw new SecurityException("Instant applications don't have access to this method");
15464        }
15465        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15466                callerPackageName);
15467        synchronized (mPackages) {
15468            PackageSetting ps = mSettings.mPackages.get(packageName);
15469            if (ps == null) {
15470                throw new IllegalArgumentException("Unknown target package " + packageName);
15471            }
15472            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15473                throw new IllegalArgumentException("Unknown target package " + packageName);
15474            }
15475            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15476                throw new IllegalArgumentException("Calling package " + callerPackageName
15477                        + " is not installer for " + packageName);
15478            }
15479
15480            if (ps.categoryHint != categoryHint) {
15481                ps.categoryHint = categoryHint;
15482                scheduleWriteSettingsLocked();
15483            }
15484        }
15485    }
15486
15487    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15488        // Queue up an async operation since the package installation may take a little while.
15489        mHandler.post(new Runnable() {
15490            public void run() {
15491                mHandler.removeCallbacks(this);
15492                 // Result object to be returned
15493                PackageInstalledInfo res = new PackageInstalledInfo();
15494                res.setReturnCode(currentStatus);
15495                res.uid = -1;
15496                res.pkg = null;
15497                res.removedInfo = null;
15498                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15499                    args.doPreInstall(res.returnCode);
15500                    synchronized (mInstallLock) {
15501                        installPackageTracedLI(args, res);
15502                    }
15503                    args.doPostInstall(res.returnCode, res.uid);
15504                }
15505
15506                // A restore should be performed at this point if (a) the install
15507                // succeeded, (b) the operation is not an update, and (c) the new
15508                // package has not opted out of backup participation.
15509                final boolean update = res.removedInfo != null
15510                        && res.removedInfo.removedPackage != null;
15511                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15512                boolean doRestore = !update
15513                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15514
15515                // Set up the post-install work request bookkeeping.  This will be used
15516                // and cleaned up by the post-install event handling regardless of whether
15517                // there's a restore pass performed.  Token values are >= 1.
15518                int token;
15519                if (mNextInstallToken < 0) mNextInstallToken = 1;
15520                token = mNextInstallToken++;
15521
15522                PostInstallData data = new PostInstallData(args, res);
15523                mRunningInstalls.put(token, data);
15524                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15525
15526                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15527                    // Pass responsibility to the Backup Manager.  It will perform a
15528                    // restore if appropriate, then pass responsibility back to the
15529                    // Package Manager to run the post-install observer callbacks
15530                    // and broadcasts.
15531                    IBackupManager bm = IBackupManager.Stub.asInterface(
15532                            ServiceManager.getService(Context.BACKUP_SERVICE));
15533                    if (bm != null) {
15534                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15535                                + " to BM for possible restore");
15536                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15537                        try {
15538                            // TODO: http://b/22388012
15539                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15540                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15541                            } else {
15542                                doRestore = false;
15543                            }
15544                        } catch (RemoteException e) {
15545                            // can't happen; the backup manager is local
15546                        } catch (Exception e) {
15547                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15548                            doRestore = false;
15549                        }
15550                    } else {
15551                        Slog.e(TAG, "Backup Manager not found!");
15552                        doRestore = false;
15553                    }
15554                }
15555
15556                if (!doRestore) {
15557                    // No restore possible, or the Backup Manager was mysteriously not
15558                    // available -- just fire the post-install work request directly.
15559                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15560
15561                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15562
15563                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15564                    mHandler.sendMessage(msg);
15565                }
15566            }
15567        });
15568    }
15569
15570    /**
15571     * Callback from PackageSettings whenever an app is first transitioned out of the
15572     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15573     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15574     * here whether the app is the target of an ongoing install, and only send the
15575     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15576     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15577     * handling.
15578     */
15579    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15580        // Serialize this with the rest of the install-process message chain.  In the
15581        // restore-at-install case, this Runnable will necessarily run before the
15582        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15583        // are coherent.  In the non-restore case, the app has already completed install
15584        // and been launched through some other means, so it is not in a problematic
15585        // state for observers to see the FIRST_LAUNCH signal.
15586        mHandler.post(new Runnable() {
15587            @Override
15588            public void run() {
15589                for (int i = 0; i < mRunningInstalls.size(); i++) {
15590                    final PostInstallData data = mRunningInstalls.valueAt(i);
15591                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15592                        continue;
15593                    }
15594                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15595                        // right package; but is it for the right user?
15596                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15597                            if (userId == data.res.newUsers[uIndex]) {
15598                                if (DEBUG_BACKUP) {
15599                                    Slog.i(TAG, "Package " + pkgName
15600                                            + " being restored so deferring FIRST_LAUNCH");
15601                                }
15602                                return;
15603                            }
15604                        }
15605                    }
15606                }
15607                // didn't find it, so not being restored
15608                if (DEBUG_BACKUP) {
15609                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15610                }
15611                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15612            }
15613        });
15614    }
15615
15616    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15617        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15618                installerPkg, null, userIds);
15619    }
15620
15621    private abstract class HandlerParams {
15622        private static final int MAX_RETRIES = 4;
15623
15624        /**
15625         * Number of times startCopy() has been attempted and had a non-fatal
15626         * error.
15627         */
15628        private int mRetries = 0;
15629
15630        /** User handle for the user requesting the information or installation. */
15631        private final UserHandle mUser;
15632        String traceMethod;
15633        int traceCookie;
15634
15635        HandlerParams(UserHandle user) {
15636            mUser = user;
15637        }
15638
15639        UserHandle getUser() {
15640            return mUser;
15641        }
15642
15643        HandlerParams setTraceMethod(String traceMethod) {
15644            this.traceMethod = traceMethod;
15645            return this;
15646        }
15647
15648        HandlerParams setTraceCookie(int traceCookie) {
15649            this.traceCookie = traceCookie;
15650            return this;
15651        }
15652
15653        final boolean startCopy() {
15654            boolean res;
15655            try {
15656                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15657
15658                if (++mRetries > MAX_RETRIES) {
15659                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15660                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15661                    handleServiceError();
15662                    return false;
15663                } else {
15664                    handleStartCopy();
15665                    res = true;
15666                }
15667            } catch (RemoteException e) {
15668                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15669                mHandler.sendEmptyMessage(MCS_RECONNECT);
15670                res = false;
15671            }
15672            handleReturnCode();
15673            return res;
15674        }
15675
15676        final void serviceError() {
15677            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15678            handleServiceError();
15679            handleReturnCode();
15680        }
15681
15682        abstract void handleStartCopy() throws RemoteException;
15683        abstract void handleServiceError();
15684        abstract void handleReturnCode();
15685    }
15686
15687    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15688        for (File path : paths) {
15689            try {
15690                mcs.clearDirectory(path.getAbsolutePath());
15691            } catch (RemoteException e) {
15692            }
15693        }
15694    }
15695
15696    static class OriginInfo {
15697        /**
15698         * Location where install is coming from, before it has been
15699         * copied/renamed into place. This could be a single monolithic APK
15700         * file, or a cluster directory. This location may be untrusted.
15701         */
15702        final File file;
15703        final String cid;
15704
15705        /**
15706         * Flag indicating that {@link #file} or {@link #cid} has already been
15707         * staged, meaning downstream users don't need to defensively copy the
15708         * contents.
15709         */
15710        final boolean staged;
15711
15712        /**
15713         * Flag indicating that {@link #file} or {@link #cid} is an already
15714         * installed app that is being moved.
15715         */
15716        final boolean existing;
15717
15718        final String resolvedPath;
15719        final File resolvedFile;
15720
15721        static OriginInfo fromNothing() {
15722            return new OriginInfo(null, null, false, false);
15723        }
15724
15725        static OriginInfo fromUntrustedFile(File file) {
15726            return new OriginInfo(file, null, false, false);
15727        }
15728
15729        static OriginInfo fromExistingFile(File file) {
15730            return new OriginInfo(file, null, false, true);
15731        }
15732
15733        static OriginInfo fromStagedFile(File file) {
15734            return new OriginInfo(file, null, true, false);
15735        }
15736
15737        static OriginInfo fromStagedContainer(String cid) {
15738            return new OriginInfo(null, cid, true, false);
15739        }
15740
15741        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15742            this.file = file;
15743            this.cid = cid;
15744            this.staged = staged;
15745            this.existing = existing;
15746
15747            if (cid != null) {
15748                resolvedPath = PackageHelper.getSdDir(cid);
15749                resolvedFile = new File(resolvedPath);
15750            } else if (file != null) {
15751                resolvedPath = file.getAbsolutePath();
15752                resolvedFile = file;
15753            } else {
15754                resolvedPath = null;
15755                resolvedFile = null;
15756            }
15757        }
15758    }
15759
15760    static class MoveInfo {
15761        final int moveId;
15762        final String fromUuid;
15763        final String toUuid;
15764        final String packageName;
15765        final String dataAppName;
15766        final int appId;
15767        final String seinfo;
15768        final int targetSdkVersion;
15769
15770        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15771                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15772            this.moveId = moveId;
15773            this.fromUuid = fromUuid;
15774            this.toUuid = toUuid;
15775            this.packageName = packageName;
15776            this.dataAppName = dataAppName;
15777            this.appId = appId;
15778            this.seinfo = seinfo;
15779            this.targetSdkVersion = targetSdkVersion;
15780        }
15781    }
15782
15783    static class VerificationInfo {
15784        /** A constant used to indicate that a uid value is not present. */
15785        public static final int NO_UID = -1;
15786
15787        /** URI referencing where the package was downloaded from. */
15788        final Uri originatingUri;
15789
15790        /** HTTP referrer URI associated with the originatingURI. */
15791        final Uri referrer;
15792
15793        /** UID of the application that the install request originated from. */
15794        final int originatingUid;
15795
15796        /** UID of application requesting the install */
15797        final int installerUid;
15798
15799        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15800            this.originatingUri = originatingUri;
15801            this.referrer = referrer;
15802            this.originatingUid = originatingUid;
15803            this.installerUid = installerUid;
15804        }
15805    }
15806
15807    class InstallParams extends HandlerParams {
15808        final OriginInfo origin;
15809        final MoveInfo move;
15810        final IPackageInstallObserver2 observer;
15811        int installFlags;
15812        final String installerPackageName;
15813        final String volumeUuid;
15814        private InstallArgs mArgs;
15815        private int mRet;
15816        final String packageAbiOverride;
15817        final String[] grantedRuntimePermissions;
15818        final VerificationInfo verificationInfo;
15819        final Certificate[][] certificates;
15820        final int installReason;
15821
15822        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15823                int installFlags, String installerPackageName, String volumeUuid,
15824                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15825                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15826            super(user);
15827            this.origin = origin;
15828            this.move = move;
15829            this.observer = observer;
15830            this.installFlags = installFlags;
15831            this.installerPackageName = installerPackageName;
15832            this.volumeUuid = volumeUuid;
15833            this.verificationInfo = verificationInfo;
15834            this.packageAbiOverride = packageAbiOverride;
15835            this.grantedRuntimePermissions = grantedPermissions;
15836            this.certificates = certificates;
15837            this.installReason = installReason;
15838        }
15839
15840        @Override
15841        public String toString() {
15842            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15843                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15844        }
15845
15846        private int installLocationPolicy(PackageInfoLite pkgLite) {
15847            String packageName = pkgLite.packageName;
15848            int installLocation = pkgLite.installLocation;
15849            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15850            // reader
15851            synchronized (mPackages) {
15852                // Currently installed package which the new package is attempting to replace or
15853                // null if no such package is installed.
15854                PackageParser.Package installedPkg = mPackages.get(packageName);
15855                // Package which currently owns the data which the new package will own if installed.
15856                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15857                // will be null whereas dataOwnerPkg will contain information about the package
15858                // which was uninstalled while keeping its data.
15859                PackageParser.Package dataOwnerPkg = installedPkg;
15860                if (dataOwnerPkg  == null) {
15861                    PackageSetting ps = mSettings.mPackages.get(packageName);
15862                    if (ps != null) {
15863                        dataOwnerPkg = ps.pkg;
15864                    }
15865                }
15866
15867                if (dataOwnerPkg != null) {
15868                    // If installed, the package will get access to data left on the device by its
15869                    // predecessor. As a security measure, this is permited only if this is not a
15870                    // version downgrade or if the predecessor package is marked as debuggable and
15871                    // a downgrade is explicitly requested.
15872                    //
15873                    // On debuggable platform builds, downgrades are permitted even for
15874                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15875                    // not offer security guarantees and thus it's OK to disable some security
15876                    // mechanisms to make debugging/testing easier on those builds. However, even on
15877                    // debuggable builds downgrades of packages are permitted only if requested via
15878                    // installFlags. This is because we aim to keep the behavior of debuggable
15879                    // platform builds as close as possible to the behavior of non-debuggable
15880                    // platform builds.
15881                    final boolean downgradeRequested =
15882                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15883                    final boolean packageDebuggable =
15884                                (dataOwnerPkg.applicationInfo.flags
15885                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15886                    final boolean downgradePermitted =
15887                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15888                    if (!downgradePermitted) {
15889                        try {
15890                            checkDowngrade(dataOwnerPkg, pkgLite);
15891                        } catch (PackageManagerException e) {
15892                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15893                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15894                        }
15895                    }
15896                }
15897
15898                if (installedPkg != null) {
15899                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15900                        // Check for updated system application.
15901                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15902                            if (onSd) {
15903                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15904                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15905                            }
15906                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15907                        } else {
15908                            if (onSd) {
15909                                // Install flag overrides everything.
15910                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15911                            }
15912                            // If current upgrade specifies particular preference
15913                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15914                                // Application explicitly specified internal.
15915                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15916                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15917                                // App explictly prefers external. Let policy decide
15918                            } else {
15919                                // Prefer previous location
15920                                if (isExternal(installedPkg)) {
15921                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15922                                }
15923                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15924                            }
15925                        }
15926                    } else {
15927                        // Invalid install. Return error code
15928                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15929                    }
15930                }
15931            }
15932            // All the special cases have been taken care of.
15933            // Return result based on recommended install location.
15934            if (onSd) {
15935                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15936            }
15937            return pkgLite.recommendedInstallLocation;
15938        }
15939
15940        /*
15941         * Invoke remote method to get package information and install
15942         * location values. Override install location based on default
15943         * policy if needed and then create install arguments based
15944         * on the install location.
15945         */
15946        public void handleStartCopy() throws RemoteException {
15947            int ret = PackageManager.INSTALL_SUCCEEDED;
15948
15949            // If we're already staged, we've firmly committed to an install location
15950            if (origin.staged) {
15951                if (origin.file != null) {
15952                    installFlags |= PackageManager.INSTALL_INTERNAL;
15953                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15954                } else if (origin.cid != null) {
15955                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15956                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15957                } else {
15958                    throw new IllegalStateException("Invalid stage location");
15959                }
15960            }
15961
15962            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15963            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15964            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15965            PackageInfoLite pkgLite = null;
15966
15967            if (onInt && onSd) {
15968                // Check if both bits are set.
15969                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15970                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15971            } else if (onSd && ephemeral) {
15972                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15973                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15974            } else {
15975                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15976                        packageAbiOverride);
15977
15978                if (DEBUG_EPHEMERAL && ephemeral) {
15979                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15980                }
15981
15982                /*
15983                 * If we have too little free space, try to free cache
15984                 * before giving up.
15985                 */
15986                if (!origin.staged && pkgLite.recommendedInstallLocation
15987                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15988                    // TODO: focus freeing disk space on the target device
15989                    final StorageManager storage = StorageManager.from(mContext);
15990                    final long lowThreshold = storage.getStorageLowBytes(
15991                            Environment.getDataDirectory());
15992
15993                    final long sizeBytes = mContainerService.calculateInstalledSize(
15994                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15995
15996                    try {
15997                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15998                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15999                                installFlags, packageAbiOverride);
16000                    } catch (InstallerException e) {
16001                        Slog.w(TAG, "Failed to free cache", e);
16002                    }
16003
16004                    /*
16005                     * The cache free must have deleted the file we
16006                     * downloaded to install.
16007                     *
16008                     * TODO: fix the "freeCache" call to not delete
16009                     *       the file we care about.
16010                     */
16011                    if (pkgLite.recommendedInstallLocation
16012                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16013                        pkgLite.recommendedInstallLocation
16014                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16015                    }
16016                }
16017            }
16018
16019            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16020                int loc = pkgLite.recommendedInstallLocation;
16021                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16022                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16023                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16024                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16025                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16026                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16027                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16028                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16029                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16030                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16031                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16032                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16033                } else {
16034                    // Override with defaults if needed.
16035                    loc = installLocationPolicy(pkgLite);
16036                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16037                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16038                    } else if (!onSd && !onInt) {
16039                        // Override install location with flags
16040                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16041                            // Set the flag to install on external media.
16042                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16043                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16044                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16045                            if (DEBUG_EPHEMERAL) {
16046                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16047                            }
16048                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16049                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16050                                    |PackageManager.INSTALL_INTERNAL);
16051                        } else {
16052                            // Make sure the flag for installing on external
16053                            // media is unset
16054                            installFlags |= PackageManager.INSTALL_INTERNAL;
16055                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16056                        }
16057                    }
16058                }
16059            }
16060
16061            final InstallArgs args = createInstallArgs(this);
16062            mArgs = args;
16063
16064            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16065                // TODO: http://b/22976637
16066                // Apps installed for "all" users use the device owner to verify the app
16067                UserHandle verifierUser = getUser();
16068                if (verifierUser == UserHandle.ALL) {
16069                    verifierUser = UserHandle.SYSTEM;
16070                }
16071
16072                /*
16073                 * Determine if we have any installed package verifiers. If we
16074                 * do, then we'll defer to them to verify the packages.
16075                 */
16076                final int requiredUid = mRequiredVerifierPackage == null ? -1
16077                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16078                                verifierUser.getIdentifier());
16079                final int installerUid =
16080                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16081                if (!origin.existing && requiredUid != -1
16082                        && isVerificationEnabled(
16083                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16084                    final Intent verification = new Intent(
16085                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16086                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16087                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16088                            PACKAGE_MIME_TYPE);
16089                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16090
16091                    // Query all live verifiers based on current user state
16092                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16093                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
16094
16095                    if (DEBUG_VERIFY) {
16096                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16097                                + verification.toString() + " with " + pkgLite.verifiers.length
16098                                + " optional verifiers");
16099                    }
16100
16101                    final int verificationId = mPendingVerificationToken++;
16102
16103                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16104
16105                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16106                            installerPackageName);
16107
16108                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16109                            installFlags);
16110
16111                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16112                            pkgLite.packageName);
16113
16114                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16115                            pkgLite.versionCode);
16116
16117                    if (verificationInfo != null) {
16118                        if (verificationInfo.originatingUri != null) {
16119                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16120                                    verificationInfo.originatingUri);
16121                        }
16122                        if (verificationInfo.referrer != null) {
16123                            verification.putExtra(Intent.EXTRA_REFERRER,
16124                                    verificationInfo.referrer);
16125                        }
16126                        if (verificationInfo.originatingUid >= 0) {
16127                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16128                                    verificationInfo.originatingUid);
16129                        }
16130                        if (verificationInfo.installerUid >= 0) {
16131                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16132                                    verificationInfo.installerUid);
16133                        }
16134                    }
16135
16136                    final PackageVerificationState verificationState = new PackageVerificationState(
16137                            requiredUid, args);
16138
16139                    mPendingVerification.append(verificationId, verificationState);
16140
16141                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16142                            receivers, verificationState);
16143
16144                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16145                    final long idleDuration = getVerificationTimeout();
16146
16147                    /*
16148                     * If any sufficient verifiers were listed in the package
16149                     * manifest, attempt to ask them.
16150                     */
16151                    if (sufficientVerifiers != null) {
16152                        final int N = sufficientVerifiers.size();
16153                        if (N == 0) {
16154                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16155                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16156                        } else {
16157                            for (int i = 0; i < N; i++) {
16158                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16159                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16160                                        verifierComponent.getPackageName(), idleDuration,
16161                                        verifierUser.getIdentifier(), false, "package verifier");
16162
16163                                final Intent sufficientIntent = new Intent(verification);
16164                                sufficientIntent.setComponent(verifierComponent);
16165                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16166                            }
16167                        }
16168                    }
16169
16170                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16171                            mRequiredVerifierPackage, receivers);
16172                    if (ret == PackageManager.INSTALL_SUCCEEDED
16173                            && mRequiredVerifierPackage != null) {
16174                        Trace.asyncTraceBegin(
16175                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16176                        /*
16177                         * Send the intent to the required verification agent,
16178                         * but only start the verification timeout after the
16179                         * target BroadcastReceivers have run.
16180                         */
16181                        verification.setComponent(requiredVerifierComponent);
16182                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16183                                mRequiredVerifierPackage, idleDuration,
16184                                verifierUser.getIdentifier(), false, "package verifier");
16185                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16186                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16187                                new BroadcastReceiver() {
16188                                    @Override
16189                                    public void onReceive(Context context, Intent intent) {
16190                                        final Message msg = mHandler
16191                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16192                                        msg.arg1 = verificationId;
16193                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16194                                    }
16195                                }, null, 0, null, null);
16196
16197                        /*
16198                         * We don't want the copy to proceed until verification
16199                         * succeeds, so null out this field.
16200                         */
16201                        mArgs = null;
16202                    }
16203                } else {
16204                    /*
16205                     * No package verification is enabled, so immediately start
16206                     * the remote call to initiate copy using temporary file.
16207                     */
16208                    ret = args.copyApk(mContainerService, true);
16209                }
16210            }
16211
16212            mRet = ret;
16213        }
16214
16215        @Override
16216        void handleReturnCode() {
16217            // If mArgs is null, then MCS couldn't be reached. When it
16218            // reconnects, it will try again to install. At that point, this
16219            // will succeed.
16220            if (mArgs != null) {
16221                processPendingInstall(mArgs, mRet);
16222            }
16223        }
16224
16225        @Override
16226        void handleServiceError() {
16227            mArgs = createInstallArgs(this);
16228            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16229        }
16230
16231        public boolean isForwardLocked() {
16232            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16233        }
16234    }
16235
16236    /**
16237     * Used during creation of InstallArgs
16238     *
16239     * @param installFlags package installation flags
16240     * @return true if should be installed on external storage
16241     */
16242    private static boolean installOnExternalAsec(int installFlags) {
16243        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16244            return false;
16245        }
16246        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16247            return true;
16248        }
16249        return false;
16250    }
16251
16252    /**
16253     * Used during creation of InstallArgs
16254     *
16255     * @param installFlags package installation flags
16256     * @return true if should be installed as forward locked
16257     */
16258    private static boolean installForwardLocked(int installFlags) {
16259        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16260    }
16261
16262    private InstallArgs createInstallArgs(InstallParams params) {
16263        if (params.move != null) {
16264            return new MoveInstallArgs(params);
16265        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16266            return new AsecInstallArgs(params);
16267        } else {
16268            return new FileInstallArgs(params);
16269        }
16270    }
16271
16272    /**
16273     * Create args that describe an existing installed package. Typically used
16274     * when cleaning up old installs, or used as a move source.
16275     */
16276    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16277            String resourcePath, String[] instructionSets) {
16278        final boolean isInAsec;
16279        if (installOnExternalAsec(installFlags)) {
16280            /* Apps on SD card are always in ASEC containers. */
16281            isInAsec = true;
16282        } else if (installForwardLocked(installFlags)
16283                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16284            /*
16285             * Forward-locked apps are only in ASEC containers if they're the
16286             * new style
16287             */
16288            isInAsec = true;
16289        } else {
16290            isInAsec = false;
16291        }
16292
16293        if (isInAsec) {
16294            return new AsecInstallArgs(codePath, instructionSets,
16295                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16296        } else {
16297            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16298        }
16299    }
16300
16301    static abstract class InstallArgs {
16302        /** @see InstallParams#origin */
16303        final OriginInfo origin;
16304        /** @see InstallParams#move */
16305        final MoveInfo move;
16306
16307        final IPackageInstallObserver2 observer;
16308        // Always refers to PackageManager flags only
16309        final int installFlags;
16310        final String installerPackageName;
16311        final String volumeUuid;
16312        final UserHandle user;
16313        final String abiOverride;
16314        final String[] installGrantPermissions;
16315        /** If non-null, drop an async trace when the install completes */
16316        final String traceMethod;
16317        final int traceCookie;
16318        final Certificate[][] certificates;
16319        final int installReason;
16320
16321        // The list of instruction sets supported by this app. This is currently
16322        // only used during the rmdex() phase to clean up resources. We can get rid of this
16323        // if we move dex files under the common app path.
16324        /* nullable */ String[] instructionSets;
16325
16326        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16327                int installFlags, String installerPackageName, String volumeUuid,
16328                UserHandle user, String[] instructionSets,
16329                String abiOverride, String[] installGrantPermissions,
16330                String traceMethod, int traceCookie, Certificate[][] certificates,
16331                int installReason) {
16332            this.origin = origin;
16333            this.move = move;
16334            this.installFlags = installFlags;
16335            this.observer = observer;
16336            this.installerPackageName = installerPackageName;
16337            this.volumeUuid = volumeUuid;
16338            this.user = user;
16339            this.instructionSets = instructionSets;
16340            this.abiOverride = abiOverride;
16341            this.installGrantPermissions = installGrantPermissions;
16342            this.traceMethod = traceMethod;
16343            this.traceCookie = traceCookie;
16344            this.certificates = certificates;
16345            this.installReason = installReason;
16346        }
16347
16348        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16349        abstract int doPreInstall(int status);
16350
16351        /**
16352         * Rename package into final resting place. All paths on the given
16353         * scanned package should be updated to reflect the rename.
16354         */
16355        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16356        abstract int doPostInstall(int status, int uid);
16357
16358        /** @see PackageSettingBase#codePathString */
16359        abstract String getCodePath();
16360        /** @see PackageSettingBase#resourcePathString */
16361        abstract String getResourcePath();
16362
16363        // Need installer lock especially for dex file removal.
16364        abstract void cleanUpResourcesLI();
16365        abstract boolean doPostDeleteLI(boolean delete);
16366
16367        /**
16368         * Called before the source arguments are copied. This is used mostly
16369         * for MoveParams when it needs to read the source file to put it in the
16370         * destination.
16371         */
16372        int doPreCopy() {
16373            return PackageManager.INSTALL_SUCCEEDED;
16374        }
16375
16376        /**
16377         * Called after the source arguments are copied. This is used mostly for
16378         * MoveParams when it needs to read the source file to put it in the
16379         * destination.
16380         */
16381        int doPostCopy(int uid) {
16382            return PackageManager.INSTALL_SUCCEEDED;
16383        }
16384
16385        protected boolean isFwdLocked() {
16386            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16387        }
16388
16389        protected boolean isExternalAsec() {
16390            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16391        }
16392
16393        protected boolean isEphemeral() {
16394            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16395        }
16396
16397        UserHandle getUser() {
16398            return user;
16399        }
16400    }
16401
16402    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16403        if (!allCodePaths.isEmpty()) {
16404            if (instructionSets == null) {
16405                throw new IllegalStateException("instructionSet == null");
16406            }
16407            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16408            for (String codePath : allCodePaths) {
16409                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16410                    try {
16411                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16412                    } catch (InstallerException ignored) {
16413                    }
16414                }
16415            }
16416        }
16417    }
16418
16419    /**
16420     * Logic to handle installation of non-ASEC applications, including copying
16421     * and renaming logic.
16422     */
16423    class FileInstallArgs extends InstallArgs {
16424        private File codeFile;
16425        private File resourceFile;
16426
16427        // Example topology:
16428        // /data/app/com.example/base.apk
16429        // /data/app/com.example/split_foo.apk
16430        // /data/app/com.example/lib/arm/libfoo.so
16431        // /data/app/com.example/lib/arm64/libfoo.so
16432        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16433
16434        /** New install */
16435        FileInstallArgs(InstallParams params) {
16436            super(params.origin, params.move, params.observer, params.installFlags,
16437                    params.installerPackageName, params.volumeUuid,
16438                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16439                    params.grantedRuntimePermissions,
16440                    params.traceMethod, params.traceCookie, params.certificates,
16441                    params.installReason);
16442            if (isFwdLocked()) {
16443                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16444            }
16445        }
16446
16447        /** Existing install */
16448        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16449            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16450                    null, null, null, 0, null /*certificates*/,
16451                    PackageManager.INSTALL_REASON_UNKNOWN);
16452            this.codeFile = (codePath != null) ? new File(codePath) : null;
16453            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16454        }
16455
16456        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16457            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16458            try {
16459                return doCopyApk(imcs, temp);
16460            } finally {
16461                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16462            }
16463        }
16464
16465        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16466            if (origin.staged) {
16467                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16468                codeFile = origin.file;
16469                resourceFile = origin.file;
16470                return PackageManager.INSTALL_SUCCEEDED;
16471            }
16472
16473            try {
16474                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16475                final File tempDir =
16476                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16477                codeFile = tempDir;
16478                resourceFile = tempDir;
16479            } catch (IOException e) {
16480                Slog.w(TAG, "Failed to create copy file: " + e);
16481                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16482            }
16483
16484            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16485                @Override
16486                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16487                    if (!FileUtils.isValidExtFilename(name)) {
16488                        throw new IllegalArgumentException("Invalid filename: " + name);
16489                    }
16490                    try {
16491                        final File file = new File(codeFile, name);
16492                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16493                                O_RDWR | O_CREAT, 0644);
16494                        Os.chmod(file.getAbsolutePath(), 0644);
16495                        return new ParcelFileDescriptor(fd);
16496                    } catch (ErrnoException e) {
16497                        throw new RemoteException("Failed to open: " + e.getMessage());
16498                    }
16499                }
16500            };
16501
16502            int ret = PackageManager.INSTALL_SUCCEEDED;
16503            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16504            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16505                Slog.e(TAG, "Failed to copy package");
16506                return ret;
16507            }
16508
16509            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16510            NativeLibraryHelper.Handle handle = null;
16511            try {
16512                handle = NativeLibraryHelper.Handle.create(codeFile);
16513                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16514                        abiOverride);
16515            } catch (IOException e) {
16516                Slog.e(TAG, "Copying native libraries failed", e);
16517                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16518            } finally {
16519                IoUtils.closeQuietly(handle);
16520            }
16521
16522            return ret;
16523        }
16524
16525        int doPreInstall(int status) {
16526            if (status != PackageManager.INSTALL_SUCCEEDED) {
16527                cleanUp();
16528            }
16529            return status;
16530        }
16531
16532        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16533            if (status != PackageManager.INSTALL_SUCCEEDED) {
16534                cleanUp();
16535                return false;
16536            }
16537
16538            final File targetDir = codeFile.getParentFile();
16539            final File beforeCodeFile = codeFile;
16540            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16541
16542            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16543            try {
16544                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16545            } catch (ErrnoException e) {
16546                Slog.w(TAG, "Failed to rename", e);
16547                return false;
16548            }
16549
16550            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16551                Slog.w(TAG, "Failed to restorecon");
16552                return false;
16553            }
16554
16555            // Reflect the rename internally
16556            codeFile = afterCodeFile;
16557            resourceFile = afterCodeFile;
16558
16559            // Reflect the rename in scanned details
16560            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16561            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16562                    afterCodeFile, pkg.baseCodePath));
16563            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16564                    afterCodeFile, pkg.splitCodePaths));
16565
16566            // Reflect the rename in app info
16567            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16568            pkg.setApplicationInfoCodePath(pkg.codePath);
16569            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16570            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16571            pkg.setApplicationInfoResourcePath(pkg.codePath);
16572            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16573            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16574
16575            return true;
16576        }
16577
16578        int doPostInstall(int status, int uid) {
16579            if (status != PackageManager.INSTALL_SUCCEEDED) {
16580                cleanUp();
16581            }
16582            return status;
16583        }
16584
16585        @Override
16586        String getCodePath() {
16587            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16588        }
16589
16590        @Override
16591        String getResourcePath() {
16592            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16593        }
16594
16595        private boolean cleanUp() {
16596            if (codeFile == null || !codeFile.exists()) {
16597                return false;
16598            }
16599
16600            removeCodePathLI(codeFile);
16601
16602            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16603                resourceFile.delete();
16604            }
16605
16606            return true;
16607        }
16608
16609        void cleanUpResourcesLI() {
16610            // Try enumerating all code paths before deleting
16611            List<String> allCodePaths = Collections.EMPTY_LIST;
16612            if (codeFile != null && codeFile.exists()) {
16613                try {
16614                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16615                    allCodePaths = pkg.getAllCodePaths();
16616                } catch (PackageParserException e) {
16617                    // Ignored; we tried our best
16618                }
16619            }
16620
16621            cleanUp();
16622            removeDexFiles(allCodePaths, instructionSets);
16623        }
16624
16625        boolean doPostDeleteLI(boolean delete) {
16626            // XXX err, shouldn't we respect the delete flag?
16627            cleanUpResourcesLI();
16628            return true;
16629        }
16630    }
16631
16632    private boolean isAsecExternal(String cid) {
16633        final String asecPath = PackageHelper.getSdFilesystem(cid);
16634        return !asecPath.startsWith(mAsecInternalPath);
16635    }
16636
16637    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16638            PackageManagerException {
16639        if (copyRet < 0) {
16640            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16641                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16642                throw new PackageManagerException(copyRet, message);
16643            }
16644        }
16645    }
16646
16647    /**
16648     * Extract the StorageManagerService "container ID" from the full code path of an
16649     * .apk.
16650     */
16651    static String cidFromCodePath(String fullCodePath) {
16652        int eidx = fullCodePath.lastIndexOf("/");
16653        String subStr1 = fullCodePath.substring(0, eidx);
16654        int sidx = subStr1.lastIndexOf("/");
16655        return subStr1.substring(sidx+1, eidx);
16656    }
16657
16658    /**
16659     * Logic to handle installation of ASEC applications, including copying and
16660     * renaming logic.
16661     */
16662    class AsecInstallArgs extends InstallArgs {
16663        static final String RES_FILE_NAME = "pkg.apk";
16664        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16665
16666        String cid;
16667        String packagePath;
16668        String resourcePath;
16669
16670        /** New install */
16671        AsecInstallArgs(InstallParams params) {
16672            super(params.origin, params.move, params.observer, params.installFlags,
16673                    params.installerPackageName, params.volumeUuid,
16674                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16675                    params.grantedRuntimePermissions,
16676                    params.traceMethod, params.traceCookie, params.certificates,
16677                    params.installReason);
16678        }
16679
16680        /** Existing install */
16681        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16682                        boolean isExternal, boolean isForwardLocked) {
16683            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16684                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16685                    instructionSets, null, null, null, 0, null /*certificates*/,
16686                    PackageManager.INSTALL_REASON_UNKNOWN);
16687            // Hackily pretend we're still looking at a full code path
16688            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16689                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16690            }
16691
16692            // Extract cid from fullCodePath
16693            int eidx = fullCodePath.lastIndexOf("/");
16694            String subStr1 = fullCodePath.substring(0, eidx);
16695            int sidx = subStr1.lastIndexOf("/");
16696            cid = subStr1.substring(sidx+1, eidx);
16697            setMountPath(subStr1);
16698        }
16699
16700        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16701            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16702                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16703                    instructionSets, null, null, null, 0, null /*certificates*/,
16704                    PackageManager.INSTALL_REASON_UNKNOWN);
16705            this.cid = cid;
16706            setMountPath(PackageHelper.getSdDir(cid));
16707        }
16708
16709        void createCopyFile() {
16710            cid = mInstallerService.allocateExternalStageCidLegacy();
16711        }
16712
16713        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16714            if (origin.staged && origin.cid != null) {
16715                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16716                cid = origin.cid;
16717                setMountPath(PackageHelper.getSdDir(cid));
16718                return PackageManager.INSTALL_SUCCEEDED;
16719            }
16720
16721            if (temp) {
16722                createCopyFile();
16723            } else {
16724                /*
16725                 * Pre-emptively destroy the container since it's destroyed if
16726                 * copying fails due to it existing anyway.
16727                 */
16728                PackageHelper.destroySdDir(cid);
16729            }
16730
16731            final String newMountPath = imcs.copyPackageToContainer(
16732                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16733                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16734
16735            if (newMountPath != null) {
16736                setMountPath(newMountPath);
16737                return PackageManager.INSTALL_SUCCEEDED;
16738            } else {
16739                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16740            }
16741        }
16742
16743        @Override
16744        String getCodePath() {
16745            return packagePath;
16746        }
16747
16748        @Override
16749        String getResourcePath() {
16750            return resourcePath;
16751        }
16752
16753        int doPreInstall(int status) {
16754            if (status != PackageManager.INSTALL_SUCCEEDED) {
16755                // Destroy container
16756                PackageHelper.destroySdDir(cid);
16757            } else {
16758                boolean mounted = PackageHelper.isContainerMounted(cid);
16759                if (!mounted) {
16760                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16761                            Process.SYSTEM_UID);
16762                    if (newMountPath != null) {
16763                        setMountPath(newMountPath);
16764                    } else {
16765                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16766                    }
16767                }
16768            }
16769            return status;
16770        }
16771
16772        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16773            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16774            String newMountPath = null;
16775            if (PackageHelper.isContainerMounted(cid)) {
16776                // Unmount the container
16777                if (!PackageHelper.unMountSdDir(cid)) {
16778                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16779                    return false;
16780                }
16781            }
16782            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16783                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16784                        " which might be stale. Will try to clean up.");
16785                // Clean up the stale container and proceed to recreate.
16786                if (!PackageHelper.destroySdDir(newCacheId)) {
16787                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16788                    return false;
16789                }
16790                // Successfully cleaned up stale container. Try to rename again.
16791                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16792                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16793                            + " inspite of cleaning it up.");
16794                    return false;
16795                }
16796            }
16797            if (!PackageHelper.isContainerMounted(newCacheId)) {
16798                Slog.w(TAG, "Mounting container " + newCacheId);
16799                newMountPath = PackageHelper.mountSdDir(newCacheId,
16800                        getEncryptKey(), Process.SYSTEM_UID);
16801            } else {
16802                newMountPath = PackageHelper.getSdDir(newCacheId);
16803            }
16804            if (newMountPath == null) {
16805                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16806                return false;
16807            }
16808            Log.i(TAG, "Succesfully renamed " + cid +
16809                    " to " + newCacheId +
16810                    " at new path: " + newMountPath);
16811            cid = newCacheId;
16812
16813            final File beforeCodeFile = new File(packagePath);
16814            setMountPath(newMountPath);
16815            final File afterCodeFile = new File(packagePath);
16816
16817            // Reflect the rename in scanned details
16818            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16819            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16820                    afterCodeFile, pkg.baseCodePath));
16821            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16822                    afterCodeFile, pkg.splitCodePaths));
16823
16824            // Reflect the rename in app info
16825            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16826            pkg.setApplicationInfoCodePath(pkg.codePath);
16827            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16828            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16829            pkg.setApplicationInfoResourcePath(pkg.codePath);
16830            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16831            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16832
16833            return true;
16834        }
16835
16836        private void setMountPath(String mountPath) {
16837            final File mountFile = new File(mountPath);
16838
16839            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16840            if (monolithicFile.exists()) {
16841                packagePath = monolithicFile.getAbsolutePath();
16842                if (isFwdLocked()) {
16843                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16844                } else {
16845                    resourcePath = packagePath;
16846                }
16847            } else {
16848                packagePath = mountFile.getAbsolutePath();
16849                resourcePath = packagePath;
16850            }
16851        }
16852
16853        int doPostInstall(int status, int uid) {
16854            if (status != PackageManager.INSTALL_SUCCEEDED) {
16855                cleanUp();
16856            } else {
16857                final int groupOwner;
16858                final String protectedFile;
16859                if (isFwdLocked()) {
16860                    groupOwner = UserHandle.getSharedAppGid(uid);
16861                    protectedFile = RES_FILE_NAME;
16862                } else {
16863                    groupOwner = -1;
16864                    protectedFile = null;
16865                }
16866
16867                if (uid < Process.FIRST_APPLICATION_UID
16868                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16869                    Slog.e(TAG, "Failed to finalize " + cid);
16870                    PackageHelper.destroySdDir(cid);
16871                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16872                }
16873
16874                boolean mounted = PackageHelper.isContainerMounted(cid);
16875                if (!mounted) {
16876                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16877                }
16878            }
16879            return status;
16880        }
16881
16882        private void cleanUp() {
16883            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16884
16885            // Destroy secure container
16886            PackageHelper.destroySdDir(cid);
16887        }
16888
16889        private List<String> getAllCodePaths() {
16890            final File codeFile = new File(getCodePath());
16891            if (codeFile != null && codeFile.exists()) {
16892                try {
16893                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16894                    return pkg.getAllCodePaths();
16895                } catch (PackageParserException e) {
16896                    // Ignored; we tried our best
16897                }
16898            }
16899            return Collections.EMPTY_LIST;
16900        }
16901
16902        void cleanUpResourcesLI() {
16903            // Enumerate all code paths before deleting
16904            cleanUpResourcesLI(getAllCodePaths());
16905        }
16906
16907        private void cleanUpResourcesLI(List<String> allCodePaths) {
16908            cleanUp();
16909            removeDexFiles(allCodePaths, instructionSets);
16910        }
16911
16912        String getPackageName() {
16913            return getAsecPackageName(cid);
16914        }
16915
16916        boolean doPostDeleteLI(boolean delete) {
16917            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16918            final List<String> allCodePaths = getAllCodePaths();
16919            boolean mounted = PackageHelper.isContainerMounted(cid);
16920            if (mounted) {
16921                // Unmount first
16922                if (PackageHelper.unMountSdDir(cid)) {
16923                    mounted = false;
16924                }
16925            }
16926            if (!mounted && delete) {
16927                cleanUpResourcesLI(allCodePaths);
16928            }
16929            return !mounted;
16930        }
16931
16932        @Override
16933        int doPreCopy() {
16934            if (isFwdLocked()) {
16935                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16936                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16937                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16938                }
16939            }
16940
16941            return PackageManager.INSTALL_SUCCEEDED;
16942        }
16943
16944        @Override
16945        int doPostCopy(int uid) {
16946            if (isFwdLocked()) {
16947                if (uid < Process.FIRST_APPLICATION_UID
16948                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16949                                RES_FILE_NAME)) {
16950                    Slog.e(TAG, "Failed to finalize " + cid);
16951                    PackageHelper.destroySdDir(cid);
16952                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16953                }
16954            }
16955
16956            return PackageManager.INSTALL_SUCCEEDED;
16957        }
16958    }
16959
16960    /**
16961     * Logic to handle movement of existing installed applications.
16962     */
16963    class MoveInstallArgs extends InstallArgs {
16964        private File codeFile;
16965        private File resourceFile;
16966
16967        /** New install */
16968        MoveInstallArgs(InstallParams params) {
16969            super(params.origin, params.move, params.observer, params.installFlags,
16970                    params.installerPackageName, params.volumeUuid,
16971                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16972                    params.grantedRuntimePermissions,
16973                    params.traceMethod, params.traceCookie, params.certificates,
16974                    params.installReason);
16975        }
16976
16977        int copyApk(IMediaContainerService imcs, boolean temp) {
16978            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16979                    + move.fromUuid + " to " + move.toUuid);
16980            synchronized (mInstaller) {
16981                try {
16982                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16983                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16984                } catch (InstallerException e) {
16985                    Slog.w(TAG, "Failed to move app", e);
16986                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16987                }
16988            }
16989
16990            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16991            resourceFile = codeFile;
16992            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16993
16994            return PackageManager.INSTALL_SUCCEEDED;
16995        }
16996
16997        int doPreInstall(int status) {
16998            if (status != PackageManager.INSTALL_SUCCEEDED) {
16999                cleanUp(move.toUuid);
17000            }
17001            return status;
17002        }
17003
17004        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17005            if (status != PackageManager.INSTALL_SUCCEEDED) {
17006                cleanUp(move.toUuid);
17007                return false;
17008            }
17009
17010            // Reflect the move in app info
17011            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17012            pkg.setApplicationInfoCodePath(pkg.codePath);
17013            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17014            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17015            pkg.setApplicationInfoResourcePath(pkg.codePath);
17016            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17017            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17018
17019            return true;
17020        }
17021
17022        int doPostInstall(int status, int uid) {
17023            if (status == PackageManager.INSTALL_SUCCEEDED) {
17024                cleanUp(move.fromUuid);
17025            } else {
17026                cleanUp(move.toUuid);
17027            }
17028            return status;
17029        }
17030
17031        @Override
17032        String getCodePath() {
17033            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17034        }
17035
17036        @Override
17037        String getResourcePath() {
17038            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17039        }
17040
17041        private boolean cleanUp(String volumeUuid) {
17042            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17043                    move.dataAppName);
17044            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17045            final int[] userIds = sUserManager.getUserIds();
17046            synchronized (mInstallLock) {
17047                // Clean up both app data and code
17048                // All package moves are frozen until finished
17049                for (int userId : userIds) {
17050                    try {
17051                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17052                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17053                    } catch (InstallerException e) {
17054                        Slog.w(TAG, String.valueOf(e));
17055                    }
17056                }
17057                removeCodePathLI(codeFile);
17058            }
17059            return true;
17060        }
17061
17062        void cleanUpResourcesLI() {
17063            throw new UnsupportedOperationException();
17064        }
17065
17066        boolean doPostDeleteLI(boolean delete) {
17067            throw new UnsupportedOperationException();
17068        }
17069    }
17070
17071    static String getAsecPackageName(String packageCid) {
17072        int idx = packageCid.lastIndexOf("-");
17073        if (idx == -1) {
17074            return packageCid;
17075        }
17076        return packageCid.substring(0, idx);
17077    }
17078
17079    // Utility method used to create code paths based on package name and available index.
17080    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17081        String idxStr = "";
17082        int idx = 1;
17083        // Fall back to default value of idx=1 if prefix is not
17084        // part of oldCodePath
17085        if (oldCodePath != null) {
17086            String subStr = oldCodePath;
17087            // Drop the suffix right away
17088            if (suffix != null && subStr.endsWith(suffix)) {
17089                subStr = subStr.substring(0, subStr.length() - suffix.length());
17090            }
17091            // If oldCodePath already contains prefix find out the
17092            // ending index to either increment or decrement.
17093            int sidx = subStr.lastIndexOf(prefix);
17094            if (sidx != -1) {
17095                subStr = subStr.substring(sidx + prefix.length());
17096                if (subStr != null) {
17097                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17098                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17099                    }
17100                    try {
17101                        idx = Integer.parseInt(subStr);
17102                        if (idx <= 1) {
17103                            idx++;
17104                        } else {
17105                            idx--;
17106                        }
17107                    } catch(NumberFormatException e) {
17108                    }
17109                }
17110            }
17111        }
17112        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17113        return prefix + idxStr;
17114    }
17115
17116    private File getNextCodePath(File targetDir, String packageName) {
17117        File result;
17118        SecureRandom random = new SecureRandom();
17119        byte[] bytes = new byte[16];
17120        do {
17121            random.nextBytes(bytes);
17122            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17123            result = new File(targetDir, packageName + "-" + suffix);
17124        } while (result.exists());
17125        return result;
17126    }
17127
17128    // Utility method that returns the relative package path with respect
17129    // to the installation directory. Like say for /data/data/com.test-1.apk
17130    // string com.test-1 is returned.
17131    static String deriveCodePathName(String codePath) {
17132        if (codePath == null) {
17133            return null;
17134        }
17135        final File codeFile = new File(codePath);
17136        final String name = codeFile.getName();
17137        if (codeFile.isDirectory()) {
17138            return name;
17139        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17140            final int lastDot = name.lastIndexOf('.');
17141            return name.substring(0, lastDot);
17142        } else {
17143            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17144            return null;
17145        }
17146    }
17147
17148    static class PackageInstalledInfo {
17149        String name;
17150        int uid;
17151        // The set of users that originally had this package installed.
17152        int[] origUsers;
17153        // The set of users that now have this package installed.
17154        int[] newUsers;
17155        PackageParser.Package pkg;
17156        int returnCode;
17157        String returnMsg;
17158        PackageRemovedInfo removedInfo;
17159        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17160
17161        public void setError(int code, String msg) {
17162            setReturnCode(code);
17163            setReturnMessage(msg);
17164            Slog.w(TAG, msg);
17165        }
17166
17167        public void setError(String msg, PackageParserException e) {
17168            setReturnCode(e.error);
17169            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17170            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17171            for (int i = 0; i < childCount; i++) {
17172                addedChildPackages.valueAt(i).setError(msg, e);
17173            }
17174            Slog.w(TAG, msg, e);
17175        }
17176
17177        public void setError(String msg, PackageManagerException e) {
17178            returnCode = e.error;
17179            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17180            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17181            for (int i = 0; i < childCount; i++) {
17182                addedChildPackages.valueAt(i).setError(msg, e);
17183            }
17184            Slog.w(TAG, msg, e);
17185        }
17186
17187        public void setReturnCode(int returnCode) {
17188            this.returnCode = returnCode;
17189            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17190            for (int i = 0; i < childCount; i++) {
17191                addedChildPackages.valueAt(i).returnCode = returnCode;
17192            }
17193        }
17194
17195        private void setReturnMessage(String returnMsg) {
17196            this.returnMsg = returnMsg;
17197            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17198            for (int i = 0; i < childCount; i++) {
17199                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17200            }
17201        }
17202
17203        // In some error cases we want to convey more info back to the observer
17204        String origPackage;
17205        String origPermission;
17206    }
17207
17208    /*
17209     * Install a non-existing package.
17210     */
17211    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17212            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17213            PackageInstalledInfo res, int installReason) {
17214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17215
17216        // Remember this for later, in case we need to rollback this install
17217        String pkgName = pkg.packageName;
17218
17219        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17220
17221        synchronized(mPackages) {
17222            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17223            if (renamedPackage != null) {
17224                // A package with the same name is already installed, though
17225                // it has been renamed to an older name.  The package we
17226                // are trying to install should be installed as an update to
17227                // the existing one, but that has not been requested, so bail.
17228                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17229                        + " without first uninstalling package running as "
17230                        + renamedPackage);
17231                return;
17232            }
17233            if (mPackages.containsKey(pkgName)) {
17234                // Don't allow installation over an existing package with the same name.
17235                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17236                        + " without first uninstalling.");
17237                return;
17238            }
17239        }
17240
17241        try {
17242            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17243                    System.currentTimeMillis(), user);
17244
17245            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17246
17247            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17248                prepareAppDataAfterInstallLIF(newPackage);
17249
17250            } else {
17251                // Remove package from internal structures, but keep around any
17252                // data that might have already existed
17253                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17254                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17255            }
17256        } catch (PackageManagerException e) {
17257            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17258        }
17259
17260        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17261    }
17262
17263    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17264        // Can't rotate keys during boot or if sharedUser.
17265        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17266                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17267            return false;
17268        }
17269        // app is using upgradeKeySets; make sure all are valid
17270        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17271        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17272        for (int i = 0; i < upgradeKeySets.length; i++) {
17273            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17274                Slog.wtf(TAG, "Package "
17275                         + (oldPs.name != null ? oldPs.name : "<null>")
17276                         + " contains upgrade-key-set reference to unknown key-set: "
17277                         + upgradeKeySets[i]
17278                         + " reverting to signatures check.");
17279                return false;
17280            }
17281        }
17282        return true;
17283    }
17284
17285    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17286        // Upgrade keysets are being used.  Determine if new package has a superset of the
17287        // required keys.
17288        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17289        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17290        for (int i = 0; i < upgradeKeySets.length; i++) {
17291            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17292            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17293                return true;
17294            }
17295        }
17296        return false;
17297    }
17298
17299    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17300        try (DigestInputStream digestStream =
17301                new DigestInputStream(new FileInputStream(file), digest)) {
17302            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17303        }
17304    }
17305
17306    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17307            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17308            int installReason) {
17309        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17310
17311        final PackageParser.Package oldPackage;
17312        final PackageSetting ps;
17313        final String pkgName = pkg.packageName;
17314        final int[] allUsers;
17315        final int[] installedUsers;
17316
17317        synchronized(mPackages) {
17318            oldPackage = mPackages.get(pkgName);
17319            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17320
17321            // don't allow upgrade to target a release SDK from a pre-release SDK
17322            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17323                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17324            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17325                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17326            if (oldTargetsPreRelease
17327                    && !newTargetsPreRelease
17328                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17329                Slog.w(TAG, "Can't install package targeting released sdk");
17330                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17331                return;
17332            }
17333
17334            ps = mSettings.mPackages.get(pkgName);
17335
17336            // verify signatures are valid
17337            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17338                if (!checkUpgradeKeySetLP(ps, pkg)) {
17339                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17340                            "New package not signed by keys specified by upgrade-keysets: "
17341                                    + pkgName);
17342                    return;
17343                }
17344            } else {
17345                // default to original signature matching
17346                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17347                        != PackageManager.SIGNATURE_MATCH) {
17348                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17349                            "New package has a different signature: " + pkgName);
17350                    return;
17351                }
17352            }
17353
17354            // don't allow a system upgrade unless the upgrade hash matches
17355            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17356                byte[] digestBytes = null;
17357                try {
17358                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17359                    updateDigest(digest, new File(pkg.baseCodePath));
17360                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17361                        for (String path : pkg.splitCodePaths) {
17362                            updateDigest(digest, new File(path));
17363                        }
17364                    }
17365                    digestBytes = digest.digest();
17366                } catch (NoSuchAlgorithmException | IOException e) {
17367                    res.setError(INSTALL_FAILED_INVALID_APK,
17368                            "Could not compute hash: " + pkgName);
17369                    return;
17370                }
17371                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17372                    res.setError(INSTALL_FAILED_INVALID_APK,
17373                            "New package fails restrict-update check: " + pkgName);
17374                    return;
17375                }
17376                // retain upgrade restriction
17377                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17378            }
17379
17380            // Check for shared user id changes
17381            String invalidPackageName =
17382                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17383            if (invalidPackageName != null) {
17384                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17385                        "Package " + invalidPackageName + " tried to change user "
17386                                + oldPackage.mSharedUserId);
17387                return;
17388            }
17389
17390            // In case of rollback, remember per-user/profile install state
17391            allUsers = sUserManager.getUserIds();
17392            installedUsers = ps.queryInstalledUsers(allUsers, true);
17393
17394            // don't allow an upgrade from full to ephemeral
17395            if (isInstantApp) {
17396                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17397                    for (int currentUser : allUsers) {
17398                        if (!ps.getInstantApp(currentUser)) {
17399                            // can't downgrade from full to instant
17400                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17401                                    + " for user: " + currentUser);
17402                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17403                            return;
17404                        }
17405                    }
17406                } else if (!ps.getInstantApp(user.getIdentifier())) {
17407                    // can't downgrade from full to instant
17408                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17409                            + " for user: " + user.getIdentifier());
17410                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17411                    return;
17412                }
17413            }
17414        }
17415
17416        // Update what is removed
17417        res.removedInfo = new PackageRemovedInfo(this);
17418        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17419        res.removedInfo.removedPackage = oldPackage.packageName;
17420        res.removedInfo.installerPackageName = ps.installerPackageName;
17421        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17422        res.removedInfo.isUpdate = true;
17423        res.removedInfo.origUsers = installedUsers;
17424        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17425        for (int i = 0; i < installedUsers.length; i++) {
17426            final int userId = installedUsers[i];
17427            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17428        }
17429
17430        final int childCount = (oldPackage.childPackages != null)
17431                ? oldPackage.childPackages.size() : 0;
17432        for (int i = 0; i < childCount; i++) {
17433            boolean childPackageUpdated = false;
17434            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17435            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17436            if (res.addedChildPackages != null) {
17437                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17438                if (childRes != null) {
17439                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17440                    childRes.removedInfo.removedPackage = childPkg.packageName;
17441                    if (childPs != null) {
17442                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17443                    }
17444                    childRes.removedInfo.isUpdate = true;
17445                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17446                    childPackageUpdated = true;
17447                }
17448            }
17449            if (!childPackageUpdated) {
17450                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17451                childRemovedRes.removedPackage = childPkg.packageName;
17452                if (childPs != null) {
17453                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17454                }
17455                childRemovedRes.isUpdate = false;
17456                childRemovedRes.dataRemoved = true;
17457                synchronized (mPackages) {
17458                    if (childPs != null) {
17459                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17460                    }
17461                }
17462                if (res.removedInfo.removedChildPackages == null) {
17463                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17464                }
17465                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17466            }
17467        }
17468
17469        boolean sysPkg = (isSystemApp(oldPackage));
17470        if (sysPkg) {
17471            // Set the system/privileged flags as needed
17472            final boolean privileged =
17473                    (oldPackage.applicationInfo.privateFlags
17474                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17475            final int systemPolicyFlags = policyFlags
17476                    | PackageParser.PARSE_IS_SYSTEM
17477                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17478
17479            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17480                    user, allUsers, installerPackageName, res, installReason);
17481        } else {
17482            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17483                    user, allUsers, installerPackageName, res, installReason);
17484        }
17485    }
17486
17487    @Override
17488    public List<String> getPreviousCodePaths(String packageName) {
17489        final int callingUid = Binder.getCallingUid();
17490        final List<String> result = new ArrayList<>();
17491        if (getInstantAppPackageName(callingUid) != null) {
17492            return result;
17493        }
17494        final PackageSetting ps = mSettings.mPackages.get(packageName);
17495        if (ps != null
17496                && ps.oldCodePaths != null
17497                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17498            result.addAll(ps.oldCodePaths);
17499        }
17500        return result;
17501    }
17502
17503    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17504            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17505            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17506            int installReason) {
17507        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17508                + deletedPackage);
17509
17510        String pkgName = deletedPackage.packageName;
17511        boolean deletedPkg = true;
17512        boolean addedPkg = false;
17513        boolean updatedSettings = false;
17514        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17515        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17516                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17517
17518        final long origUpdateTime = (pkg.mExtras != null)
17519                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17520
17521        // First delete the existing package while retaining the data directory
17522        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17523                res.removedInfo, true, pkg)) {
17524            // If the existing package wasn't successfully deleted
17525            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17526            deletedPkg = false;
17527        } else {
17528            // Successfully deleted the old package; proceed with replace.
17529
17530            // If deleted package lived in a container, give users a chance to
17531            // relinquish resources before killing.
17532            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17533                if (DEBUG_INSTALL) {
17534                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17535                }
17536                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17537                final ArrayList<String> pkgList = new ArrayList<String>(1);
17538                pkgList.add(deletedPackage.applicationInfo.packageName);
17539                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17540            }
17541
17542            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17543                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17544            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17545
17546            try {
17547                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17548                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17549                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17550                        installReason);
17551
17552                // Update the in-memory copy of the previous code paths.
17553                PackageSetting ps = mSettings.mPackages.get(pkgName);
17554                if (!killApp) {
17555                    if (ps.oldCodePaths == null) {
17556                        ps.oldCodePaths = new ArraySet<>();
17557                    }
17558                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17559                    if (deletedPackage.splitCodePaths != null) {
17560                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17561                    }
17562                } else {
17563                    ps.oldCodePaths = null;
17564                }
17565                if (ps.childPackageNames != null) {
17566                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17567                        final String childPkgName = ps.childPackageNames.get(i);
17568                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17569                        childPs.oldCodePaths = ps.oldCodePaths;
17570                    }
17571                }
17572                // set instant app status, but, only if it's explicitly specified
17573                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17574                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17575                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17576                prepareAppDataAfterInstallLIF(newPackage);
17577                addedPkg = true;
17578                mDexManager.notifyPackageUpdated(newPackage.packageName,
17579                        newPackage.baseCodePath, newPackage.splitCodePaths);
17580            } catch (PackageManagerException e) {
17581                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17582            }
17583        }
17584
17585        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17586            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17587
17588            // Revert all internal state mutations and added folders for the failed install
17589            if (addedPkg) {
17590                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17591                        res.removedInfo, true, null);
17592            }
17593
17594            // Restore the old package
17595            if (deletedPkg) {
17596                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17597                File restoreFile = new File(deletedPackage.codePath);
17598                // Parse old package
17599                boolean oldExternal = isExternal(deletedPackage);
17600                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17601                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17602                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17603                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17604                try {
17605                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17606                            null);
17607                } catch (PackageManagerException e) {
17608                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17609                            + e.getMessage());
17610                    return;
17611                }
17612
17613                synchronized (mPackages) {
17614                    // Ensure the installer package name up to date
17615                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17616
17617                    // Update permissions for restored package
17618                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17619
17620                    mSettings.writeLPr();
17621                }
17622
17623                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17624            }
17625        } else {
17626            synchronized (mPackages) {
17627                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17628                if (ps != null) {
17629                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17630                    if (res.removedInfo.removedChildPackages != null) {
17631                        final int childCount = res.removedInfo.removedChildPackages.size();
17632                        // Iterate in reverse as we may modify the collection
17633                        for (int i = childCount - 1; i >= 0; i--) {
17634                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17635                            if (res.addedChildPackages.containsKey(childPackageName)) {
17636                                res.removedInfo.removedChildPackages.removeAt(i);
17637                            } else {
17638                                PackageRemovedInfo childInfo = res.removedInfo
17639                                        .removedChildPackages.valueAt(i);
17640                                childInfo.removedForAllUsers = mPackages.get(
17641                                        childInfo.removedPackage) == null;
17642                            }
17643                        }
17644                    }
17645                }
17646            }
17647        }
17648    }
17649
17650    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17651            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17652            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17653            int installReason) {
17654        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17655                + ", old=" + deletedPackage);
17656
17657        final boolean disabledSystem;
17658
17659        // Remove existing system package
17660        removePackageLI(deletedPackage, true);
17661
17662        synchronized (mPackages) {
17663            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17664        }
17665        if (!disabledSystem) {
17666            // We didn't need to disable the .apk as a current system package,
17667            // which means we are replacing another update that is already
17668            // installed.  We need to make sure to delete the older one's .apk.
17669            res.removedInfo.args = createInstallArgsForExisting(0,
17670                    deletedPackage.applicationInfo.getCodePath(),
17671                    deletedPackage.applicationInfo.getResourcePath(),
17672                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17673        } else {
17674            res.removedInfo.args = null;
17675        }
17676
17677        // Successfully disabled the old package. Now proceed with re-installation
17678        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17679                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17680        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17681
17682        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17683        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17684                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17685
17686        PackageParser.Package newPackage = null;
17687        try {
17688            // Add the package to the internal data structures
17689            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17690
17691            // Set the update and install times
17692            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17693            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17694                    System.currentTimeMillis());
17695
17696            // Update the package dynamic state if succeeded
17697            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17698                // Now that the install succeeded make sure we remove data
17699                // directories for any child package the update removed.
17700                final int deletedChildCount = (deletedPackage.childPackages != null)
17701                        ? deletedPackage.childPackages.size() : 0;
17702                final int newChildCount = (newPackage.childPackages != null)
17703                        ? newPackage.childPackages.size() : 0;
17704                for (int i = 0; i < deletedChildCount; i++) {
17705                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17706                    boolean childPackageDeleted = true;
17707                    for (int j = 0; j < newChildCount; j++) {
17708                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17709                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17710                            childPackageDeleted = false;
17711                            break;
17712                        }
17713                    }
17714                    if (childPackageDeleted) {
17715                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17716                                deletedChildPkg.packageName);
17717                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17718                            PackageRemovedInfo removedChildRes = res.removedInfo
17719                                    .removedChildPackages.get(deletedChildPkg.packageName);
17720                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17721                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17722                        }
17723                    }
17724                }
17725
17726                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17727                        installReason);
17728                prepareAppDataAfterInstallLIF(newPackage);
17729
17730                mDexManager.notifyPackageUpdated(newPackage.packageName,
17731                            newPackage.baseCodePath, newPackage.splitCodePaths);
17732            }
17733        } catch (PackageManagerException e) {
17734            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17735            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17736        }
17737
17738        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17739            // Re installation failed. Restore old information
17740            // Remove new pkg information
17741            if (newPackage != null) {
17742                removeInstalledPackageLI(newPackage, true);
17743            }
17744            // Add back the old system package
17745            try {
17746                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17747            } catch (PackageManagerException e) {
17748                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17749            }
17750
17751            synchronized (mPackages) {
17752                if (disabledSystem) {
17753                    enableSystemPackageLPw(deletedPackage);
17754                }
17755
17756                // Ensure the installer package name up to date
17757                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17758
17759                // Update permissions for restored package
17760                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17761
17762                mSettings.writeLPr();
17763            }
17764
17765            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17766                    + " after failed upgrade");
17767        }
17768    }
17769
17770    /**
17771     * Checks whether the parent or any of the child packages have a change shared
17772     * user. For a package to be a valid update the shred users of the parent and
17773     * the children should match. We may later support changing child shared users.
17774     * @param oldPkg The updated package.
17775     * @param newPkg The update package.
17776     * @return The shared user that change between the versions.
17777     */
17778    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17779            PackageParser.Package newPkg) {
17780        // Check parent shared user
17781        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17782            return newPkg.packageName;
17783        }
17784        // Check child shared users
17785        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17786        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17787        for (int i = 0; i < newChildCount; i++) {
17788            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17789            // If this child was present, did it have the same shared user?
17790            for (int j = 0; j < oldChildCount; j++) {
17791                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17792                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17793                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17794                    return newChildPkg.packageName;
17795                }
17796            }
17797        }
17798        return null;
17799    }
17800
17801    private void removeNativeBinariesLI(PackageSetting ps) {
17802        // Remove the lib path for the parent package
17803        if (ps != null) {
17804            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17805            // Remove the lib path for the child packages
17806            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17807            for (int i = 0; i < childCount; i++) {
17808                PackageSetting childPs = null;
17809                synchronized (mPackages) {
17810                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17811                }
17812                if (childPs != null) {
17813                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17814                            .legacyNativeLibraryPathString);
17815                }
17816            }
17817        }
17818    }
17819
17820    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17821        // Enable the parent package
17822        mSettings.enableSystemPackageLPw(pkg.packageName);
17823        // Enable the child packages
17824        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17825        for (int i = 0; i < childCount; i++) {
17826            PackageParser.Package childPkg = pkg.childPackages.get(i);
17827            mSettings.enableSystemPackageLPw(childPkg.packageName);
17828        }
17829    }
17830
17831    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17832            PackageParser.Package newPkg) {
17833        // Disable the parent package (parent always replaced)
17834        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17835        // Disable the child packages
17836        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17837        for (int i = 0; i < childCount; i++) {
17838            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17839            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17840            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17841        }
17842        return disabled;
17843    }
17844
17845    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17846            String installerPackageName) {
17847        // Enable the parent package
17848        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17849        // Enable the child packages
17850        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17851        for (int i = 0; i < childCount; i++) {
17852            PackageParser.Package childPkg = pkg.childPackages.get(i);
17853            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17854        }
17855    }
17856
17857    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17858        // Collect all used permissions in the UID
17859        ArraySet<String> usedPermissions = new ArraySet<>();
17860        final int packageCount = su.packages.size();
17861        for (int i = 0; i < packageCount; i++) {
17862            PackageSetting ps = su.packages.valueAt(i);
17863            if (ps.pkg == null) {
17864                continue;
17865            }
17866            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17867            for (int j = 0; j < requestedPermCount; j++) {
17868                String permission = ps.pkg.requestedPermissions.get(j);
17869                BasePermission bp = mSettings.mPermissions.get(permission);
17870                if (bp != null) {
17871                    usedPermissions.add(permission);
17872                }
17873            }
17874        }
17875
17876        PermissionsState permissionsState = su.getPermissionsState();
17877        // Prune install permissions
17878        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17879        final int installPermCount = installPermStates.size();
17880        for (int i = installPermCount - 1; i >= 0;  i--) {
17881            PermissionState permissionState = installPermStates.get(i);
17882            if (!usedPermissions.contains(permissionState.getName())) {
17883                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17884                if (bp != null) {
17885                    permissionsState.revokeInstallPermission(bp);
17886                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17887                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17888                }
17889            }
17890        }
17891
17892        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17893
17894        // Prune runtime permissions
17895        for (int userId : allUserIds) {
17896            List<PermissionState> runtimePermStates = permissionsState
17897                    .getRuntimePermissionStates(userId);
17898            final int runtimePermCount = runtimePermStates.size();
17899            for (int i = runtimePermCount - 1; i >= 0; i--) {
17900                PermissionState permissionState = runtimePermStates.get(i);
17901                if (!usedPermissions.contains(permissionState.getName())) {
17902                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17903                    if (bp != null) {
17904                        permissionsState.revokeRuntimePermission(bp, userId);
17905                        permissionsState.updatePermissionFlags(bp, userId,
17906                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17907                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17908                                runtimePermissionChangedUserIds, userId);
17909                    }
17910                }
17911            }
17912        }
17913
17914        return runtimePermissionChangedUserIds;
17915    }
17916
17917    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17918            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17919        // Update the parent package setting
17920        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17921                res, user, installReason);
17922        // Update the child packages setting
17923        final int childCount = (newPackage.childPackages != null)
17924                ? newPackage.childPackages.size() : 0;
17925        for (int i = 0; i < childCount; i++) {
17926            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17927            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17928            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17929                    childRes.origUsers, childRes, user, installReason);
17930        }
17931    }
17932
17933    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17934            String installerPackageName, int[] allUsers, int[] installedForUsers,
17935            PackageInstalledInfo res, UserHandle user, int installReason) {
17936        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17937
17938        String pkgName = newPackage.packageName;
17939        synchronized (mPackages) {
17940            //write settings. the installStatus will be incomplete at this stage.
17941            //note that the new package setting would have already been
17942            //added to mPackages. It hasn't been persisted yet.
17943            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17944            // TODO: Remove this write? It's also written at the end of this method
17945            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17946            mSettings.writeLPr();
17947            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17948        }
17949
17950        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17951        synchronized (mPackages) {
17952            updatePermissionsLPw(newPackage.packageName, newPackage,
17953                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17954                            ? UPDATE_PERMISSIONS_ALL : 0));
17955            // For system-bundled packages, we assume that installing an upgraded version
17956            // of the package implies that the user actually wants to run that new code,
17957            // so we enable the package.
17958            PackageSetting ps = mSettings.mPackages.get(pkgName);
17959            final int userId = user.getIdentifier();
17960            if (ps != null) {
17961                if (isSystemApp(newPackage)) {
17962                    if (DEBUG_INSTALL) {
17963                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17964                    }
17965                    // Enable system package for requested users
17966                    if (res.origUsers != null) {
17967                        for (int origUserId : res.origUsers) {
17968                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17969                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17970                                        origUserId, installerPackageName);
17971                            }
17972                        }
17973                    }
17974                    // Also convey the prior install/uninstall state
17975                    if (allUsers != null && installedForUsers != null) {
17976                        for (int currentUserId : allUsers) {
17977                            final boolean installed = ArrayUtils.contains(
17978                                    installedForUsers, currentUserId);
17979                            if (DEBUG_INSTALL) {
17980                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17981                            }
17982                            ps.setInstalled(installed, currentUserId);
17983                        }
17984                        // these install state changes will be persisted in the
17985                        // upcoming call to mSettings.writeLPr().
17986                    }
17987                }
17988                // It's implied that when a user requests installation, they want the app to be
17989                // installed and enabled.
17990                if (userId != UserHandle.USER_ALL) {
17991                    ps.setInstalled(true, userId);
17992                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17993                }
17994
17995                // When replacing an existing package, preserve the original install reason for all
17996                // users that had the package installed before.
17997                final Set<Integer> previousUserIds = new ArraySet<>();
17998                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17999                    final int installReasonCount = res.removedInfo.installReasons.size();
18000                    for (int i = 0; i < installReasonCount; i++) {
18001                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18002                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18003                        ps.setInstallReason(previousInstallReason, previousUserId);
18004                        previousUserIds.add(previousUserId);
18005                    }
18006                }
18007
18008                // Set install reason for users that are having the package newly installed.
18009                if (userId == UserHandle.USER_ALL) {
18010                    for (int currentUserId : sUserManager.getUserIds()) {
18011                        if (!previousUserIds.contains(currentUserId)) {
18012                            ps.setInstallReason(installReason, currentUserId);
18013                        }
18014                    }
18015                } else if (!previousUserIds.contains(userId)) {
18016                    ps.setInstallReason(installReason, userId);
18017                }
18018                mSettings.writeKernelMappingLPr(ps);
18019            }
18020            res.name = pkgName;
18021            res.uid = newPackage.applicationInfo.uid;
18022            res.pkg = newPackage;
18023            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18024            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18025            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18026            //to update install status
18027            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18028            mSettings.writeLPr();
18029            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18030        }
18031
18032        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18033    }
18034
18035    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18036        try {
18037            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18038            installPackageLI(args, res);
18039        } finally {
18040            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18041        }
18042    }
18043
18044    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18045        final int installFlags = args.installFlags;
18046        final String installerPackageName = args.installerPackageName;
18047        final String volumeUuid = args.volumeUuid;
18048        final File tmpPackageFile = new File(args.getCodePath());
18049        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18050        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18051                || (args.volumeUuid != null));
18052        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18053        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18054        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18055        boolean replace = false;
18056        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18057        if (args.move != null) {
18058            // moving a complete application; perform an initial scan on the new install location
18059            scanFlags |= SCAN_INITIAL;
18060        }
18061        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18062            scanFlags |= SCAN_DONT_KILL_APP;
18063        }
18064        if (instantApp) {
18065            scanFlags |= SCAN_AS_INSTANT_APP;
18066        }
18067        if (fullApp) {
18068            scanFlags |= SCAN_AS_FULL_APP;
18069        }
18070
18071        // Result object to be returned
18072        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18073
18074        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18075
18076        // Sanity check
18077        if (instantApp && (forwardLocked || onExternal)) {
18078            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18079                    + " external=" + onExternal);
18080            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18081            return;
18082        }
18083
18084        // Retrieve PackageSettings and parse package
18085        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18086                | PackageParser.PARSE_ENFORCE_CODE
18087                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18088                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18089                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18090                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18091        PackageParser pp = new PackageParser();
18092        pp.setSeparateProcesses(mSeparateProcesses);
18093        pp.setDisplayMetrics(mMetrics);
18094        pp.setCallback(mPackageParserCallback);
18095
18096        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18097        final PackageParser.Package pkg;
18098        try {
18099            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18100        } catch (PackageParserException e) {
18101            res.setError("Failed parse during installPackageLI", e);
18102            return;
18103        } finally {
18104            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18105        }
18106
18107        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18108        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18109            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18110            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18111                    "Instant app package must target O");
18112            return;
18113        }
18114        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18115            Slog.w(TAG, "Instant app package " + pkg.packageName
18116                    + " does not target targetSandboxVersion 2");
18117            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18118                    "Instant app package must use targetSanboxVersion 2");
18119            return;
18120        }
18121
18122        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18123            // Static shared libraries have synthetic package names
18124            renameStaticSharedLibraryPackage(pkg);
18125
18126            // No static shared libs on external storage
18127            if (onExternal) {
18128                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18129                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18130                        "Packages declaring static-shared libs cannot be updated");
18131                return;
18132            }
18133        }
18134
18135        // If we are installing a clustered package add results for the children
18136        if (pkg.childPackages != null) {
18137            synchronized (mPackages) {
18138                final int childCount = pkg.childPackages.size();
18139                for (int i = 0; i < childCount; i++) {
18140                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18141                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18142                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18143                    childRes.pkg = childPkg;
18144                    childRes.name = childPkg.packageName;
18145                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18146                    if (childPs != null) {
18147                        childRes.origUsers = childPs.queryInstalledUsers(
18148                                sUserManager.getUserIds(), true);
18149                    }
18150                    if ((mPackages.containsKey(childPkg.packageName))) {
18151                        childRes.removedInfo = new PackageRemovedInfo(this);
18152                        childRes.removedInfo.removedPackage = childPkg.packageName;
18153                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18154                    }
18155                    if (res.addedChildPackages == null) {
18156                        res.addedChildPackages = new ArrayMap<>();
18157                    }
18158                    res.addedChildPackages.put(childPkg.packageName, childRes);
18159                }
18160            }
18161        }
18162
18163        // If package doesn't declare API override, mark that we have an install
18164        // time CPU ABI override.
18165        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18166            pkg.cpuAbiOverride = args.abiOverride;
18167        }
18168
18169        String pkgName = res.name = pkg.packageName;
18170        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18171            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18172                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18173                return;
18174            }
18175        }
18176
18177        try {
18178            // either use what we've been given or parse directly from the APK
18179            if (args.certificates != null) {
18180                try {
18181                    PackageParser.populateCertificates(pkg, args.certificates);
18182                } catch (PackageParserException e) {
18183                    // there was something wrong with the certificates we were given;
18184                    // try to pull them from the APK
18185                    PackageParser.collectCertificates(pkg, parseFlags);
18186                }
18187            } else {
18188                PackageParser.collectCertificates(pkg, parseFlags);
18189            }
18190        } catch (PackageParserException e) {
18191            res.setError("Failed collect during installPackageLI", e);
18192            return;
18193        }
18194
18195        // Get rid of all references to package scan path via parser.
18196        pp = null;
18197        String oldCodePath = null;
18198        boolean systemApp = false;
18199        synchronized (mPackages) {
18200            // Check if installing already existing package
18201            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18202                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18203                if (pkg.mOriginalPackages != null
18204                        && pkg.mOriginalPackages.contains(oldName)
18205                        && mPackages.containsKey(oldName)) {
18206                    // This package is derived from an original package,
18207                    // and this device has been updating from that original
18208                    // name.  We must continue using the original name, so
18209                    // rename the new package here.
18210                    pkg.setPackageName(oldName);
18211                    pkgName = pkg.packageName;
18212                    replace = true;
18213                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18214                            + oldName + " pkgName=" + pkgName);
18215                } else if (mPackages.containsKey(pkgName)) {
18216                    // This package, under its official name, already exists
18217                    // on the device; we should replace it.
18218                    replace = true;
18219                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18220                }
18221
18222                // Child packages are installed through the parent package
18223                if (pkg.parentPackage != null) {
18224                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18225                            "Package " + pkg.packageName + " is child of package "
18226                                    + pkg.parentPackage.parentPackage + ". Child packages "
18227                                    + "can be updated only through the parent package.");
18228                    return;
18229                }
18230
18231                if (replace) {
18232                    // Prevent apps opting out from runtime permissions
18233                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18234                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18235                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18236                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18237                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18238                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18239                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18240                                        + " doesn't support runtime permissions but the old"
18241                                        + " target SDK " + oldTargetSdk + " does.");
18242                        return;
18243                    }
18244                    // Prevent apps from downgrading their targetSandbox.
18245                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18246                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18247                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18248                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18249                                "Package " + pkg.packageName + " new target sandbox "
18250                                + newTargetSandbox + " is incompatible with the previous value of"
18251                                + oldTargetSandbox + ".");
18252                        return;
18253                    }
18254
18255                    // Prevent installing of child packages
18256                    if (oldPackage.parentPackage != null) {
18257                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18258                                "Package " + pkg.packageName + " is child of package "
18259                                        + oldPackage.parentPackage + ". Child packages "
18260                                        + "can be updated only through the parent package.");
18261                        return;
18262                    }
18263                }
18264            }
18265
18266            PackageSetting ps = mSettings.mPackages.get(pkgName);
18267            if (ps != null) {
18268                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18269
18270                // Static shared libs have same package with different versions where
18271                // we internally use a synthetic package name to allow multiple versions
18272                // of the same package, therefore we need to compare signatures against
18273                // the package setting for the latest library version.
18274                PackageSetting signatureCheckPs = ps;
18275                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18276                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18277                    if (libraryEntry != null) {
18278                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18279                    }
18280                }
18281
18282                // Quick sanity check that we're signed correctly if updating;
18283                // we'll check this again later when scanning, but we want to
18284                // bail early here before tripping over redefined permissions.
18285                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18286                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18287                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18288                                + pkg.packageName + " upgrade keys do not match the "
18289                                + "previously installed version");
18290                        return;
18291                    }
18292                } else {
18293                    try {
18294                        verifySignaturesLP(signatureCheckPs, pkg);
18295                    } catch (PackageManagerException e) {
18296                        res.setError(e.error, e.getMessage());
18297                        return;
18298                    }
18299                }
18300
18301                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18302                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18303                    systemApp = (ps.pkg.applicationInfo.flags &
18304                            ApplicationInfo.FLAG_SYSTEM) != 0;
18305                }
18306                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18307            }
18308
18309            int N = pkg.permissions.size();
18310            for (int i = N-1; i >= 0; i--) {
18311                PackageParser.Permission perm = pkg.permissions.get(i);
18312                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18313
18314                // Don't allow anyone but the system to define ephemeral permissions.
18315                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18316                        && !systemApp) {
18317                    Slog.w(TAG, "Non-System package " + pkg.packageName
18318                            + " attempting to delcare ephemeral permission "
18319                            + perm.info.name + "; Removing ephemeral.");
18320                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18321                }
18322                // Check whether the newly-scanned package wants to define an already-defined perm
18323                if (bp != null) {
18324                    // If the defining package is signed with our cert, it's okay.  This
18325                    // also includes the "updating the same package" case, of course.
18326                    // "updating same package" could also involve key-rotation.
18327                    final boolean sigsOk;
18328                    if (bp.sourcePackage.equals(pkg.packageName)
18329                            && (bp.packageSetting instanceof PackageSetting)
18330                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18331                                    scanFlags))) {
18332                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18333                    } else {
18334                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18335                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18336                    }
18337                    if (!sigsOk) {
18338                        // If the owning package is the system itself, we log but allow
18339                        // install to proceed; we fail the install on all other permission
18340                        // redefinitions.
18341                        if (!bp.sourcePackage.equals("android")) {
18342                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18343                                    + pkg.packageName + " attempting to redeclare permission "
18344                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18345                            res.origPermission = perm.info.name;
18346                            res.origPackage = bp.sourcePackage;
18347                            return;
18348                        } else {
18349                            Slog.w(TAG, "Package " + pkg.packageName
18350                                    + " attempting to redeclare system permission "
18351                                    + perm.info.name + "; ignoring new declaration");
18352                            pkg.permissions.remove(i);
18353                        }
18354                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18355                        // Prevent apps to change protection level to dangerous from any other
18356                        // type as this would allow a privilege escalation where an app adds a
18357                        // normal/signature permission in other app's group and later redefines
18358                        // it as dangerous leading to the group auto-grant.
18359                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18360                                == PermissionInfo.PROTECTION_DANGEROUS) {
18361                            if (bp != null && !bp.isRuntime()) {
18362                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18363                                        + "non-runtime permission " + perm.info.name
18364                                        + " to runtime; keeping old protection level");
18365                                perm.info.protectionLevel = bp.protectionLevel;
18366                            }
18367                        }
18368                    }
18369                }
18370            }
18371        }
18372
18373        if (systemApp) {
18374            if (onExternal) {
18375                // Abort update; system app can't be replaced with app on sdcard
18376                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18377                        "Cannot install updates to system apps on sdcard");
18378                return;
18379            } else if (instantApp) {
18380                // Abort update; system app can't be replaced with an instant app
18381                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18382                        "Cannot update a system app with an instant app");
18383                return;
18384            }
18385        }
18386
18387        if (args.move != null) {
18388            // We did an in-place move, so dex is ready to roll
18389            scanFlags |= SCAN_NO_DEX;
18390            scanFlags |= SCAN_MOVE;
18391
18392            synchronized (mPackages) {
18393                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18394                if (ps == null) {
18395                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18396                            "Missing settings for moved package " + pkgName);
18397                }
18398
18399                // We moved the entire application as-is, so bring over the
18400                // previously derived ABI information.
18401                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18402                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18403            }
18404
18405        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18406            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18407            scanFlags |= SCAN_NO_DEX;
18408
18409            try {
18410                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18411                    args.abiOverride : pkg.cpuAbiOverride);
18412                final boolean extractNativeLibs = !pkg.isLibrary();
18413                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18414                        extractNativeLibs, mAppLib32InstallDir);
18415            } catch (PackageManagerException pme) {
18416                Slog.e(TAG, "Error deriving application ABI", pme);
18417                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18418                return;
18419            }
18420
18421            // Shared libraries for the package need to be updated.
18422            synchronized (mPackages) {
18423                try {
18424                    updateSharedLibrariesLPr(pkg, null);
18425                } catch (PackageManagerException e) {
18426                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18427                }
18428            }
18429
18430            // dexopt can take some time to complete, so, for instant apps, we skip this
18431            // step during installation. Instead, we'll take extra time the first time the
18432            // instant app starts. It's preferred to do it this way to provide continuous
18433            // progress to the user instead of mysteriously blocking somewhere in the
18434            // middle of running an instant app. The default behaviour can be overridden
18435            // via gservices.
18436            if (!instantApp || Global.getInt(
18437                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18438                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18439                // Do not run PackageDexOptimizer through the local performDexOpt
18440                // method because `pkg` may not be in `mPackages` yet.
18441                //
18442                // Also, don't fail application installs if the dexopt step fails.
18443                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18444                        REASON_INSTALL,
18445                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18446                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18447                        null /* instructionSets */,
18448                        getOrCreateCompilerPackageStats(pkg),
18449                        mDexManager.isUsedByOtherApps(pkg.packageName),
18450                        dexoptOptions);
18451                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18452            }
18453
18454            // Notify BackgroundDexOptService that the package has been changed.
18455            // If this is an update of a package which used to fail to compile,
18456            // BDOS will remove it from its blacklist.
18457            // TODO: Layering violation
18458            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18459        }
18460
18461        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18462            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18463            return;
18464        }
18465
18466        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18467
18468        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18469                "installPackageLI")) {
18470            if (replace) {
18471                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18472                    // Static libs have a synthetic package name containing the version
18473                    // and cannot be updated as an update would get a new package name,
18474                    // unless this is the exact same version code which is useful for
18475                    // development.
18476                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18477                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18478                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18479                                + "static-shared libs cannot be updated");
18480                        return;
18481                    }
18482                }
18483                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18484                        installerPackageName, res, args.installReason);
18485            } else {
18486                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18487                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18488            }
18489        }
18490
18491        synchronized (mPackages) {
18492            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18493            if (ps != null) {
18494                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18495                ps.setUpdateAvailable(false /*updateAvailable*/);
18496            }
18497
18498            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18499            for (int i = 0; i < childCount; i++) {
18500                PackageParser.Package childPkg = pkg.childPackages.get(i);
18501                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18502                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18503                if (childPs != null) {
18504                    childRes.newUsers = childPs.queryInstalledUsers(
18505                            sUserManager.getUserIds(), true);
18506                }
18507            }
18508
18509            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18510                updateSequenceNumberLP(ps, res.newUsers);
18511                updateInstantAppInstallerLocked(pkgName);
18512            }
18513        }
18514    }
18515
18516    private void startIntentFilterVerifications(int userId, boolean replacing,
18517            PackageParser.Package pkg) {
18518        if (mIntentFilterVerifierComponent == null) {
18519            Slog.w(TAG, "No IntentFilter verification will not be done as "
18520                    + "there is no IntentFilterVerifier available!");
18521            return;
18522        }
18523
18524        final int verifierUid = getPackageUid(
18525                mIntentFilterVerifierComponent.getPackageName(),
18526                MATCH_DEBUG_TRIAGED_MISSING,
18527                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18528
18529        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18530        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18531        mHandler.sendMessage(msg);
18532
18533        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18534        for (int i = 0; i < childCount; i++) {
18535            PackageParser.Package childPkg = pkg.childPackages.get(i);
18536            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18537            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18538            mHandler.sendMessage(msg);
18539        }
18540    }
18541
18542    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18543            PackageParser.Package pkg) {
18544        int size = pkg.activities.size();
18545        if (size == 0) {
18546            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18547                    "No activity, so no need to verify any IntentFilter!");
18548            return;
18549        }
18550
18551        final boolean hasDomainURLs = hasDomainURLs(pkg);
18552        if (!hasDomainURLs) {
18553            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18554                    "No domain URLs, so no need to verify any IntentFilter!");
18555            return;
18556        }
18557
18558        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18559                + " if any IntentFilter from the " + size
18560                + " Activities needs verification ...");
18561
18562        int count = 0;
18563        final String packageName = pkg.packageName;
18564
18565        synchronized (mPackages) {
18566            // If this is a new install and we see that we've already run verification for this
18567            // package, we have nothing to do: it means the state was restored from backup.
18568            if (!replacing) {
18569                IntentFilterVerificationInfo ivi =
18570                        mSettings.getIntentFilterVerificationLPr(packageName);
18571                if (ivi != null) {
18572                    if (DEBUG_DOMAIN_VERIFICATION) {
18573                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18574                                + ivi.getStatusString());
18575                    }
18576                    return;
18577                }
18578            }
18579
18580            // If any filters need to be verified, then all need to be.
18581            boolean needToVerify = false;
18582            for (PackageParser.Activity a : pkg.activities) {
18583                for (ActivityIntentInfo filter : a.intents) {
18584                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18585                        if (DEBUG_DOMAIN_VERIFICATION) {
18586                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18587                        }
18588                        needToVerify = true;
18589                        break;
18590                    }
18591                }
18592            }
18593
18594            if (needToVerify) {
18595                final int verificationId = mIntentFilterVerificationToken++;
18596                for (PackageParser.Activity a : pkg.activities) {
18597                    for (ActivityIntentInfo filter : a.intents) {
18598                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18599                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18600                                    "Verification needed for IntentFilter:" + filter.toString());
18601                            mIntentFilterVerifier.addOneIntentFilterVerification(
18602                                    verifierUid, userId, verificationId, filter, packageName);
18603                            count++;
18604                        }
18605                    }
18606                }
18607            }
18608        }
18609
18610        if (count > 0) {
18611            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18612                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18613                    +  " for userId:" + userId);
18614            mIntentFilterVerifier.startVerifications(userId);
18615        } else {
18616            if (DEBUG_DOMAIN_VERIFICATION) {
18617                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18618            }
18619        }
18620    }
18621
18622    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18623        final ComponentName cn  = filter.activity.getComponentName();
18624        final String packageName = cn.getPackageName();
18625
18626        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18627                packageName);
18628        if (ivi == null) {
18629            return true;
18630        }
18631        int status = ivi.getStatus();
18632        switch (status) {
18633            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18634            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18635                return true;
18636
18637            default:
18638                // Nothing to do
18639                return false;
18640        }
18641    }
18642
18643    private static boolean isMultiArch(ApplicationInfo info) {
18644        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18645    }
18646
18647    private static boolean isExternal(PackageParser.Package pkg) {
18648        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18649    }
18650
18651    private static boolean isExternal(PackageSetting ps) {
18652        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18653    }
18654
18655    private static boolean isSystemApp(PackageParser.Package pkg) {
18656        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18657    }
18658
18659    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18660        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18661    }
18662
18663    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18664        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18665    }
18666
18667    private static boolean isSystemApp(PackageSetting ps) {
18668        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18669    }
18670
18671    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18672        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18673    }
18674
18675    private int packageFlagsToInstallFlags(PackageSetting ps) {
18676        int installFlags = 0;
18677        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18678            // This existing package was an external ASEC install when we have
18679            // the external flag without a UUID
18680            installFlags |= PackageManager.INSTALL_EXTERNAL;
18681        }
18682        if (ps.isForwardLocked()) {
18683            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18684        }
18685        return installFlags;
18686    }
18687
18688    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18689        if (isExternal(pkg)) {
18690            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18691                return StorageManager.UUID_PRIMARY_PHYSICAL;
18692            } else {
18693                return pkg.volumeUuid;
18694            }
18695        } else {
18696            return StorageManager.UUID_PRIVATE_INTERNAL;
18697        }
18698    }
18699
18700    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18701        if (isExternal(pkg)) {
18702            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18703                return mSettings.getExternalVersion();
18704            } else {
18705                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18706            }
18707        } else {
18708            return mSettings.getInternalVersion();
18709        }
18710    }
18711
18712    private void deleteTempPackageFiles() {
18713        final FilenameFilter filter = new FilenameFilter() {
18714            public boolean accept(File dir, String name) {
18715                return name.startsWith("vmdl") && name.endsWith(".tmp");
18716            }
18717        };
18718        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18719            file.delete();
18720        }
18721    }
18722
18723    @Override
18724    public void deletePackageAsUser(String packageName, int versionCode,
18725            IPackageDeleteObserver observer, int userId, int flags) {
18726        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18727                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18728    }
18729
18730    @Override
18731    public void deletePackageVersioned(VersionedPackage versionedPackage,
18732            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18733        final int callingUid = Binder.getCallingUid();
18734        mContext.enforceCallingOrSelfPermission(
18735                android.Manifest.permission.DELETE_PACKAGES, null);
18736        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18737        Preconditions.checkNotNull(versionedPackage);
18738        Preconditions.checkNotNull(observer);
18739        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18740                PackageManager.VERSION_CODE_HIGHEST,
18741                Integer.MAX_VALUE, "versionCode must be >= -1");
18742
18743        final String packageName = versionedPackage.getPackageName();
18744        final int versionCode = versionedPackage.getVersionCode();
18745        final String internalPackageName;
18746        synchronized (mPackages) {
18747            // Normalize package name to handle renamed packages and static libs
18748            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18749                    versionedPackage.getVersionCode());
18750        }
18751
18752        final int uid = Binder.getCallingUid();
18753        if (!isOrphaned(internalPackageName)
18754                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18755            try {
18756                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18757                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18758                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18759                observer.onUserActionRequired(intent);
18760            } catch (RemoteException re) {
18761            }
18762            return;
18763        }
18764        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18765        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18766        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18767            mContext.enforceCallingOrSelfPermission(
18768                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18769                    "deletePackage for user " + userId);
18770        }
18771
18772        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18773            try {
18774                observer.onPackageDeleted(packageName,
18775                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18776            } catch (RemoteException re) {
18777            }
18778            return;
18779        }
18780
18781        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18782            try {
18783                observer.onPackageDeleted(packageName,
18784                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18785            } catch (RemoteException re) {
18786            }
18787            return;
18788        }
18789
18790        if (DEBUG_REMOVE) {
18791            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18792                    + " deleteAllUsers: " + deleteAllUsers + " version="
18793                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18794                    ? "VERSION_CODE_HIGHEST" : versionCode));
18795        }
18796        // Queue up an async operation since the package deletion may take a little while.
18797        mHandler.post(new Runnable() {
18798            public void run() {
18799                mHandler.removeCallbacks(this);
18800                int returnCode;
18801                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18802                boolean doDeletePackage = true;
18803                if (ps != null) {
18804                    final boolean targetIsInstantApp =
18805                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18806                    doDeletePackage = !targetIsInstantApp
18807                            || canViewInstantApps;
18808                }
18809                if (doDeletePackage) {
18810                    if (!deleteAllUsers) {
18811                        returnCode = deletePackageX(internalPackageName, versionCode,
18812                                userId, deleteFlags);
18813                    } else {
18814                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18815                                internalPackageName, users);
18816                        // If nobody is blocking uninstall, proceed with delete for all users
18817                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18818                            returnCode = deletePackageX(internalPackageName, versionCode,
18819                                    userId, deleteFlags);
18820                        } else {
18821                            // Otherwise uninstall individually for users with blockUninstalls=false
18822                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18823                            for (int userId : users) {
18824                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18825                                    returnCode = deletePackageX(internalPackageName, versionCode,
18826                                            userId, userFlags);
18827                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18828                                        Slog.w(TAG, "Package delete failed for user " + userId
18829                                                + ", returnCode " + returnCode);
18830                                    }
18831                                }
18832                            }
18833                            // The app has only been marked uninstalled for certain users.
18834                            // We still need to report that delete was blocked
18835                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18836                        }
18837                    }
18838                } else {
18839                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18840                }
18841                try {
18842                    observer.onPackageDeleted(packageName, returnCode, null);
18843                } catch (RemoteException e) {
18844                    Log.i(TAG, "Observer no longer exists.");
18845                } //end catch
18846            } //end run
18847        });
18848    }
18849
18850    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18851        if (pkg.staticSharedLibName != null) {
18852            return pkg.manifestPackageName;
18853        }
18854        return pkg.packageName;
18855    }
18856
18857    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18858        // Handle renamed packages
18859        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18860        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18861
18862        // Is this a static library?
18863        SparseArray<SharedLibraryEntry> versionedLib =
18864                mStaticLibsByDeclaringPackage.get(packageName);
18865        if (versionedLib == null || versionedLib.size() <= 0) {
18866            return packageName;
18867        }
18868
18869        // Figure out which lib versions the caller can see
18870        SparseIntArray versionsCallerCanSee = null;
18871        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18872        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18873                && callingAppId != Process.ROOT_UID) {
18874            versionsCallerCanSee = new SparseIntArray();
18875            String libName = versionedLib.valueAt(0).info.getName();
18876            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18877            if (uidPackages != null) {
18878                for (String uidPackage : uidPackages) {
18879                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18880                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18881                    if (libIdx >= 0) {
18882                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18883                        versionsCallerCanSee.append(libVersion, libVersion);
18884                    }
18885                }
18886            }
18887        }
18888
18889        // Caller can see nothing - done
18890        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18891            return packageName;
18892        }
18893
18894        // Find the version the caller can see and the app version code
18895        SharedLibraryEntry highestVersion = null;
18896        final int versionCount = versionedLib.size();
18897        for (int i = 0; i < versionCount; i++) {
18898            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18899            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18900                    libEntry.info.getVersion()) < 0) {
18901                continue;
18902            }
18903            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18904            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18905                if (libVersionCode == versionCode) {
18906                    return libEntry.apk;
18907                }
18908            } else if (highestVersion == null) {
18909                highestVersion = libEntry;
18910            } else if (libVersionCode  > highestVersion.info
18911                    .getDeclaringPackage().getVersionCode()) {
18912                highestVersion = libEntry;
18913            }
18914        }
18915
18916        if (highestVersion != null) {
18917            return highestVersion.apk;
18918        }
18919
18920        return packageName;
18921    }
18922
18923    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18924        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18925              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18926            return true;
18927        }
18928        final int callingUserId = UserHandle.getUserId(callingUid);
18929        // If the caller installed the pkgName, then allow it to silently uninstall.
18930        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18931            return true;
18932        }
18933
18934        // Allow package verifier to silently uninstall.
18935        if (mRequiredVerifierPackage != null &&
18936                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18937            return true;
18938        }
18939
18940        // Allow package uninstaller to silently uninstall.
18941        if (mRequiredUninstallerPackage != null &&
18942                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18943            return true;
18944        }
18945
18946        // Allow storage manager to silently uninstall.
18947        if (mStorageManagerPackage != null &&
18948                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18949            return true;
18950        }
18951
18952        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18953        // uninstall for device owner provisioning.
18954        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18955                == PERMISSION_GRANTED) {
18956            return true;
18957        }
18958
18959        return false;
18960    }
18961
18962    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18963        int[] result = EMPTY_INT_ARRAY;
18964        for (int userId : userIds) {
18965            if (getBlockUninstallForUser(packageName, userId)) {
18966                result = ArrayUtils.appendInt(result, userId);
18967            }
18968        }
18969        return result;
18970    }
18971
18972    @Override
18973    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18974        final int callingUid = Binder.getCallingUid();
18975        if (getInstantAppPackageName(callingUid) != null
18976                && !isCallerSameApp(packageName, callingUid)) {
18977            return false;
18978        }
18979        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18980    }
18981
18982    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18983        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18984                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18985        try {
18986            if (dpm != null) {
18987                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18988                        /* callingUserOnly =*/ false);
18989                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18990                        : deviceOwnerComponentName.getPackageName();
18991                // Does the package contains the device owner?
18992                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18993                // this check is probably not needed, since DO should be registered as a device
18994                // admin on some user too. (Original bug for this: b/17657954)
18995                if (packageName.equals(deviceOwnerPackageName)) {
18996                    return true;
18997                }
18998                // Does it contain a device admin for any user?
18999                int[] users;
19000                if (userId == UserHandle.USER_ALL) {
19001                    users = sUserManager.getUserIds();
19002                } else {
19003                    users = new int[]{userId};
19004                }
19005                for (int i = 0; i < users.length; ++i) {
19006                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19007                        return true;
19008                    }
19009                }
19010            }
19011        } catch (RemoteException e) {
19012        }
19013        return false;
19014    }
19015
19016    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19017        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19018    }
19019
19020    /**
19021     *  This method is an internal method that could be get invoked either
19022     *  to delete an installed package or to clean up a failed installation.
19023     *  After deleting an installed package, a broadcast is sent to notify any
19024     *  listeners that the package has been removed. For cleaning up a failed
19025     *  installation, the broadcast is not necessary since the package's
19026     *  installation wouldn't have sent the initial broadcast either
19027     *  The key steps in deleting a package are
19028     *  deleting the package information in internal structures like mPackages,
19029     *  deleting the packages base directories through installd
19030     *  updating mSettings to reflect current status
19031     *  persisting settings for later use
19032     *  sending a broadcast if necessary
19033     */
19034    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19035        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19036        final boolean res;
19037
19038        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19039                ? UserHandle.USER_ALL : userId;
19040
19041        if (isPackageDeviceAdmin(packageName, removeUser)) {
19042            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19043            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19044        }
19045
19046        PackageSetting uninstalledPs = null;
19047        PackageParser.Package pkg = null;
19048
19049        // for the uninstall-updates case and restricted profiles, remember the per-
19050        // user handle installed state
19051        int[] allUsers;
19052        synchronized (mPackages) {
19053            uninstalledPs = mSettings.mPackages.get(packageName);
19054            if (uninstalledPs == null) {
19055                Slog.w(TAG, "Not removing non-existent package " + packageName);
19056                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19057            }
19058
19059            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19060                    && uninstalledPs.versionCode != versionCode) {
19061                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19062                        + uninstalledPs.versionCode + " != " + versionCode);
19063                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19064            }
19065
19066            // Static shared libs can be declared by any package, so let us not
19067            // allow removing a package if it provides a lib others depend on.
19068            pkg = mPackages.get(packageName);
19069
19070            allUsers = sUserManager.getUserIds();
19071
19072            if (pkg != null && pkg.staticSharedLibName != null) {
19073                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19074                        pkg.staticSharedLibVersion);
19075                if (libEntry != null) {
19076                    for (int currUserId : allUsers) {
19077                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19078                            continue;
19079                        }
19080                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19081                                libEntry.info, 0, currUserId);
19082                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19083                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19084                                    + " hosting lib " + libEntry.info.getName() + " version "
19085                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19086                                    + " for user " + currUserId);
19087                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19088                        }
19089                    }
19090                }
19091            }
19092
19093            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19094        }
19095
19096        final int freezeUser;
19097        if (isUpdatedSystemApp(uninstalledPs)
19098                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19099            // We're downgrading a system app, which will apply to all users, so
19100            // freeze them all during the downgrade
19101            freezeUser = UserHandle.USER_ALL;
19102        } else {
19103            freezeUser = removeUser;
19104        }
19105
19106        synchronized (mInstallLock) {
19107            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19108            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19109                    deleteFlags, "deletePackageX")) {
19110                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19111                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19112            }
19113            synchronized (mPackages) {
19114                if (res) {
19115                    if (pkg != null) {
19116                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19117                    }
19118                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19119                    updateInstantAppInstallerLocked(packageName);
19120                }
19121            }
19122        }
19123
19124        if (res) {
19125            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19126            info.sendPackageRemovedBroadcasts(killApp);
19127            info.sendSystemPackageUpdatedBroadcasts();
19128            info.sendSystemPackageAppearedBroadcasts();
19129        }
19130        // Force a gc here.
19131        Runtime.getRuntime().gc();
19132        // Delete the resources here after sending the broadcast to let
19133        // other processes clean up before deleting resources.
19134        if (info.args != null) {
19135            synchronized (mInstallLock) {
19136                info.args.doPostDeleteLI(true);
19137            }
19138        }
19139
19140        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19141    }
19142
19143    static class PackageRemovedInfo {
19144        final PackageSender packageSender;
19145        String removedPackage;
19146        String installerPackageName;
19147        int uid = -1;
19148        int removedAppId = -1;
19149        int[] origUsers;
19150        int[] removedUsers = null;
19151        int[] broadcastUsers = null;
19152        SparseArray<Integer> installReasons;
19153        boolean isRemovedPackageSystemUpdate = false;
19154        boolean isUpdate;
19155        boolean dataRemoved;
19156        boolean removedForAllUsers;
19157        boolean isStaticSharedLib;
19158        // Clean up resources deleted packages.
19159        InstallArgs args = null;
19160        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19161        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19162
19163        PackageRemovedInfo(PackageSender packageSender) {
19164            this.packageSender = packageSender;
19165        }
19166
19167        void sendPackageRemovedBroadcasts(boolean killApp) {
19168            sendPackageRemovedBroadcastInternal(killApp);
19169            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19170            for (int i = 0; i < childCount; i++) {
19171                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19172                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19173            }
19174        }
19175
19176        void sendSystemPackageUpdatedBroadcasts() {
19177            if (isRemovedPackageSystemUpdate) {
19178                sendSystemPackageUpdatedBroadcastsInternal();
19179                final int childCount = (removedChildPackages != null)
19180                        ? removedChildPackages.size() : 0;
19181                for (int i = 0; i < childCount; i++) {
19182                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19183                    if (childInfo.isRemovedPackageSystemUpdate) {
19184                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19185                    }
19186                }
19187            }
19188        }
19189
19190        void sendSystemPackageAppearedBroadcasts() {
19191            final int packageCount = (appearedChildPackages != null)
19192                    ? appearedChildPackages.size() : 0;
19193            for (int i = 0; i < packageCount; i++) {
19194                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19195                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19196                    true, UserHandle.getAppId(installedInfo.uid),
19197                    installedInfo.newUsers);
19198            }
19199        }
19200
19201        private void sendSystemPackageUpdatedBroadcastsInternal() {
19202            Bundle extras = new Bundle(2);
19203            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19204            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19205            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19206                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19207            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19208                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19209            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19210                null, null, 0, removedPackage, null, null);
19211            if (installerPackageName != null) {
19212                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19213                        removedPackage, extras, 0 /*flags*/,
19214                        installerPackageName, null, null);
19215                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19216                        removedPackage, extras, 0 /*flags*/,
19217                        installerPackageName, null, null);
19218            }
19219        }
19220
19221        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19222            // Don't send static shared library removal broadcasts as these
19223            // libs are visible only the the apps that depend on them an one
19224            // cannot remove the library if it has a dependency.
19225            if (isStaticSharedLib) {
19226                return;
19227            }
19228            Bundle extras = new Bundle(2);
19229            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19230            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19231            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19232            if (isUpdate || isRemovedPackageSystemUpdate) {
19233                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19234            }
19235            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19236            if (removedPackage != null) {
19237                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19238                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19239                if (installerPackageName != null) {
19240                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19241                            removedPackage, extras, 0 /*flags*/,
19242                            installerPackageName, null, broadcastUsers);
19243                }
19244                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19245                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19246                        removedPackage, extras,
19247                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19248                        null, null, broadcastUsers);
19249                }
19250            }
19251            if (removedAppId >= 0) {
19252                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19253                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19254                    null, null, broadcastUsers);
19255            }
19256        }
19257
19258        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19259            removedUsers = userIds;
19260            if (removedUsers == null) {
19261                broadcastUsers = null;
19262                return;
19263            }
19264
19265            broadcastUsers = EMPTY_INT_ARRAY;
19266            for (int i = userIds.length - 1; i >= 0; --i) {
19267                final int userId = userIds[i];
19268                if (deletedPackageSetting.getInstantApp(userId)) {
19269                    continue;
19270                }
19271                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19272            }
19273        }
19274    }
19275
19276    /*
19277     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19278     * flag is not set, the data directory is removed as well.
19279     * make sure this flag is set for partially installed apps. If not its meaningless to
19280     * delete a partially installed application.
19281     */
19282    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19283            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19284        String packageName = ps.name;
19285        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19286        // Retrieve object to delete permissions for shared user later on
19287        final PackageParser.Package deletedPkg;
19288        final PackageSetting deletedPs;
19289        // reader
19290        synchronized (mPackages) {
19291            deletedPkg = mPackages.get(packageName);
19292            deletedPs = mSettings.mPackages.get(packageName);
19293            if (outInfo != null) {
19294                outInfo.removedPackage = packageName;
19295                outInfo.installerPackageName = ps.installerPackageName;
19296                outInfo.isStaticSharedLib = deletedPkg != null
19297                        && deletedPkg.staticSharedLibName != null;
19298                outInfo.populateUsers(deletedPs == null ? null
19299                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19300            }
19301        }
19302
19303        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19304
19305        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19306            final PackageParser.Package resolvedPkg;
19307            if (deletedPkg != null) {
19308                resolvedPkg = deletedPkg;
19309            } else {
19310                // We don't have a parsed package when it lives on an ejected
19311                // adopted storage device, so fake something together
19312                resolvedPkg = new PackageParser.Package(ps.name);
19313                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19314            }
19315            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19316                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19317            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19318            if (outInfo != null) {
19319                outInfo.dataRemoved = true;
19320            }
19321            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19322        }
19323
19324        int removedAppId = -1;
19325
19326        // writer
19327        synchronized (mPackages) {
19328            boolean installedStateChanged = false;
19329            if (deletedPs != null) {
19330                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19331                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19332                    clearDefaultBrowserIfNeeded(packageName);
19333                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19334                    removedAppId = mSettings.removePackageLPw(packageName);
19335                    if (outInfo != null) {
19336                        outInfo.removedAppId = removedAppId;
19337                    }
19338                    updatePermissionsLPw(deletedPs.name, null, 0);
19339                    if (deletedPs.sharedUser != null) {
19340                        // Remove permissions associated with package. Since runtime
19341                        // permissions are per user we have to kill the removed package
19342                        // or packages running under the shared user of the removed
19343                        // package if revoking the permissions requested only by the removed
19344                        // package is successful and this causes a change in gids.
19345                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19346                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19347                                    userId);
19348                            if (userIdToKill == UserHandle.USER_ALL
19349                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19350                                // If gids changed for this user, kill all affected packages.
19351                                mHandler.post(new Runnable() {
19352                                    @Override
19353                                    public void run() {
19354                                        // This has to happen with no lock held.
19355                                        killApplication(deletedPs.name, deletedPs.appId,
19356                                                KILL_APP_REASON_GIDS_CHANGED);
19357                                    }
19358                                });
19359                                break;
19360                            }
19361                        }
19362                    }
19363                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19364                }
19365                // make sure to preserve per-user disabled state if this removal was just
19366                // a downgrade of a system app to the factory package
19367                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19368                    if (DEBUG_REMOVE) {
19369                        Slog.d(TAG, "Propagating install state across downgrade");
19370                    }
19371                    for (int userId : allUserHandles) {
19372                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19373                        if (DEBUG_REMOVE) {
19374                            Slog.d(TAG, "    user " + userId + " => " + installed);
19375                        }
19376                        if (installed != ps.getInstalled(userId)) {
19377                            installedStateChanged = true;
19378                        }
19379                        ps.setInstalled(installed, userId);
19380                    }
19381                }
19382            }
19383            // can downgrade to reader
19384            if (writeSettings) {
19385                // Save settings now
19386                mSettings.writeLPr();
19387            }
19388            if (installedStateChanged) {
19389                mSettings.writeKernelMappingLPr(ps);
19390            }
19391        }
19392        if (removedAppId != -1) {
19393            // A user ID was deleted here. Go through all users and remove it
19394            // from KeyStore.
19395            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19396        }
19397    }
19398
19399    static boolean locationIsPrivileged(File path) {
19400        try {
19401            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19402                    .getCanonicalPath();
19403            return path.getCanonicalPath().startsWith(privilegedAppDir);
19404        } catch (IOException e) {
19405            Slog.e(TAG, "Unable to access code path " + path);
19406        }
19407        return false;
19408    }
19409
19410    /*
19411     * Tries to delete system package.
19412     */
19413    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19414            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19415            boolean writeSettings) {
19416        if (deletedPs.parentPackageName != null) {
19417            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19418            return false;
19419        }
19420
19421        final boolean applyUserRestrictions
19422                = (allUserHandles != null) && (outInfo.origUsers != null);
19423        final PackageSetting disabledPs;
19424        // Confirm if the system package has been updated
19425        // An updated system app can be deleted. This will also have to restore
19426        // the system pkg from system partition
19427        // reader
19428        synchronized (mPackages) {
19429            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19430        }
19431
19432        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19433                + " disabledPs=" + disabledPs);
19434
19435        if (disabledPs == null) {
19436            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19437            return false;
19438        } else if (DEBUG_REMOVE) {
19439            Slog.d(TAG, "Deleting system pkg from data partition");
19440        }
19441
19442        if (DEBUG_REMOVE) {
19443            if (applyUserRestrictions) {
19444                Slog.d(TAG, "Remembering install states:");
19445                for (int userId : allUserHandles) {
19446                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19447                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19448                }
19449            }
19450        }
19451
19452        // Delete the updated package
19453        outInfo.isRemovedPackageSystemUpdate = true;
19454        if (outInfo.removedChildPackages != null) {
19455            final int childCount = (deletedPs.childPackageNames != null)
19456                    ? deletedPs.childPackageNames.size() : 0;
19457            for (int i = 0; i < childCount; i++) {
19458                String childPackageName = deletedPs.childPackageNames.get(i);
19459                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19460                        .contains(childPackageName)) {
19461                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19462                            childPackageName);
19463                    if (childInfo != null) {
19464                        childInfo.isRemovedPackageSystemUpdate = true;
19465                    }
19466                }
19467            }
19468        }
19469
19470        if (disabledPs.versionCode < deletedPs.versionCode) {
19471            // Delete data for downgrades
19472            flags &= ~PackageManager.DELETE_KEEP_DATA;
19473        } else {
19474            // Preserve data by setting flag
19475            flags |= PackageManager.DELETE_KEEP_DATA;
19476        }
19477
19478        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19479                outInfo, writeSettings, disabledPs.pkg);
19480        if (!ret) {
19481            return false;
19482        }
19483
19484        // writer
19485        synchronized (mPackages) {
19486            // Reinstate the old system package
19487            enableSystemPackageLPw(disabledPs.pkg);
19488            // Remove any native libraries from the upgraded package.
19489            removeNativeBinariesLI(deletedPs);
19490        }
19491
19492        // Install the system package
19493        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19494        int parseFlags = mDefParseFlags
19495                | PackageParser.PARSE_MUST_BE_APK
19496                | PackageParser.PARSE_IS_SYSTEM
19497                | PackageParser.PARSE_IS_SYSTEM_DIR;
19498        if (locationIsPrivileged(disabledPs.codePath)) {
19499            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19500        }
19501
19502        final PackageParser.Package newPkg;
19503        try {
19504            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19505                0 /* currentTime */, null);
19506        } catch (PackageManagerException e) {
19507            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19508                    + e.getMessage());
19509            return false;
19510        }
19511
19512        try {
19513            // update shared libraries for the newly re-installed system package
19514            updateSharedLibrariesLPr(newPkg, null);
19515        } catch (PackageManagerException e) {
19516            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19517        }
19518
19519        prepareAppDataAfterInstallLIF(newPkg);
19520
19521        // writer
19522        synchronized (mPackages) {
19523            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19524
19525            // Propagate the permissions state as we do not want to drop on the floor
19526            // runtime permissions. The update permissions method below will take
19527            // care of removing obsolete permissions and grant install permissions.
19528            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19529            updatePermissionsLPw(newPkg.packageName, newPkg,
19530                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19531
19532            if (applyUserRestrictions) {
19533                boolean installedStateChanged = false;
19534                if (DEBUG_REMOVE) {
19535                    Slog.d(TAG, "Propagating install state across reinstall");
19536                }
19537                for (int userId : allUserHandles) {
19538                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19539                    if (DEBUG_REMOVE) {
19540                        Slog.d(TAG, "    user " + userId + " => " + installed);
19541                    }
19542                    if (installed != ps.getInstalled(userId)) {
19543                        installedStateChanged = true;
19544                    }
19545                    ps.setInstalled(installed, userId);
19546
19547                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19548                }
19549                // Regardless of writeSettings we need to ensure that this restriction
19550                // state propagation is persisted
19551                mSettings.writeAllUsersPackageRestrictionsLPr();
19552                if (installedStateChanged) {
19553                    mSettings.writeKernelMappingLPr(ps);
19554                }
19555            }
19556            // can downgrade to reader here
19557            if (writeSettings) {
19558                mSettings.writeLPr();
19559            }
19560        }
19561        return true;
19562    }
19563
19564    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19565            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19566            PackageRemovedInfo outInfo, boolean writeSettings,
19567            PackageParser.Package replacingPackage) {
19568        synchronized (mPackages) {
19569            if (outInfo != null) {
19570                outInfo.uid = ps.appId;
19571            }
19572
19573            if (outInfo != null && outInfo.removedChildPackages != null) {
19574                final int childCount = (ps.childPackageNames != null)
19575                        ? ps.childPackageNames.size() : 0;
19576                for (int i = 0; i < childCount; i++) {
19577                    String childPackageName = ps.childPackageNames.get(i);
19578                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19579                    if (childPs == null) {
19580                        return false;
19581                    }
19582                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19583                            childPackageName);
19584                    if (childInfo != null) {
19585                        childInfo.uid = childPs.appId;
19586                    }
19587                }
19588            }
19589        }
19590
19591        // Delete package data from internal structures and also remove data if flag is set
19592        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19593
19594        // Delete the child packages data
19595        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19596        for (int i = 0; i < childCount; i++) {
19597            PackageSetting childPs;
19598            synchronized (mPackages) {
19599                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19600            }
19601            if (childPs != null) {
19602                PackageRemovedInfo childOutInfo = (outInfo != null
19603                        && outInfo.removedChildPackages != null)
19604                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19605                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19606                        && (replacingPackage != null
19607                        && !replacingPackage.hasChildPackage(childPs.name))
19608                        ? flags & ~DELETE_KEEP_DATA : flags;
19609                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19610                        deleteFlags, writeSettings);
19611            }
19612        }
19613
19614        // Delete application code and resources only for parent packages
19615        if (ps.parentPackageName == null) {
19616            if (deleteCodeAndResources && (outInfo != null)) {
19617                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19618                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19619                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19620            }
19621        }
19622
19623        return true;
19624    }
19625
19626    @Override
19627    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19628            int userId) {
19629        mContext.enforceCallingOrSelfPermission(
19630                android.Manifest.permission.DELETE_PACKAGES, null);
19631        synchronized (mPackages) {
19632            // Cannot block uninstall of static shared libs as they are
19633            // considered a part of the using app (emulating static linking).
19634            // Also static libs are installed always on internal storage.
19635            PackageParser.Package pkg = mPackages.get(packageName);
19636            if (pkg != null && pkg.staticSharedLibName != null) {
19637                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19638                        + " providing static shared library: " + pkg.staticSharedLibName);
19639                return false;
19640            }
19641            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19642            mSettings.writePackageRestrictionsLPr(userId);
19643        }
19644        return true;
19645    }
19646
19647    @Override
19648    public boolean getBlockUninstallForUser(String packageName, int userId) {
19649        synchronized (mPackages) {
19650            final PackageSetting ps = mSettings.mPackages.get(packageName);
19651            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19652                return false;
19653            }
19654            return mSettings.getBlockUninstallLPr(userId, packageName);
19655        }
19656    }
19657
19658    @Override
19659    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19660        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19661        synchronized (mPackages) {
19662            PackageSetting ps = mSettings.mPackages.get(packageName);
19663            if (ps == null) {
19664                Log.w(TAG, "Package doesn't exist: " + packageName);
19665                return false;
19666            }
19667            if (systemUserApp) {
19668                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19669            } else {
19670                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19671            }
19672            mSettings.writeLPr();
19673        }
19674        return true;
19675    }
19676
19677    /*
19678     * This method handles package deletion in general
19679     */
19680    private boolean deletePackageLIF(String packageName, UserHandle user,
19681            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19682            PackageRemovedInfo outInfo, boolean writeSettings,
19683            PackageParser.Package replacingPackage) {
19684        if (packageName == null) {
19685            Slog.w(TAG, "Attempt to delete null packageName.");
19686            return false;
19687        }
19688
19689        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19690
19691        PackageSetting ps;
19692        synchronized (mPackages) {
19693            ps = mSettings.mPackages.get(packageName);
19694            if (ps == null) {
19695                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19696                return false;
19697            }
19698
19699            if (ps.parentPackageName != null && (!isSystemApp(ps)
19700                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19701                if (DEBUG_REMOVE) {
19702                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19703                            + ((user == null) ? UserHandle.USER_ALL : user));
19704                }
19705                final int removedUserId = (user != null) ? user.getIdentifier()
19706                        : UserHandle.USER_ALL;
19707                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19708                    return false;
19709                }
19710                markPackageUninstalledForUserLPw(ps, user);
19711                scheduleWritePackageRestrictionsLocked(user);
19712                return true;
19713            }
19714        }
19715
19716        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19717                && user.getIdentifier() != UserHandle.USER_ALL)) {
19718            // The caller is asking that the package only be deleted for a single
19719            // user.  To do this, we just mark its uninstalled state and delete
19720            // its data. If this is a system app, we only allow this to happen if
19721            // they have set the special DELETE_SYSTEM_APP which requests different
19722            // semantics than normal for uninstalling system apps.
19723            markPackageUninstalledForUserLPw(ps, user);
19724
19725            if (!isSystemApp(ps)) {
19726                // Do not uninstall the APK if an app should be cached
19727                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19728                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19729                    // Other user still have this package installed, so all
19730                    // we need to do is clear this user's data and save that
19731                    // it is uninstalled.
19732                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19733                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19734                        return false;
19735                    }
19736                    scheduleWritePackageRestrictionsLocked(user);
19737                    return true;
19738                } else {
19739                    // We need to set it back to 'installed' so the uninstall
19740                    // broadcasts will be sent correctly.
19741                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19742                    ps.setInstalled(true, user.getIdentifier());
19743                    mSettings.writeKernelMappingLPr(ps);
19744                }
19745            } else {
19746                // This is a system app, so we assume that the
19747                // other users still have this package installed, so all
19748                // we need to do is clear this user's data and save that
19749                // it is uninstalled.
19750                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19751                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19752                    return false;
19753                }
19754                scheduleWritePackageRestrictionsLocked(user);
19755                return true;
19756            }
19757        }
19758
19759        // If we are deleting a composite package for all users, keep track
19760        // of result for each child.
19761        if (ps.childPackageNames != null && outInfo != null) {
19762            synchronized (mPackages) {
19763                final int childCount = ps.childPackageNames.size();
19764                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19765                for (int i = 0; i < childCount; i++) {
19766                    String childPackageName = ps.childPackageNames.get(i);
19767                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19768                    childInfo.removedPackage = childPackageName;
19769                    childInfo.installerPackageName = ps.installerPackageName;
19770                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19771                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19772                    if (childPs != null) {
19773                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19774                    }
19775                }
19776            }
19777        }
19778
19779        boolean ret = false;
19780        if (isSystemApp(ps)) {
19781            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19782            // When an updated system application is deleted we delete the existing resources
19783            // as well and fall back to existing code in system partition
19784            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19785        } else {
19786            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19787            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19788                    outInfo, writeSettings, replacingPackage);
19789        }
19790
19791        // Take a note whether we deleted the package for all users
19792        if (outInfo != null) {
19793            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19794            if (outInfo.removedChildPackages != null) {
19795                synchronized (mPackages) {
19796                    final int childCount = outInfo.removedChildPackages.size();
19797                    for (int i = 0; i < childCount; i++) {
19798                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19799                        if (childInfo != null) {
19800                            childInfo.removedForAllUsers = mPackages.get(
19801                                    childInfo.removedPackage) == null;
19802                        }
19803                    }
19804                }
19805            }
19806            // If we uninstalled an update to a system app there may be some
19807            // child packages that appeared as they are declared in the system
19808            // app but were not declared in the update.
19809            if (isSystemApp(ps)) {
19810                synchronized (mPackages) {
19811                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19812                    final int childCount = (updatedPs.childPackageNames != null)
19813                            ? updatedPs.childPackageNames.size() : 0;
19814                    for (int i = 0; i < childCount; i++) {
19815                        String childPackageName = updatedPs.childPackageNames.get(i);
19816                        if (outInfo.removedChildPackages == null
19817                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19818                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19819                            if (childPs == null) {
19820                                continue;
19821                            }
19822                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19823                            installRes.name = childPackageName;
19824                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19825                            installRes.pkg = mPackages.get(childPackageName);
19826                            installRes.uid = childPs.pkg.applicationInfo.uid;
19827                            if (outInfo.appearedChildPackages == null) {
19828                                outInfo.appearedChildPackages = new ArrayMap<>();
19829                            }
19830                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19831                        }
19832                    }
19833                }
19834            }
19835        }
19836
19837        return ret;
19838    }
19839
19840    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19841        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19842                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19843        for (int nextUserId : userIds) {
19844            if (DEBUG_REMOVE) {
19845                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19846            }
19847            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19848                    false /*installed*/,
19849                    true /*stopped*/,
19850                    true /*notLaunched*/,
19851                    false /*hidden*/,
19852                    false /*suspended*/,
19853                    false /*instantApp*/,
19854                    null /*lastDisableAppCaller*/,
19855                    null /*enabledComponents*/,
19856                    null /*disabledComponents*/,
19857                    ps.readUserState(nextUserId).domainVerificationStatus,
19858                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19859        }
19860        mSettings.writeKernelMappingLPr(ps);
19861    }
19862
19863    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19864            PackageRemovedInfo outInfo) {
19865        final PackageParser.Package pkg;
19866        synchronized (mPackages) {
19867            pkg = mPackages.get(ps.name);
19868        }
19869
19870        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19871                : new int[] {userId};
19872        for (int nextUserId : userIds) {
19873            if (DEBUG_REMOVE) {
19874                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19875                        + nextUserId);
19876            }
19877
19878            destroyAppDataLIF(pkg, userId,
19879                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19880            destroyAppProfilesLIF(pkg, userId);
19881            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19882            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19883            schedulePackageCleaning(ps.name, nextUserId, false);
19884            synchronized (mPackages) {
19885                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19886                    scheduleWritePackageRestrictionsLocked(nextUserId);
19887                }
19888                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19889            }
19890        }
19891
19892        if (outInfo != null) {
19893            outInfo.removedPackage = ps.name;
19894            outInfo.installerPackageName = ps.installerPackageName;
19895            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19896            outInfo.removedAppId = ps.appId;
19897            outInfo.removedUsers = userIds;
19898            outInfo.broadcastUsers = userIds;
19899        }
19900
19901        return true;
19902    }
19903
19904    private final class ClearStorageConnection implements ServiceConnection {
19905        IMediaContainerService mContainerService;
19906
19907        @Override
19908        public void onServiceConnected(ComponentName name, IBinder service) {
19909            synchronized (this) {
19910                mContainerService = IMediaContainerService.Stub
19911                        .asInterface(Binder.allowBlocking(service));
19912                notifyAll();
19913            }
19914        }
19915
19916        @Override
19917        public void onServiceDisconnected(ComponentName name) {
19918        }
19919    }
19920
19921    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19922        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19923
19924        final boolean mounted;
19925        if (Environment.isExternalStorageEmulated()) {
19926            mounted = true;
19927        } else {
19928            final String status = Environment.getExternalStorageState();
19929
19930            mounted = status.equals(Environment.MEDIA_MOUNTED)
19931                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19932        }
19933
19934        if (!mounted) {
19935            return;
19936        }
19937
19938        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19939        int[] users;
19940        if (userId == UserHandle.USER_ALL) {
19941            users = sUserManager.getUserIds();
19942        } else {
19943            users = new int[] { userId };
19944        }
19945        final ClearStorageConnection conn = new ClearStorageConnection();
19946        if (mContext.bindServiceAsUser(
19947                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19948            try {
19949                for (int curUser : users) {
19950                    long timeout = SystemClock.uptimeMillis() + 5000;
19951                    synchronized (conn) {
19952                        long now;
19953                        while (conn.mContainerService == null &&
19954                                (now = SystemClock.uptimeMillis()) < timeout) {
19955                            try {
19956                                conn.wait(timeout - now);
19957                            } catch (InterruptedException e) {
19958                            }
19959                        }
19960                    }
19961                    if (conn.mContainerService == null) {
19962                        return;
19963                    }
19964
19965                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19966                    clearDirectory(conn.mContainerService,
19967                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19968                    if (allData) {
19969                        clearDirectory(conn.mContainerService,
19970                                userEnv.buildExternalStorageAppDataDirs(packageName));
19971                        clearDirectory(conn.mContainerService,
19972                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19973                    }
19974                }
19975            } finally {
19976                mContext.unbindService(conn);
19977            }
19978        }
19979    }
19980
19981    @Override
19982    public void clearApplicationProfileData(String packageName) {
19983        enforceSystemOrRoot("Only the system can clear all profile data");
19984
19985        final PackageParser.Package pkg;
19986        synchronized (mPackages) {
19987            pkg = mPackages.get(packageName);
19988        }
19989
19990        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19991            synchronized (mInstallLock) {
19992                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19993            }
19994        }
19995    }
19996
19997    @Override
19998    public void clearApplicationUserData(final String packageName,
19999            final IPackageDataObserver observer, final int userId) {
20000        mContext.enforceCallingOrSelfPermission(
20001                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20002
20003        final int callingUid = Binder.getCallingUid();
20004        enforceCrossUserPermission(callingUid, userId,
20005                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20006
20007        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20008        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20009            return;
20010        }
20011        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20012            throw new SecurityException("Cannot clear data for a protected package: "
20013                    + packageName);
20014        }
20015        // Queue up an async operation since the package deletion may take a little while.
20016        mHandler.post(new Runnable() {
20017            public void run() {
20018                mHandler.removeCallbacks(this);
20019                final boolean succeeded;
20020                try (PackageFreezer freezer = freezePackage(packageName,
20021                        "clearApplicationUserData")) {
20022                    synchronized (mInstallLock) {
20023                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20024                    }
20025                    clearExternalStorageDataSync(packageName, userId, true);
20026                    synchronized (mPackages) {
20027                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20028                                packageName, userId);
20029                    }
20030                }
20031                if (succeeded) {
20032                    // invoke DeviceStorageMonitor's update method to clear any notifications
20033                    DeviceStorageMonitorInternal dsm = LocalServices
20034                            .getService(DeviceStorageMonitorInternal.class);
20035                    if (dsm != null) {
20036                        dsm.checkMemory();
20037                    }
20038                }
20039                if(observer != null) {
20040                    try {
20041                        observer.onRemoveCompleted(packageName, succeeded);
20042                    } catch (RemoteException e) {
20043                        Log.i(TAG, "Observer no longer exists.");
20044                    }
20045                } //end if observer
20046            } //end run
20047        });
20048    }
20049
20050    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20051        if (packageName == null) {
20052            Slog.w(TAG, "Attempt to delete null packageName.");
20053            return false;
20054        }
20055
20056        // Try finding details about the requested package
20057        PackageParser.Package pkg;
20058        synchronized (mPackages) {
20059            pkg = mPackages.get(packageName);
20060            if (pkg == null) {
20061                final PackageSetting ps = mSettings.mPackages.get(packageName);
20062                if (ps != null) {
20063                    pkg = ps.pkg;
20064                }
20065            }
20066
20067            if (pkg == null) {
20068                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20069                return false;
20070            }
20071
20072            PackageSetting ps = (PackageSetting) pkg.mExtras;
20073            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20074        }
20075
20076        clearAppDataLIF(pkg, userId,
20077                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20078
20079        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20080        removeKeystoreDataIfNeeded(userId, appId);
20081
20082        UserManagerInternal umInternal = getUserManagerInternal();
20083        final int flags;
20084        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20085            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20086        } else if (umInternal.isUserRunning(userId)) {
20087            flags = StorageManager.FLAG_STORAGE_DE;
20088        } else {
20089            flags = 0;
20090        }
20091        prepareAppDataContentsLIF(pkg, userId, flags);
20092
20093        return true;
20094    }
20095
20096    /**
20097     * Reverts user permission state changes (permissions and flags) in
20098     * all packages for a given user.
20099     *
20100     * @param userId The device user for which to do a reset.
20101     */
20102    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20103        final int packageCount = mPackages.size();
20104        for (int i = 0; i < packageCount; i++) {
20105            PackageParser.Package pkg = mPackages.valueAt(i);
20106            PackageSetting ps = (PackageSetting) pkg.mExtras;
20107            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20108        }
20109    }
20110
20111    private void resetNetworkPolicies(int userId) {
20112        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20113    }
20114
20115    /**
20116     * Reverts user permission state changes (permissions and flags).
20117     *
20118     * @param ps The package for which to reset.
20119     * @param userId The device user for which to do a reset.
20120     */
20121    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20122            final PackageSetting ps, final int userId) {
20123        if (ps.pkg == null) {
20124            return;
20125        }
20126
20127        // These are flags that can change base on user actions.
20128        final int userSettableMask = FLAG_PERMISSION_USER_SET
20129                | FLAG_PERMISSION_USER_FIXED
20130                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20131                | FLAG_PERMISSION_REVIEW_REQUIRED;
20132
20133        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20134                | FLAG_PERMISSION_POLICY_FIXED;
20135
20136        boolean writeInstallPermissions = false;
20137        boolean writeRuntimePermissions = false;
20138
20139        final int permissionCount = ps.pkg.requestedPermissions.size();
20140        for (int i = 0; i < permissionCount; i++) {
20141            String permission = ps.pkg.requestedPermissions.get(i);
20142
20143            BasePermission bp = mSettings.mPermissions.get(permission);
20144            if (bp == null) {
20145                continue;
20146            }
20147
20148            // If shared user we just reset the state to which only this app contributed.
20149            if (ps.sharedUser != null) {
20150                boolean used = false;
20151                final int packageCount = ps.sharedUser.packages.size();
20152                for (int j = 0; j < packageCount; j++) {
20153                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20154                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20155                            && pkg.pkg.requestedPermissions.contains(permission)) {
20156                        used = true;
20157                        break;
20158                    }
20159                }
20160                if (used) {
20161                    continue;
20162                }
20163            }
20164
20165            PermissionsState permissionsState = ps.getPermissionsState();
20166
20167            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20168
20169            // Always clear the user settable flags.
20170            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20171                    bp.name) != null;
20172            // If permission review is enabled and this is a legacy app, mark the
20173            // permission as requiring a review as this is the initial state.
20174            int flags = 0;
20175            if (mPermissionReviewRequired
20176                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20177                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20178            }
20179            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20180                if (hasInstallState) {
20181                    writeInstallPermissions = true;
20182                } else {
20183                    writeRuntimePermissions = true;
20184                }
20185            }
20186
20187            // Below is only runtime permission handling.
20188            if (!bp.isRuntime()) {
20189                continue;
20190            }
20191
20192            // Never clobber system or policy.
20193            if ((oldFlags & policyOrSystemFlags) != 0) {
20194                continue;
20195            }
20196
20197            // If this permission was granted by default, make sure it is.
20198            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20199                if (permissionsState.grantRuntimePermission(bp, userId)
20200                        != PERMISSION_OPERATION_FAILURE) {
20201                    writeRuntimePermissions = true;
20202                }
20203            // If permission review is enabled the permissions for a legacy apps
20204            // are represented as constantly granted runtime ones, so don't revoke.
20205            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20206                // Otherwise, reset the permission.
20207                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20208                switch (revokeResult) {
20209                    case PERMISSION_OPERATION_SUCCESS:
20210                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20211                        writeRuntimePermissions = true;
20212                        final int appId = ps.appId;
20213                        mHandler.post(new Runnable() {
20214                            @Override
20215                            public void run() {
20216                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20217                            }
20218                        });
20219                    } break;
20220                }
20221            }
20222        }
20223
20224        // Synchronously write as we are taking permissions away.
20225        if (writeRuntimePermissions) {
20226            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20227        }
20228
20229        // Synchronously write as we are taking permissions away.
20230        if (writeInstallPermissions) {
20231            mSettings.writeLPr();
20232        }
20233    }
20234
20235    /**
20236     * Remove entries from the keystore daemon. Will only remove it if the
20237     * {@code appId} is valid.
20238     */
20239    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20240        if (appId < 0) {
20241            return;
20242        }
20243
20244        final KeyStore keyStore = KeyStore.getInstance();
20245        if (keyStore != null) {
20246            if (userId == UserHandle.USER_ALL) {
20247                for (final int individual : sUserManager.getUserIds()) {
20248                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20249                }
20250            } else {
20251                keyStore.clearUid(UserHandle.getUid(userId, appId));
20252            }
20253        } else {
20254            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20255        }
20256    }
20257
20258    @Override
20259    public void deleteApplicationCacheFiles(final String packageName,
20260            final IPackageDataObserver observer) {
20261        final int userId = UserHandle.getCallingUserId();
20262        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20263    }
20264
20265    @Override
20266    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20267            final IPackageDataObserver observer) {
20268        final int callingUid = Binder.getCallingUid();
20269        mContext.enforceCallingOrSelfPermission(
20270                android.Manifest.permission.DELETE_CACHE_FILES, null);
20271        enforceCrossUserPermission(callingUid, userId,
20272                /* requireFullPermission= */ true, /* checkShell= */ false,
20273                "delete application cache files");
20274        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20275                android.Manifest.permission.ACCESS_INSTANT_APPS);
20276
20277        final PackageParser.Package pkg;
20278        synchronized (mPackages) {
20279            pkg = mPackages.get(packageName);
20280        }
20281
20282        // Queue up an async operation since the package deletion may take a little while.
20283        mHandler.post(new Runnable() {
20284            public void run() {
20285                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20286                boolean doClearData = true;
20287                if (ps != null) {
20288                    final boolean targetIsInstantApp =
20289                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20290                    doClearData = !targetIsInstantApp
20291                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20292                }
20293                if (doClearData) {
20294                    synchronized (mInstallLock) {
20295                        final int flags = StorageManager.FLAG_STORAGE_DE
20296                                | StorageManager.FLAG_STORAGE_CE;
20297                        // We're only clearing cache files, so we don't care if the
20298                        // app is unfrozen and still able to run
20299                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20300                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20301                    }
20302                    clearExternalStorageDataSync(packageName, userId, false);
20303                }
20304                if (observer != null) {
20305                    try {
20306                        observer.onRemoveCompleted(packageName, true);
20307                    } catch (RemoteException e) {
20308                        Log.i(TAG, "Observer no longer exists.");
20309                    }
20310                }
20311            }
20312        });
20313    }
20314
20315    @Override
20316    public void getPackageSizeInfo(final String packageName, int userHandle,
20317            final IPackageStatsObserver observer) {
20318        throw new UnsupportedOperationException(
20319                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20320    }
20321
20322    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20323        final PackageSetting ps;
20324        synchronized (mPackages) {
20325            ps = mSettings.mPackages.get(packageName);
20326            if (ps == null) {
20327                Slog.w(TAG, "Failed to find settings for " + packageName);
20328                return false;
20329            }
20330        }
20331
20332        final String[] packageNames = { packageName };
20333        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20334        final String[] codePaths = { ps.codePathString };
20335
20336        try {
20337            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20338                    ps.appId, ceDataInodes, codePaths, stats);
20339
20340            // For now, ignore code size of packages on system partition
20341            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20342                stats.codeSize = 0;
20343            }
20344
20345            // External clients expect these to be tracked separately
20346            stats.dataSize -= stats.cacheSize;
20347
20348        } catch (InstallerException e) {
20349            Slog.w(TAG, String.valueOf(e));
20350            return false;
20351        }
20352
20353        return true;
20354    }
20355
20356    private int getUidTargetSdkVersionLockedLPr(int uid) {
20357        Object obj = mSettings.getUserIdLPr(uid);
20358        if (obj instanceof SharedUserSetting) {
20359            final SharedUserSetting sus = (SharedUserSetting) obj;
20360            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20361            final Iterator<PackageSetting> it = sus.packages.iterator();
20362            while (it.hasNext()) {
20363                final PackageSetting ps = it.next();
20364                if (ps.pkg != null) {
20365                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20366                    if (v < vers) vers = v;
20367                }
20368            }
20369            return vers;
20370        } else if (obj instanceof PackageSetting) {
20371            final PackageSetting ps = (PackageSetting) obj;
20372            if (ps.pkg != null) {
20373                return ps.pkg.applicationInfo.targetSdkVersion;
20374            }
20375        }
20376        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20377    }
20378
20379    @Override
20380    public void addPreferredActivity(IntentFilter filter, int match,
20381            ComponentName[] set, ComponentName activity, int userId) {
20382        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20383                "Adding preferred");
20384    }
20385
20386    private void addPreferredActivityInternal(IntentFilter filter, int match,
20387            ComponentName[] set, ComponentName activity, boolean always, int userId,
20388            String opname) {
20389        // writer
20390        int callingUid = Binder.getCallingUid();
20391        enforceCrossUserPermission(callingUid, userId,
20392                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20393        if (filter.countActions() == 0) {
20394            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20395            return;
20396        }
20397        synchronized (mPackages) {
20398            if (mContext.checkCallingOrSelfPermission(
20399                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20400                    != PackageManager.PERMISSION_GRANTED) {
20401                if (getUidTargetSdkVersionLockedLPr(callingUid)
20402                        < Build.VERSION_CODES.FROYO) {
20403                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20404                            + callingUid);
20405                    return;
20406                }
20407                mContext.enforceCallingOrSelfPermission(
20408                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20409            }
20410
20411            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20412            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20413                    + userId + ":");
20414            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20415            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20416            scheduleWritePackageRestrictionsLocked(userId);
20417            postPreferredActivityChangedBroadcast(userId);
20418        }
20419    }
20420
20421    private void postPreferredActivityChangedBroadcast(int userId) {
20422        mHandler.post(() -> {
20423            final IActivityManager am = ActivityManager.getService();
20424            if (am == null) {
20425                return;
20426            }
20427
20428            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20429            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20430            try {
20431                am.broadcastIntent(null, intent, null, null,
20432                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20433                        null, false, false, userId);
20434            } catch (RemoteException e) {
20435            }
20436        });
20437    }
20438
20439    @Override
20440    public void replacePreferredActivity(IntentFilter filter, int match,
20441            ComponentName[] set, ComponentName activity, int userId) {
20442        if (filter.countActions() != 1) {
20443            throw new IllegalArgumentException(
20444                    "replacePreferredActivity expects filter to have only 1 action.");
20445        }
20446        if (filter.countDataAuthorities() != 0
20447                || filter.countDataPaths() != 0
20448                || filter.countDataSchemes() > 1
20449                || filter.countDataTypes() != 0) {
20450            throw new IllegalArgumentException(
20451                    "replacePreferredActivity expects filter to have no data authorities, " +
20452                    "paths, or types; and at most one scheme.");
20453        }
20454
20455        final int callingUid = Binder.getCallingUid();
20456        enforceCrossUserPermission(callingUid, userId,
20457                true /* requireFullPermission */, false /* checkShell */,
20458                "replace preferred activity");
20459        synchronized (mPackages) {
20460            if (mContext.checkCallingOrSelfPermission(
20461                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20462                    != PackageManager.PERMISSION_GRANTED) {
20463                if (getUidTargetSdkVersionLockedLPr(callingUid)
20464                        < Build.VERSION_CODES.FROYO) {
20465                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20466                            + Binder.getCallingUid());
20467                    return;
20468                }
20469                mContext.enforceCallingOrSelfPermission(
20470                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20471            }
20472
20473            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20474            if (pir != null) {
20475                // Get all of the existing entries that exactly match this filter.
20476                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20477                if (existing != null && existing.size() == 1) {
20478                    PreferredActivity cur = existing.get(0);
20479                    if (DEBUG_PREFERRED) {
20480                        Slog.i(TAG, "Checking replace of preferred:");
20481                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20482                        if (!cur.mPref.mAlways) {
20483                            Slog.i(TAG, "  -- CUR; not mAlways!");
20484                        } else {
20485                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20486                            Slog.i(TAG, "  -- CUR: mSet="
20487                                    + Arrays.toString(cur.mPref.mSetComponents));
20488                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20489                            Slog.i(TAG, "  -- NEW: mMatch="
20490                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20491                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20492                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20493                        }
20494                    }
20495                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20496                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20497                            && cur.mPref.sameSet(set)) {
20498                        // Setting the preferred activity to what it happens to be already
20499                        if (DEBUG_PREFERRED) {
20500                            Slog.i(TAG, "Replacing with same preferred activity "
20501                                    + cur.mPref.mShortComponent + " for user "
20502                                    + userId + ":");
20503                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20504                        }
20505                        return;
20506                    }
20507                }
20508
20509                if (existing != null) {
20510                    if (DEBUG_PREFERRED) {
20511                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20512                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20513                    }
20514                    for (int i = 0; i < existing.size(); i++) {
20515                        PreferredActivity pa = existing.get(i);
20516                        if (DEBUG_PREFERRED) {
20517                            Slog.i(TAG, "Removing existing preferred activity "
20518                                    + pa.mPref.mComponent + ":");
20519                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20520                        }
20521                        pir.removeFilter(pa);
20522                    }
20523                }
20524            }
20525            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20526                    "Replacing preferred");
20527        }
20528    }
20529
20530    @Override
20531    public void clearPackagePreferredActivities(String packageName) {
20532        final int callingUid = Binder.getCallingUid();
20533        if (getInstantAppPackageName(callingUid) != null) {
20534            return;
20535        }
20536        // writer
20537        synchronized (mPackages) {
20538            PackageParser.Package pkg = mPackages.get(packageName);
20539            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20540                if (mContext.checkCallingOrSelfPermission(
20541                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20542                        != PackageManager.PERMISSION_GRANTED) {
20543                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20544                            < Build.VERSION_CODES.FROYO) {
20545                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20546                                + callingUid);
20547                        return;
20548                    }
20549                    mContext.enforceCallingOrSelfPermission(
20550                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20551                }
20552            }
20553            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20554            if (ps != null
20555                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20556                return;
20557            }
20558            int user = UserHandle.getCallingUserId();
20559            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20560                scheduleWritePackageRestrictionsLocked(user);
20561            }
20562        }
20563    }
20564
20565    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20566    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20567        ArrayList<PreferredActivity> removed = null;
20568        boolean changed = false;
20569        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20570            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20571            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20572            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20573                continue;
20574            }
20575            Iterator<PreferredActivity> it = pir.filterIterator();
20576            while (it.hasNext()) {
20577                PreferredActivity pa = it.next();
20578                // Mark entry for removal only if it matches the package name
20579                // and the entry is of type "always".
20580                if (packageName == null ||
20581                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20582                                && pa.mPref.mAlways)) {
20583                    if (removed == null) {
20584                        removed = new ArrayList<PreferredActivity>();
20585                    }
20586                    removed.add(pa);
20587                }
20588            }
20589            if (removed != null) {
20590                for (int j=0; j<removed.size(); j++) {
20591                    PreferredActivity pa = removed.get(j);
20592                    pir.removeFilter(pa);
20593                }
20594                changed = true;
20595            }
20596        }
20597        if (changed) {
20598            postPreferredActivityChangedBroadcast(userId);
20599        }
20600        return changed;
20601    }
20602
20603    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20604    private void clearIntentFilterVerificationsLPw(int userId) {
20605        final int packageCount = mPackages.size();
20606        for (int i = 0; i < packageCount; i++) {
20607            PackageParser.Package pkg = mPackages.valueAt(i);
20608            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20609        }
20610    }
20611
20612    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20613    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20614        if (userId == UserHandle.USER_ALL) {
20615            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20616                    sUserManager.getUserIds())) {
20617                for (int oneUserId : sUserManager.getUserIds()) {
20618                    scheduleWritePackageRestrictionsLocked(oneUserId);
20619                }
20620            }
20621        } else {
20622            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20623                scheduleWritePackageRestrictionsLocked(userId);
20624            }
20625        }
20626    }
20627
20628    /** Clears state for all users, and touches intent filter verification policy */
20629    void clearDefaultBrowserIfNeeded(String packageName) {
20630        for (int oneUserId : sUserManager.getUserIds()) {
20631            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20632        }
20633    }
20634
20635    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20636        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20637        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20638            if (packageName.equals(defaultBrowserPackageName)) {
20639                setDefaultBrowserPackageName(null, userId);
20640            }
20641        }
20642    }
20643
20644    @Override
20645    public void resetApplicationPreferences(int userId) {
20646        mContext.enforceCallingOrSelfPermission(
20647                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20648        final long identity = Binder.clearCallingIdentity();
20649        // writer
20650        try {
20651            synchronized (mPackages) {
20652                clearPackagePreferredActivitiesLPw(null, userId);
20653                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20654                // TODO: We have to reset the default SMS and Phone. This requires
20655                // significant refactoring to keep all default apps in the package
20656                // manager (cleaner but more work) or have the services provide
20657                // callbacks to the package manager to request a default app reset.
20658                applyFactoryDefaultBrowserLPw(userId);
20659                clearIntentFilterVerificationsLPw(userId);
20660                primeDomainVerificationsLPw(userId);
20661                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20662                scheduleWritePackageRestrictionsLocked(userId);
20663            }
20664            resetNetworkPolicies(userId);
20665        } finally {
20666            Binder.restoreCallingIdentity(identity);
20667        }
20668    }
20669
20670    @Override
20671    public int getPreferredActivities(List<IntentFilter> outFilters,
20672            List<ComponentName> outActivities, String packageName) {
20673        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20674            return 0;
20675        }
20676        int num = 0;
20677        final int userId = UserHandle.getCallingUserId();
20678        // reader
20679        synchronized (mPackages) {
20680            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20681            if (pir != null) {
20682                final Iterator<PreferredActivity> it = pir.filterIterator();
20683                while (it.hasNext()) {
20684                    final PreferredActivity pa = it.next();
20685                    if (packageName == null
20686                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20687                                    && pa.mPref.mAlways)) {
20688                        if (outFilters != null) {
20689                            outFilters.add(new IntentFilter(pa));
20690                        }
20691                        if (outActivities != null) {
20692                            outActivities.add(pa.mPref.mComponent);
20693                        }
20694                    }
20695                }
20696            }
20697        }
20698
20699        return num;
20700    }
20701
20702    @Override
20703    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20704            int userId) {
20705        int callingUid = Binder.getCallingUid();
20706        if (callingUid != Process.SYSTEM_UID) {
20707            throw new SecurityException(
20708                    "addPersistentPreferredActivity can only be run by the system");
20709        }
20710        if (filter.countActions() == 0) {
20711            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20712            return;
20713        }
20714        synchronized (mPackages) {
20715            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20716                    ":");
20717            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20718            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20719                    new PersistentPreferredActivity(filter, activity));
20720            scheduleWritePackageRestrictionsLocked(userId);
20721            postPreferredActivityChangedBroadcast(userId);
20722        }
20723    }
20724
20725    @Override
20726    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20727        int callingUid = Binder.getCallingUid();
20728        if (callingUid != Process.SYSTEM_UID) {
20729            throw new SecurityException(
20730                    "clearPackagePersistentPreferredActivities can only be run by the system");
20731        }
20732        ArrayList<PersistentPreferredActivity> removed = null;
20733        boolean changed = false;
20734        synchronized (mPackages) {
20735            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20736                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20737                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20738                        .valueAt(i);
20739                if (userId != thisUserId) {
20740                    continue;
20741                }
20742                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20743                while (it.hasNext()) {
20744                    PersistentPreferredActivity ppa = it.next();
20745                    // Mark entry for removal only if it matches the package name.
20746                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20747                        if (removed == null) {
20748                            removed = new ArrayList<PersistentPreferredActivity>();
20749                        }
20750                        removed.add(ppa);
20751                    }
20752                }
20753                if (removed != null) {
20754                    for (int j=0; j<removed.size(); j++) {
20755                        PersistentPreferredActivity ppa = removed.get(j);
20756                        ppir.removeFilter(ppa);
20757                    }
20758                    changed = true;
20759                }
20760            }
20761
20762            if (changed) {
20763                scheduleWritePackageRestrictionsLocked(userId);
20764                postPreferredActivityChangedBroadcast(userId);
20765            }
20766        }
20767    }
20768
20769    /**
20770     * Common machinery for picking apart a restored XML blob and passing
20771     * it to a caller-supplied functor to be applied to the running system.
20772     */
20773    private void restoreFromXml(XmlPullParser parser, int userId,
20774            String expectedStartTag, BlobXmlRestorer functor)
20775            throws IOException, XmlPullParserException {
20776        int type;
20777        while ((type = parser.next()) != XmlPullParser.START_TAG
20778                && type != XmlPullParser.END_DOCUMENT) {
20779        }
20780        if (type != XmlPullParser.START_TAG) {
20781            // oops didn't find a start tag?!
20782            if (DEBUG_BACKUP) {
20783                Slog.e(TAG, "Didn't find start tag during restore");
20784            }
20785            return;
20786        }
20787Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20788        // this is supposed to be TAG_PREFERRED_BACKUP
20789        if (!expectedStartTag.equals(parser.getName())) {
20790            if (DEBUG_BACKUP) {
20791                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20792            }
20793            return;
20794        }
20795
20796        // skip interfering stuff, then we're aligned with the backing implementation
20797        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20798Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20799        functor.apply(parser, userId);
20800    }
20801
20802    private interface BlobXmlRestorer {
20803        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20804    }
20805
20806    /**
20807     * Non-Binder method, support for the backup/restore mechanism: write the
20808     * full set of preferred activities in its canonical XML format.  Returns the
20809     * XML output as a byte array, or null if there is none.
20810     */
20811    @Override
20812    public byte[] getPreferredActivityBackup(int userId) {
20813        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20814            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20815        }
20816
20817        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20818        try {
20819            final XmlSerializer serializer = new FastXmlSerializer();
20820            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20821            serializer.startDocument(null, true);
20822            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20823
20824            synchronized (mPackages) {
20825                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20826            }
20827
20828            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20829            serializer.endDocument();
20830            serializer.flush();
20831        } catch (Exception e) {
20832            if (DEBUG_BACKUP) {
20833                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20834            }
20835            return null;
20836        }
20837
20838        return dataStream.toByteArray();
20839    }
20840
20841    @Override
20842    public void restorePreferredActivities(byte[] backup, int userId) {
20843        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20844            throw new SecurityException("Only the system may call restorePreferredActivities()");
20845        }
20846
20847        try {
20848            final XmlPullParser parser = Xml.newPullParser();
20849            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20850            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20851                    new BlobXmlRestorer() {
20852                        @Override
20853                        public void apply(XmlPullParser parser, int userId)
20854                                throws XmlPullParserException, IOException {
20855                            synchronized (mPackages) {
20856                                mSettings.readPreferredActivitiesLPw(parser, userId);
20857                            }
20858                        }
20859                    } );
20860        } catch (Exception e) {
20861            if (DEBUG_BACKUP) {
20862                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20863            }
20864        }
20865    }
20866
20867    /**
20868     * Non-Binder method, support for the backup/restore mechanism: write the
20869     * default browser (etc) settings in its canonical XML format.  Returns the default
20870     * browser XML representation as a byte array, or null if there is none.
20871     */
20872    @Override
20873    public byte[] getDefaultAppsBackup(int userId) {
20874        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20875            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20876        }
20877
20878        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20879        try {
20880            final XmlSerializer serializer = new FastXmlSerializer();
20881            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20882            serializer.startDocument(null, true);
20883            serializer.startTag(null, TAG_DEFAULT_APPS);
20884
20885            synchronized (mPackages) {
20886                mSettings.writeDefaultAppsLPr(serializer, userId);
20887            }
20888
20889            serializer.endTag(null, TAG_DEFAULT_APPS);
20890            serializer.endDocument();
20891            serializer.flush();
20892        } catch (Exception e) {
20893            if (DEBUG_BACKUP) {
20894                Slog.e(TAG, "Unable to write default apps for backup", e);
20895            }
20896            return null;
20897        }
20898
20899        return dataStream.toByteArray();
20900    }
20901
20902    @Override
20903    public void restoreDefaultApps(byte[] backup, int userId) {
20904        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20905            throw new SecurityException("Only the system may call restoreDefaultApps()");
20906        }
20907
20908        try {
20909            final XmlPullParser parser = Xml.newPullParser();
20910            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20911            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20912                    new BlobXmlRestorer() {
20913                        @Override
20914                        public void apply(XmlPullParser parser, int userId)
20915                                throws XmlPullParserException, IOException {
20916                            synchronized (mPackages) {
20917                                mSettings.readDefaultAppsLPw(parser, userId);
20918                            }
20919                        }
20920                    } );
20921        } catch (Exception e) {
20922            if (DEBUG_BACKUP) {
20923                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20924            }
20925        }
20926    }
20927
20928    @Override
20929    public byte[] getIntentFilterVerificationBackup(int userId) {
20930        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20931            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20932        }
20933
20934        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20935        try {
20936            final XmlSerializer serializer = new FastXmlSerializer();
20937            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20938            serializer.startDocument(null, true);
20939            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20940
20941            synchronized (mPackages) {
20942                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20943            }
20944
20945            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20946            serializer.endDocument();
20947            serializer.flush();
20948        } catch (Exception e) {
20949            if (DEBUG_BACKUP) {
20950                Slog.e(TAG, "Unable to write default apps for backup", e);
20951            }
20952            return null;
20953        }
20954
20955        return dataStream.toByteArray();
20956    }
20957
20958    @Override
20959    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20960        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20961            throw new SecurityException("Only the system may call restorePreferredActivities()");
20962        }
20963
20964        try {
20965            final XmlPullParser parser = Xml.newPullParser();
20966            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20967            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20968                    new BlobXmlRestorer() {
20969                        @Override
20970                        public void apply(XmlPullParser parser, int userId)
20971                                throws XmlPullParserException, IOException {
20972                            synchronized (mPackages) {
20973                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20974                                mSettings.writeLPr();
20975                            }
20976                        }
20977                    } );
20978        } catch (Exception e) {
20979            if (DEBUG_BACKUP) {
20980                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20981            }
20982        }
20983    }
20984
20985    @Override
20986    public byte[] getPermissionGrantBackup(int userId) {
20987        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20988            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20989        }
20990
20991        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20992        try {
20993            final XmlSerializer serializer = new FastXmlSerializer();
20994            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20995            serializer.startDocument(null, true);
20996            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20997
20998            synchronized (mPackages) {
20999                serializeRuntimePermissionGrantsLPr(serializer, userId);
21000            }
21001
21002            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21003            serializer.endDocument();
21004            serializer.flush();
21005        } catch (Exception e) {
21006            if (DEBUG_BACKUP) {
21007                Slog.e(TAG, "Unable to write default apps for backup", e);
21008            }
21009            return null;
21010        }
21011
21012        return dataStream.toByteArray();
21013    }
21014
21015    @Override
21016    public void restorePermissionGrants(byte[] backup, int userId) {
21017        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21018            throw new SecurityException("Only the system may call restorePermissionGrants()");
21019        }
21020
21021        try {
21022            final XmlPullParser parser = Xml.newPullParser();
21023            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21024            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21025                    new BlobXmlRestorer() {
21026                        @Override
21027                        public void apply(XmlPullParser parser, int userId)
21028                                throws XmlPullParserException, IOException {
21029                            synchronized (mPackages) {
21030                                processRestoredPermissionGrantsLPr(parser, userId);
21031                            }
21032                        }
21033                    } );
21034        } catch (Exception e) {
21035            if (DEBUG_BACKUP) {
21036                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21037            }
21038        }
21039    }
21040
21041    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21042            throws IOException {
21043        serializer.startTag(null, TAG_ALL_GRANTS);
21044
21045        final int N = mSettings.mPackages.size();
21046        for (int i = 0; i < N; i++) {
21047            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21048            boolean pkgGrantsKnown = false;
21049
21050            PermissionsState packagePerms = ps.getPermissionsState();
21051
21052            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21053                final int grantFlags = state.getFlags();
21054                // only look at grants that are not system/policy fixed
21055                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21056                    final boolean isGranted = state.isGranted();
21057                    // And only back up the user-twiddled state bits
21058                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21059                        final String packageName = mSettings.mPackages.keyAt(i);
21060                        if (!pkgGrantsKnown) {
21061                            serializer.startTag(null, TAG_GRANT);
21062                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21063                            pkgGrantsKnown = true;
21064                        }
21065
21066                        final boolean userSet =
21067                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21068                        final boolean userFixed =
21069                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21070                        final boolean revoke =
21071                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21072
21073                        serializer.startTag(null, TAG_PERMISSION);
21074                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21075                        if (isGranted) {
21076                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21077                        }
21078                        if (userSet) {
21079                            serializer.attribute(null, ATTR_USER_SET, "true");
21080                        }
21081                        if (userFixed) {
21082                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21083                        }
21084                        if (revoke) {
21085                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21086                        }
21087                        serializer.endTag(null, TAG_PERMISSION);
21088                    }
21089                }
21090            }
21091
21092            if (pkgGrantsKnown) {
21093                serializer.endTag(null, TAG_GRANT);
21094            }
21095        }
21096
21097        serializer.endTag(null, TAG_ALL_GRANTS);
21098    }
21099
21100    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21101            throws XmlPullParserException, IOException {
21102        String pkgName = null;
21103        int outerDepth = parser.getDepth();
21104        int type;
21105        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21106                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21107            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21108                continue;
21109            }
21110
21111            final String tagName = parser.getName();
21112            if (tagName.equals(TAG_GRANT)) {
21113                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21114                if (DEBUG_BACKUP) {
21115                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21116                }
21117            } else if (tagName.equals(TAG_PERMISSION)) {
21118
21119                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21120                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21121
21122                int newFlagSet = 0;
21123                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21124                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21125                }
21126                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21127                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21128                }
21129                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21130                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21131                }
21132                if (DEBUG_BACKUP) {
21133                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21134                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21135                }
21136                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21137                if (ps != null) {
21138                    // Already installed so we apply the grant immediately
21139                    if (DEBUG_BACKUP) {
21140                        Slog.v(TAG, "        + already installed; applying");
21141                    }
21142                    PermissionsState perms = ps.getPermissionsState();
21143                    BasePermission bp = mSettings.mPermissions.get(permName);
21144                    if (bp != null) {
21145                        if (isGranted) {
21146                            perms.grantRuntimePermission(bp, userId);
21147                        }
21148                        if (newFlagSet != 0) {
21149                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21150                        }
21151                    }
21152                } else {
21153                    // Need to wait for post-restore install to apply the grant
21154                    if (DEBUG_BACKUP) {
21155                        Slog.v(TAG, "        - not yet installed; saving for later");
21156                    }
21157                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21158                            isGranted, newFlagSet, userId);
21159                }
21160            } else {
21161                PackageManagerService.reportSettingsProblem(Log.WARN,
21162                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21163                XmlUtils.skipCurrentTag(parser);
21164            }
21165        }
21166
21167        scheduleWriteSettingsLocked();
21168        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21169    }
21170
21171    @Override
21172    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21173            int sourceUserId, int targetUserId, int flags) {
21174        mContext.enforceCallingOrSelfPermission(
21175                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21176        int callingUid = Binder.getCallingUid();
21177        enforceOwnerRights(ownerPackage, callingUid);
21178        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21179        if (intentFilter.countActions() == 0) {
21180            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21181            return;
21182        }
21183        synchronized (mPackages) {
21184            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21185                    ownerPackage, targetUserId, flags);
21186            CrossProfileIntentResolver resolver =
21187                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21188            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21189            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21190            if (existing != null) {
21191                int size = existing.size();
21192                for (int i = 0; i < size; i++) {
21193                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21194                        return;
21195                    }
21196                }
21197            }
21198            resolver.addFilter(newFilter);
21199            scheduleWritePackageRestrictionsLocked(sourceUserId);
21200        }
21201    }
21202
21203    @Override
21204    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21205        mContext.enforceCallingOrSelfPermission(
21206                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21207        final int callingUid = Binder.getCallingUid();
21208        enforceOwnerRights(ownerPackage, callingUid);
21209        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21210        synchronized (mPackages) {
21211            CrossProfileIntentResolver resolver =
21212                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21213            ArraySet<CrossProfileIntentFilter> set =
21214                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21215            for (CrossProfileIntentFilter filter : set) {
21216                if (filter.getOwnerPackage().equals(ownerPackage)) {
21217                    resolver.removeFilter(filter);
21218                }
21219            }
21220            scheduleWritePackageRestrictionsLocked(sourceUserId);
21221        }
21222    }
21223
21224    // Enforcing that callingUid is owning pkg on userId
21225    private void enforceOwnerRights(String pkg, int callingUid) {
21226        // The system owns everything.
21227        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21228            return;
21229        }
21230        final int callingUserId = UserHandle.getUserId(callingUid);
21231        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21232        if (pi == null) {
21233            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21234                    + callingUserId);
21235        }
21236        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21237            throw new SecurityException("Calling uid " + callingUid
21238                    + " does not own package " + pkg);
21239        }
21240    }
21241
21242    @Override
21243    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21244        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21245            return null;
21246        }
21247        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21248    }
21249
21250    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21251        UserManagerService ums = UserManagerService.getInstance();
21252        if (ums != null) {
21253            final UserInfo parent = ums.getProfileParent(userId);
21254            final int launcherUid = (parent != null) ? parent.id : userId;
21255            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21256            if (launcherComponent != null) {
21257                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21258                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21259                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21260                        .setPackage(launcherComponent.getPackageName());
21261                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21262            }
21263        }
21264    }
21265
21266    /**
21267     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21268     * then reports the most likely home activity or null if there are more than one.
21269     */
21270    private ComponentName getDefaultHomeActivity(int userId) {
21271        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21272        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21273        if (cn != null) {
21274            return cn;
21275        }
21276
21277        // Find the launcher with the highest priority and return that component if there are no
21278        // other home activity with the same priority.
21279        int lastPriority = Integer.MIN_VALUE;
21280        ComponentName lastComponent = null;
21281        final int size = allHomeCandidates.size();
21282        for (int i = 0; i < size; i++) {
21283            final ResolveInfo ri = allHomeCandidates.get(i);
21284            if (ri.priority > lastPriority) {
21285                lastComponent = ri.activityInfo.getComponentName();
21286                lastPriority = ri.priority;
21287            } else if (ri.priority == lastPriority) {
21288                // Two components found with same priority.
21289                lastComponent = null;
21290            }
21291        }
21292        return lastComponent;
21293    }
21294
21295    private Intent getHomeIntent() {
21296        Intent intent = new Intent(Intent.ACTION_MAIN);
21297        intent.addCategory(Intent.CATEGORY_HOME);
21298        intent.addCategory(Intent.CATEGORY_DEFAULT);
21299        return intent;
21300    }
21301
21302    private IntentFilter getHomeFilter() {
21303        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21304        filter.addCategory(Intent.CATEGORY_HOME);
21305        filter.addCategory(Intent.CATEGORY_DEFAULT);
21306        return filter;
21307    }
21308
21309    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21310            int userId) {
21311        Intent intent  = getHomeIntent();
21312        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21313                PackageManager.GET_META_DATA, userId);
21314        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21315                true, false, false, userId);
21316
21317        allHomeCandidates.clear();
21318        if (list != null) {
21319            for (ResolveInfo ri : list) {
21320                allHomeCandidates.add(ri);
21321            }
21322        }
21323        return (preferred == null || preferred.activityInfo == null)
21324                ? null
21325                : new ComponentName(preferred.activityInfo.packageName,
21326                        preferred.activityInfo.name);
21327    }
21328
21329    @Override
21330    public void setHomeActivity(ComponentName comp, int userId) {
21331        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21332            return;
21333        }
21334        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21335        getHomeActivitiesAsUser(homeActivities, userId);
21336
21337        boolean found = false;
21338
21339        final int size = homeActivities.size();
21340        final ComponentName[] set = new ComponentName[size];
21341        for (int i = 0; i < size; i++) {
21342            final ResolveInfo candidate = homeActivities.get(i);
21343            final ActivityInfo info = candidate.activityInfo;
21344            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21345            set[i] = activityName;
21346            if (!found && activityName.equals(comp)) {
21347                found = true;
21348            }
21349        }
21350        if (!found) {
21351            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21352                    + userId);
21353        }
21354        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21355                set, comp, userId);
21356    }
21357
21358    private @Nullable String getSetupWizardPackageName() {
21359        final Intent intent = new Intent(Intent.ACTION_MAIN);
21360        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21361
21362        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21363                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21364                        | MATCH_DISABLED_COMPONENTS,
21365                UserHandle.myUserId());
21366        if (matches.size() == 1) {
21367            return matches.get(0).getComponentInfo().packageName;
21368        } else {
21369            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21370                    + ": matches=" + matches);
21371            return null;
21372        }
21373    }
21374
21375    private @Nullable String getStorageManagerPackageName() {
21376        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21377
21378        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21379                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21380                        | MATCH_DISABLED_COMPONENTS,
21381                UserHandle.myUserId());
21382        if (matches.size() == 1) {
21383            return matches.get(0).getComponentInfo().packageName;
21384        } else {
21385            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21386                    + matches.size() + ": matches=" + matches);
21387            return null;
21388        }
21389    }
21390
21391    @Override
21392    public void setApplicationEnabledSetting(String appPackageName,
21393            int newState, int flags, int userId, String callingPackage) {
21394        if (!sUserManager.exists(userId)) return;
21395        if (callingPackage == null) {
21396            callingPackage = Integer.toString(Binder.getCallingUid());
21397        }
21398        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21399    }
21400
21401    @Override
21402    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21403        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21404        synchronized (mPackages) {
21405            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21406            if (pkgSetting != null) {
21407                pkgSetting.setUpdateAvailable(updateAvailable);
21408            }
21409        }
21410    }
21411
21412    @Override
21413    public void setComponentEnabledSetting(ComponentName componentName,
21414            int newState, int flags, int userId) {
21415        if (!sUserManager.exists(userId)) return;
21416        setEnabledSetting(componentName.getPackageName(),
21417                componentName.getClassName(), newState, flags, userId, null);
21418    }
21419
21420    private void setEnabledSetting(final String packageName, String className, int newState,
21421            final int flags, int userId, String callingPackage) {
21422        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21423              || newState == COMPONENT_ENABLED_STATE_ENABLED
21424              || newState == COMPONENT_ENABLED_STATE_DISABLED
21425              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21426              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21427            throw new IllegalArgumentException("Invalid new component state: "
21428                    + newState);
21429        }
21430        PackageSetting pkgSetting;
21431        final int callingUid = Binder.getCallingUid();
21432        final int permission;
21433        if (callingUid == Process.SYSTEM_UID) {
21434            permission = PackageManager.PERMISSION_GRANTED;
21435        } else {
21436            permission = mContext.checkCallingOrSelfPermission(
21437                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21438        }
21439        enforceCrossUserPermission(callingUid, userId,
21440                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21441        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21442        boolean sendNow = false;
21443        boolean isApp = (className == null);
21444        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21445        String componentName = isApp ? packageName : className;
21446        int packageUid = -1;
21447        ArrayList<String> components;
21448
21449        // reader
21450        synchronized (mPackages) {
21451            pkgSetting = mSettings.mPackages.get(packageName);
21452            if (pkgSetting == null) {
21453                if (!isCallerInstantApp) {
21454                    if (className == null) {
21455                        throw new IllegalArgumentException("Unknown package: " + packageName);
21456                    }
21457                    throw new IllegalArgumentException(
21458                            "Unknown component: " + packageName + "/" + className);
21459                } else {
21460                    // throw SecurityException to prevent leaking package information
21461                    throw new SecurityException(
21462                            "Attempt to change component state; "
21463                            + "pid=" + Binder.getCallingPid()
21464                            + ", uid=" + callingUid
21465                            + (className == null
21466                                    ? ", package=" + packageName
21467                                    : ", component=" + packageName + "/" + className));
21468                }
21469            }
21470        }
21471
21472        // Limit who can change which apps
21473        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21474            // Don't allow apps that don't have permission to modify other apps
21475            if (!allowedByPermission
21476                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21477                throw new SecurityException(
21478                        "Attempt to change component state; "
21479                        + "pid=" + Binder.getCallingPid()
21480                        + ", uid=" + callingUid
21481                        + (className == null
21482                                ? ", package=" + packageName
21483                                : ", component=" + packageName + "/" + className));
21484            }
21485            // Don't allow changing protected packages.
21486            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21487                throw new SecurityException("Cannot disable a protected package: " + packageName);
21488            }
21489        }
21490
21491        synchronized (mPackages) {
21492            if (callingUid == Process.SHELL_UID
21493                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21494                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21495                // unless it is a test package.
21496                int oldState = pkgSetting.getEnabled(userId);
21497                if (className == null
21498                    &&
21499                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21500                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21501                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21502                    &&
21503                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21504                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21505                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21506                    // ok
21507                } else {
21508                    throw new SecurityException(
21509                            "Shell cannot change component state for " + packageName + "/"
21510                            + className + " to " + newState);
21511                }
21512            }
21513            if (className == null) {
21514                // We're dealing with an application/package level state change
21515                if (pkgSetting.getEnabled(userId) == newState) {
21516                    // Nothing to do
21517                    return;
21518                }
21519                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21520                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21521                    // Don't care about who enables an app.
21522                    callingPackage = null;
21523                }
21524                pkgSetting.setEnabled(newState, userId, callingPackage);
21525                // pkgSetting.pkg.mSetEnabled = newState;
21526            } else {
21527                // We're dealing with a component level state change
21528                // First, verify that this is a valid class name.
21529                PackageParser.Package pkg = pkgSetting.pkg;
21530                if (pkg == null || !pkg.hasComponentClassName(className)) {
21531                    if (pkg != null &&
21532                            pkg.applicationInfo.targetSdkVersion >=
21533                                    Build.VERSION_CODES.JELLY_BEAN) {
21534                        throw new IllegalArgumentException("Component class " + className
21535                                + " does not exist in " + packageName);
21536                    } else {
21537                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21538                                + className + " does not exist in " + packageName);
21539                    }
21540                }
21541                switch (newState) {
21542                case COMPONENT_ENABLED_STATE_ENABLED:
21543                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21544                        return;
21545                    }
21546                    break;
21547                case COMPONENT_ENABLED_STATE_DISABLED:
21548                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21549                        return;
21550                    }
21551                    break;
21552                case COMPONENT_ENABLED_STATE_DEFAULT:
21553                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21554                        return;
21555                    }
21556                    break;
21557                default:
21558                    Slog.e(TAG, "Invalid new component state: " + newState);
21559                    return;
21560                }
21561            }
21562            scheduleWritePackageRestrictionsLocked(userId);
21563            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21564            final long callingId = Binder.clearCallingIdentity();
21565            try {
21566                updateInstantAppInstallerLocked(packageName);
21567            } finally {
21568                Binder.restoreCallingIdentity(callingId);
21569            }
21570            components = mPendingBroadcasts.get(userId, packageName);
21571            final boolean newPackage = components == null;
21572            if (newPackage) {
21573                components = new ArrayList<String>();
21574            }
21575            if (!components.contains(componentName)) {
21576                components.add(componentName);
21577            }
21578            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21579                sendNow = true;
21580                // Purge entry from pending broadcast list if another one exists already
21581                // since we are sending one right away.
21582                mPendingBroadcasts.remove(userId, packageName);
21583            } else {
21584                if (newPackage) {
21585                    mPendingBroadcasts.put(userId, packageName, components);
21586                }
21587                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21588                    // Schedule a message
21589                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21590                }
21591            }
21592        }
21593
21594        long callingId = Binder.clearCallingIdentity();
21595        try {
21596            if (sendNow) {
21597                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21598                sendPackageChangedBroadcast(packageName,
21599                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21600            }
21601        } finally {
21602            Binder.restoreCallingIdentity(callingId);
21603        }
21604    }
21605
21606    @Override
21607    public void flushPackageRestrictionsAsUser(int userId) {
21608        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21609            return;
21610        }
21611        if (!sUserManager.exists(userId)) {
21612            return;
21613        }
21614        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21615                false /* checkShell */, "flushPackageRestrictions");
21616        synchronized (mPackages) {
21617            mSettings.writePackageRestrictionsLPr(userId);
21618            mDirtyUsers.remove(userId);
21619            if (mDirtyUsers.isEmpty()) {
21620                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21621            }
21622        }
21623    }
21624
21625    private void sendPackageChangedBroadcast(String packageName,
21626            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21627        if (DEBUG_INSTALL)
21628            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21629                    + componentNames);
21630        Bundle extras = new Bundle(4);
21631        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21632        String nameList[] = new String[componentNames.size()];
21633        componentNames.toArray(nameList);
21634        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21635        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21636        extras.putInt(Intent.EXTRA_UID, packageUid);
21637        // If this is not reporting a change of the overall package, then only send it
21638        // to registered receivers.  We don't want to launch a swath of apps for every
21639        // little component state change.
21640        final int flags = !componentNames.contains(packageName)
21641                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21642        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21643                new int[] {UserHandle.getUserId(packageUid)});
21644    }
21645
21646    @Override
21647    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21648        if (!sUserManager.exists(userId)) return;
21649        final int callingUid = Binder.getCallingUid();
21650        if (getInstantAppPackageName(callingUid) != null) {
21651            return;
21652        }
21653        final int permission = mContext.checkCallingOrSelfPermission(
21654                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21655        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21656        enforceCrossUserPermission(callingUid, userId,
21657                true /* requireFullPermission */, true /* checkShell */, "stop package");
21658        // writer
21659        synchronized (mPackages) {
21660            final PackageSetting ps = mSettings.mPackages.get(packageName);
21661            if (!filterAppAccessLPr(ps, callingUid, userId)
21662                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21663                            allowedByPermission, callingUid, userId)) {
21664                scheduleWritePackageRestrictionsLocked(userId);
21665            }
21666        }
21667    }
21668
21669    @Override
21670    public String getInstallerPackageName(String packageName) {
21671        final int callingUid = Binder.getCallingUid();
21672        if (getInstantAppPackageName(callingUid) != null) {
21673            return null;
21674        }
21675        // reader
21676        synchronized (mPackages) {
21677            final PackageSetting ps = mSettings.mPackages.get(packageName);
21678            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21679                return null;
21680            }
21681            return mSettings.getInstallerPackageNameLPr(packageName);
21682        }
21683    }
21684
21685    public boolean isOrphaned(String packageName) {
21686        // reader
21687        synchronized (mPackages) {
21688            return mSettings.isOrphaned(packageName);
21689        }
21690    }
21691
21692    @Override
21693    public int getApplicationEnabledSetting(String packageName, int userId) {
21694        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21695        int callingUid = Binder.getCallingUid();
21696        enforceCrossUserPermission(callingUid, userId,
21697                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21698        // reader
21699        synchronized (mPackages) {
21700            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21701                return COMPONENT_ENABLED_STATE_DISABLED;
21702            }
21703            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21704        }
21705    }
21706
21707    @Override
21708    public int getComponentEnabledSetting(ComponentName component, int userId) {
21709        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21710        int callingUid = Binder.getCallingUid();
21711        enforceCrossUserPermission(callingUid, userId,
21712                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21713        synchronized (mPackages) {
21714            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21715                    component, TYPE_UNKNOWN, userId)) {
21716                return COMPONENT_ENABLED_STATE_DISABLED;
21717            }
21718            return mSettings.getComponentEnabledSettingLPr(component, userId);
21719        }
21720    }
21721
21722    @Override
21723    public void enterSafeMode() {
21724        enforceSystemOrRoot("Only the system can request entering safe mode");
21725
21726        if (!mSystemReady) {
21727            mSafeMode = true;
21728        }
21729    }
21730
21731    @Override
21732    public void systemReady() {
21733        enforceSystemOrRoot("Only the system can claim the system is ready");
21734
21735        mSystemReady = true;
21736        final ContentResolver resolver = mContext.getContentResolver();
21737        ContentObserver co = new ContentObserver(mHandler) {
21738            @Override
21739            public void onChange(boolean selfChange) {
21740                mEphemeralAppsDisabled =
21741                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21742                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21743            }
21744        };
21745        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21746                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21747                false, co, UserHandle.USER_SYSTEM);
21748        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21749                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21750        co.onChange(true);
21751
21752        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21753        // disabled after already being started.
21754        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21755                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21756
21757        // Read the compatibilty setting when the system is ready.
21758        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21759                mContext.getContentResolver(),
21760                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21761        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21762        if (DEBUG_SETTINGS) {
21763            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21764        }
21765
21766        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21767
21768        synchronized (mPackages) {
21769            // Verify that all of the preferred activity components actually
21770            // exist.  It is possible for applications to be updated and at
21771            // that point remove a previously declared activity component that
21772            // had been set as a preferred activity.  We try to clean this up
21773            // the next time we encounter that preferred activity, but it is
21774            // possible for the user flow to never be able to return to that
21775            // situation so here we do a sanity check to make sure we haven't
21776            // left any junk around.
21777            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21778            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21779                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21780                removed.clear();
21781                for (PreferredActivity pa : pir.filterSet()) {
21782                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21783                        removed.add(pa);
21784                    }
21785                }
21786                if (removed.size() > 0) {
21787                    for (int r=0; r<removed.size(); r++) {
21788                        PreferredActivity pa = removed.get(r);
21789                        Slog.w(TAG, "Removing dangling preferred activity: "
21790                                + pa.mPref.mComponent);
21791                        pir.removeFilter(pa);
21792                    }
21793                    mSettings.writePackageRestrictionsLPr(
21794                            mSettings.mPreferredActivities.keyAt(i));
21795                }
21796            }
21797
21798            for (int userId : UserManagerService.getInstance().getUserIds()) {
21799                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21800                    grantPermissionsUserIds = ArrayUtils.appendInt(
21801                            grantPermissionsUserIds, userId);
21802                }
21803            }
21804        }
21805        sUserManager.systemReady();
21806
21807        // If we upgraded grant all default permissions before kicking off.
21808        for (int userId : grantPermissionsUserIds) {
21809            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21810        }
21811
21812        // If we did not grant default permissions, we preload from this the
21813        // default permission exceptions lazily to ensure we don't hit the
21814        // disk on a new user creation.
21815        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21816            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21817        }
21818
21819        // Kick off any messages waiting for system ready
21820        if (mPostSystemReadyMessages != null) {
21821            for (Message msg : mPostSystemReadyMessages) {
21822                msg.sendToTarget();
21823            }
21824            mPostSystemReadyMessages = null;
21825        }
21826
21827        // Watch for external volumes that come and go over time
21828        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21829        storage.registerListener(mStorageListener);
21830
21831        mInstallerService.systemReady();
21832        mPackageDexOptimizer.systemReady();
21833
21834        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21835                StorageManagerInternal.class);
21836        StorageManagerInternal.addExternalStoragePolicy(
21837                new StorageManagerInternal.ExternalStorageMountPolicy() {
21838            @Override
21839            public int getMountMode(int uid, String packageName) {
21840                if (Process.isIsolated(uid)) {
21841                    return Zygote.MOUNT_EXTERNAL_NONE;
21842                }
21843                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21844                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21845                }
21846                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21847                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21848                }
21849                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21850                    return Zygote.MOUNT_EXTERNAL_READ;
21851                }
21852                return Zygote.MOUNT_EXTERNAL_WRITE;
21853            }
21854
21855            @Override
21856            public boolean hasExternalStorage(int uid, String packageName) {
21857                return true;
21858            }
21859        });
21860
21861        // Now that we're mostly running, clean up stale users and apps
21862        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21863        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21864
21865        if (mPrivappPermissionsViolations != null) {
21866            Slog.wtf(TAG,"Signature|privileged permissions not in "
21867                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21868            mPrivappPermissionsViolations = null;
21869        }
21870    }
21871
21872    public void waitForAppDataPrepared() {
21873        if (mPrepareAppDataFuture == null) {
21874            return;
21875        }
21876        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21877        mPrepareAppDataFuture = null;
21878    }
21879
21880    @Override
21881    public boolean isSafeMode() {
21882        // allow instant applications
21883        return mSafeMode;
21884    }
21885
21886    @Override
21887    public boolean hasSystemUidErrors() {
21888        // allow instant applications
21889        return mHasSystemUidErrors;
21890    }
21891
21892    static String arrayToString(int[] array) {
21893        StringBuffer buf = new StringBuffer(128);
21894        buf.append('[');
21895        if (array != null) {
21896            for (int i=0; i<array.length; i++) {
21897                if (i > 0) buf.append(", ");
21898                buf.append(array[i]);
21899            }
21900        }
21901        buf.append(']');
21902        return buf.toString();
21903    }
21904
21905    static class DumpState {
21906        public static final int DUMP_LIBS = 1 << 0;
21907        public static final int DUMP_FEATURES = 1 << 1;
21908        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21909        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21910        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21911        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21912        public static final int DUMP_PERMISSIONS = 1 << 6;
21913        public static final int DUMP_PACKAGES = 1 << 7;
21914        public static final int DUMP_SHARED_USERS = 1 << 8;
21915        public static final int DUMP_MESSAGES = 1 << 9;
21916        public static final int DUMP_PROVIDERS = 1 << 10;
21917        public static final int DUMP_VERIFIERS = 1 << 11;
21918        public static final int DUMP_PREFERRED = 1 << 12;
21919        public static final int DUMP_PREFERRED_XML = 1 << 13;
21920        public static final int DUMP_KEYSETS = 1 << 14;
21921        public static final int DUMP_VERSION = 1 << 15;
21922        public static final int DUMP_INSTALLS = 1 << 16;
21923        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21924        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21925        public static final int DUMP_FROZEN = 1 << 19;
21926        public static final int DUMP_DEXOPT = 1 << 20;
21927        public static final int DUMP_COMPILER_STATS = 1 << 21;
21928        public static final int DUMP_CHANGES = 1 << 22;
21929        public static final int DUMP_VOLUMES = 1 << 23;
21930
21931        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21932
21933        private int mTypes;
21934
21935        private int mOptions;
21936
21937        private boolean mTitlePrinted;
21938
21939        private SharedUserSetting mSharedUser;
21940
21941        public boolean isDumping(int type) {
21942            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21943                return true;
21944            }
21945
21946            return (mTypes & type) != 0;
21947        }
21948
21949        public void setDump(int type) {
21950            mTypes |= type;
21951        }
21952
21953        public boolean isOptionEnabled(int option) {
21954            return (mOptions & option) != 0;
21955        }
21956
21957        public void setOptionEnabled(int option) {
21958            mOptions |= option;
21959        }
21960
21961        public boolean onTitlePrinted() {
21962            final boolean printed = mTitlePrinted;
21963            mTitlePrinted = true;
21964            return printed;
21965        }
21966
21967        public boolean getTitlePrinted() {
21968            return mTitlePrinted;
21969        }
21970
21971        public void setTitlePrinted(boolean enabled) {
21972            mTitlePrinted = enabled;
21973        }
21974
21975        public SharedUserSetting getSharedUser() {
21976            return mSharedUser;
21977        }
21978
21979        public void setSharedUser(SharedUserSetting user) {
21980            mSharedUser = user;
21981        }
21982    }
21983
21984    @Override
21985    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21986            FileDescriptor err, String[] args, ShellCallback callback,
21987            ResultReceiver resultReceiver) {
21988        (new PackageManagerShellCommand(this)).exec(
21989                this, in, out, err, args, callback, resultReceiver);
21990    }
21991
21992    @Override
21993    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21994        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21995
21996        DumpState dumpState = new DumpState();
21997        boolean fullPreferred = false;
21998        boolean checkin = false;
21999
22000        String packageName = null;
22001        ArraySet<String> permissionNames = null;
22002
22003        int opti = 0;
22004        while (opti < args.length) {
22005            String opt = args[opti];
22006            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22007                break;
22008            }
22009            opti++;
22010
22011            if ("-a".equals(opt)) {
22012                // Right now we only know how to print all.
22013            } else if ("-h".equals(opt)) {
22014                pw.println("Package manager dump options:");
22015                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22016                pw.println("    --checkin: dump for a checkin");
22017                pw.println("    -f: print details of intent filters");
22018                pw.println("    -h: print this help");
22019                pw.println("  cmd may be one of:");
22020                pw.println("    l[ibraries]: list known shared libraries");
22021                pw.println("    f[eatures]: list device features");
22022                pw.println("    k[eysets]: print known keysets");
22023                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22024                pw.println("    perm[issions]: dump permissions");
22025                pw.println("    permission [name ...]: dump declaration and use of given permission");
22026                pw.println("    pref[erred]: print preferred package settings");
22027                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22028                pw.println("    prov[iders]: dump content providers");
22029                pw.println("    p[ackages]: dump installed packages");
22030                pw.println("    s[hared-users]: dump shared user IDs");
22031                pw.println("    m[essages]: print collected runtime messages");
22032                pw.println("    v[erifiers]: print package verifier info");
22033                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22034                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22035                pw.println("    version: print database version info");
22036                pw.println("    write: write current settings now");
22037                pw.println("    installs: details about install sessions");
22038                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22039                pw.println("    dexopt: dump dexopt state");
22040                pw.println("    compiler-stats: dump compiler statistics");
22041                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22042                pw.println("    <package.name>: info about given package");
22043                return;
22044            } else if ("--checkin".equals(opt)) {
22045                checkin = true;
22046            } else if ("-f".equals(opt)) {
22047                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22048            } else if ("--proto".equals(opt)) {
22049                dumpProto(fd);
22050                return;
22051            } else {
22052                pw.println("Unknown argument: " + opt + "; use -h for help");
22053            }
22054        }
22055
22056        // Is the caller requesting to dump a particular piece of data?
22057        if (opti < args.length) {
22058            String cmd = args[opti];
22059            opti++;
22060            // Is this a package name?
22061            if ("android".equals(cmd) || cmd.contains(".")) {
22062                packageName = cmd;
22063                // When dumping a single package, we always dump all of its
22064                // filter information since the amount of data will be reasonable.
22065                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22066            } else if ("check-permission".equals(cmd)) {
22067                if (opti >= args.length) {
22068                    pw.println("Error: check-permission missing permission argument");
22069                    return;
22070                }
22071                String perm = args[opti];
22072                opti++;
22073                if (opti >= args.length) {
22074                    pw.println("Error: check-permission missing package argument");
22075                    return;
22076                }
22077
22078                String pkg = args[opti];
22079                opti++;
22080                int user = UserHandle.getUserId(Binder.getCallingUid());
22081                if (opti < args.length) {
22082                    try {
22083                        user = Integer.parseInt(args[opti]);
22084                    } catch (NumberFormatException e) {
22085                        pw.println("Error: check-permission user argument is not a number: "
22086                                + args[opti]);
22087                        return;
22088                    }
22089                }
22090
22091                // Normalize package name to handle renamed packages and static libs
22092                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22093
22094                pw.println(checkPermission(perm, pkg, user));
22095                return;
22096            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22097                dumpState.setDump(DumpState.DUMP_LIBS);
22098            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22099                dumpState.setDump(DumpState.DUMP_FEATURES);
22100            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22101                if (opti >= args.length) {
22102                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22103                            | DumpState.DUMP_SERVICE_RESOLVERS
22104                            | DumpState.DUMP_RECEIVER_RESOLVERS
22105                            | DumpState.DUMP_CONTENT_RESOLVERS);
22106                } else {
22107                    while (opti < args.length) {
22108                        String name = args[opti];
22109                        if ("a".equals(name) || "activity".equals(name)) {
22110                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22111                        } else if ("s".equals(name) || "service".equals(name)) {
22112                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22113                        } else if ("r".equals(name) || "receiver".equals(name)) {
22114                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22115                        } else if ("c".equals(name) || "content".equals(name)) {
22116                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22117                        } else {
22118                            pw.println("Error: unknown resolver table type: " + name);
22119                            return;
22120                        }
22121                        opti++;
22122                    }
22123                }
22124            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22125                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22126            } else if ("permission".equals(cmd)) {
22127                if (opti >= args.length) {
22128                    pw.println("Error: permission requires permission name");
22129                    return;
22130                }
22131                permissionNames = new ArraySet<>();
22132                while (opti < args.length) {
22133                    permissionNames.add(args[opti]);
22134                    opti++;
22135                }
22136                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22137                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22138            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22139                dumpState.setDump(DumpState.DUMP_PREFERRED);
22140            } else if ("preferred-xml".equals(cmd)) {
22141                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22142                if (opti < args.length && "--full".equals(args[opti])) {
22143                    fullPreferred = true;
22144                    opti++;
22145                }
22146            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22147                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22148            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22149                dumpState.setDump(DumpState.DUMP_PACKAGES);
22150            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22151                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22152            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22153                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22154            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22155                dumpState.setDump(DumpState.DUMP_MESSAGES);
22156            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22157                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22158            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22159                    || "intent-filter-verifiers".equals(cmd)) {
22160                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22161            } else if ("version".equals(cmd)) {
22162                dumpState.setDump(DumpState.DUMP_VERSION);
22163            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22164                dumpState.setDump(DumpState.DUMP_KEYSETS);
22165            } else if ("installs".equals(cmd)) {
22166                dumpState.setDump(DumpState.DUMP_INSTALLS);
22167            } else if ("frozen".equals(cmd)) {
22168                dumpState.setDump(DumpState.DUMP_FROZEN);
22169            } else if ("volumes".equals(cmd)) {
22170                dumpState.setDump(DumpState.DUMP_VOLUMES);
22171            } else if ("dexopt".equals(cmd)) {
22172                dumpState.setDump(DumpState.DUMP_DEXOPT);
22173            } else if ("compiler-stats".equals(cmd)) {
22174                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22175            } else if ("changes".equals(cmd)) {
22176                dumpState.setDump(DumpState.DUMP_CHANGES);
22177            } else if ("write".equals(cmd)) {
22178                synchronized (mPackages) {
22179                    mSettings.writeLPr();
22180                    pw.println("Settings written.");
22181                    return;
22182                }
22183            }
22184        }
22185
22186        if (checkin) {
22187            pw.println("vers,1");
22188        }
22189
22190        // reader
22191        synchronized (mPackages) {
22192            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22193                if (!checkin) {
22194                    if (dumpState.onTitlePrinted())
22195                        pw.println();
22196                    pw.println("Database versions:");
22197                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22198                }
22199            }
22200
22201            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22202                if (!checkin) {
22203                    if (dumpState.onTitlePrinted())
22204                        pw.println();
22205                    pw.println("Verifiers:");
22206                    pw.print("  Required: ");
22207                    pw.print(mRequiredVerifierPackage);
22208                    pw.print(" (uid=");
22209                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22210                            UserHandle.USER_SYSTEM));
22211                    pw.println(")");
22212                } else if (mRequiredVerifierPackage != null) {
22213                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22214                    pw.print(",");
22215                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22216                            UserHandle.USER_SYSTEM));
22217                }
22218            }
22219
22220            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22221                    packageName == null) {
22222                if (mIntentFilterVerifierComponent != null) {
22223                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22224                    if (!checkin) {
22225                        if (dumpState.onTitlePrinted())
22226                            pw.println();
22227                        pw.println("Intent Filter Verifier:");
22228                        pw.print("  Using: ");
22229                        pw.print(verifierPackageName);
22230                        pw.print(" (uid=");
22231                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22232                                UserHandle.USER_SYSTEM));
22233                        pw.println(")");
22234                    } else if (verifierPackageName != null) {
22235                        pw.print("ifv,"); pw.print(verifierPackageName);
22236                        pw.print(",");
22237                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22238                                UserHandle.USER_SYSTEM));
22239                    }
22240                } else {
22241                    pw.println();
22242                    pw.println("No Intent Filter Verifier available!");
22243                }
22244            }
22245
22246            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22247                boolean printedHeader = false;
22248                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22249                while (it.hasNext()) {
22250                    String libName = it.next();
22251                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22252                    if (versionedLib == null) {
22253                        continue;
22254                    }
22255                    final int versionCount = versionedLib.size();
22256                    for (int i = 0; i < versionCount; i++) {
22257                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22258                        if (!checkin) {
22259                            if (!printedHeader) {
22260                                if (dumpState.onTitlePrinted())
22261                                    pw.println();
22262                                pw.println("Libraries:");
22263                                printedHeader = true;
22264                            }
22265                            pw.print("  ");
22266                        } else {
22267                            pw.print("lib,");
22268                        }
22269                        pw.print(libEntry.info.getName());
22270                        if (libEntry.info.isStatic()) {
22271                            pw.print(" version=" + libEntry.info.getVersion());
22272                        }
22273                        if (!checkin) {
22274                            pw.print(" -> ");
22275                        }
22276                        if (libEntry.path != null) {
22277                            pw.print(" (jar) ");
22278                            pw.print(libEntry.path);
22279                        } else {
22280                            pw.print(" (apk) ");
22281                            pw.print(libEntry.apk);
22282                        }
22283                        pw.println();
22284                    }
22285                }
22286            }
22287
22288            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22289                if (dumpState.onTitlePrinted())
22290                    pw.println();
22291                if (!checkin) {
22292                    pw.println("Features:");
22293                }
22294
22295                synchronized (mAvailableFeatures) {
22296                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22297                        if (checkin) {
22298                            pw.print("feat,");
22299                            pw.print(feat.name);
22300                            pw.print(",");
22301                            pw.println(feat.version);
22302                        } else {
22303                            pw.print("  ");
22304                            pw.print(feat.name);
22305                            if (feat.version > 0) {
22306                                pw.print(" version=");
22307                                pw.print(feat.version);
22308                            }
22309                            pw.println();
22310                        }
22311                    }
22312                }
22313            }
22314
22315            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22316                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22317                        : "Activity Resolver Table:", "  ", packageName,
22318                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22319                    dumpState.setTitlePrinted(true);
22320                }
22321            }
22322            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22323                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22324                        : "Receiver Resolver Table:", "  ", packageName,
22325                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22326                    dumpState.setTitlePrinted(true);
22327                }
22328            }
22329            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22330                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22331                        : "Service Resolver Table:", "  ", packageName,
22332                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22333                    dumpState.setTitlePrinted(true);
22334                }
22335            }
22336            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22337                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22338                        : "Provider Resolver Table:", "  ", packageName,
22339                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22340                    dumpState.setTitlePrinted(true);
22341                }
22342            }
22343
22344            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22345                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22346                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22347                    int user = mSettings.mPreferredActivities.keyAt(i);
22348                    if (pir.dump(pw,
22349                            dumpState.getTitlePrinted()
22350                                ? "\nPreferred Activities User " + user + ":"
22351                                : "Preferred Activities User " + user + ":", "  ",
22352                            packageName, true, false)) {
22353                        dumpState.setTitlePrinted(true);
22354                    }
22355                }
22356            }
22357
22358            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22359                pw.flush();
22360                FileOutputStream fout = new FileOutputStream(fd);
22361                BufferedOutputStream str = new BufferedOutputStream(fout);
22362                XmlSerializer serializer = new FastXmlSerializer();
22363                try {
22364                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22365                    serializer.startDocument(null, true);
22366                    serializer.setFeature(
22367                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22368                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22369                    serializer.endDocument();
22370                    serializer.flush();
22371                } catch (IllegalArgumentException e) {
22372                    pw.println("Failed writing: " + e);
22373                } catch (IllegalStateException e) {
22374                    pw.println("Failed writing: " + e);
22375                } catch (IOException e) {
22376                    pw.println("Failed writing: " + e);
22377                }
22378            }
22379
22380            if (!checkin
22381                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22382                    && packageName == null) {
22383                pw.println();
22384                int count = mSettings.mPackages.size();
22385                if (count == 0) {
22386                    pw.println("No applications!");
22387                    pw.println();
22388                } else {
22389                    final String prefix = "  ";
22390                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22391                    if (allPackageSettings.size() == 0) {
22392                        pw.println("No domain preferred apps!");
22393                        pw.println();
22394                    } else {
22395                        pw.println("App verification status:");
22396                        pw.println();
22397                        count = 0;
22398                        for (PackageSetting ps : allPackageSettings) {
22399                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22400                            if (ivi == null || ivi.getPackageName() == null) continue;
22401                            pw.println(prefix + "Package: " + ivi.getPackageName());
22402                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22403                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22404                            pw.println();
22405                            count++;
22406                        }
22407                        if (count == 0) {
22408                            pw.println(prefix + "No app verification established.");
22409                            pw.println();
22410                        }
22411                        for (int userId : sUserManager.getUserIds()) {
22412                            pw.println("App linkages for user " + userId + ":");
22413                            pw.println();
22414                            count = 0;
22415                            for (PackageSetting ps : allPackageSettings) {
22416                                final long status = ps.getDomainVerificationStatusForUser(userId);
22417                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22418                                        && !DEBUG_DOMAIN_VERIFICATION) {
22419                                    continue;
22420                                }
22421                                pw.println(prefix + "Package: " + ps.name);
22422                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22423                                String statusStr = IntentFilterVerificationInfo.
22424                                        getStatusStringFromValue(status);
22425                                pw.println(prefix + "Status:  " + statusStr);
22426                                pw.println();
22427                                count++;
22428                            }
22429                            if (count == 0) {
22430                                pw.println(prefix + "No configured app linkages.");
22431                                pw.println();
22432                            }
22433                        }
22434                    }
22435                }
22436            }
22437
22438            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22439                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22440                if (packageName == null && permissionNames == null) {
22441                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22442                        if (iperm == 0) {
22443                            if (dumpState.onTitlePrinted())
22444                                pw.println();
22445                            pw.println("AppOp Permissions:");
22446                        }
22447                        pw.print("  AppOp Permission ");
22448                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22449                        pw.println(":");
22450                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22451                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22452                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22453                        }
22454                    }
22455                }
22456            }
22457
22458            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22459                boolean printedSomething = false;
22460                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22461                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22462                        continue;
22463                    }
22464                    if (!printedSomething) {
22465                        if (dumpState.onTitlePrinted())
22466                            pw.println();
22467                        pw.println("Registered ContentProviders:");
22468                        printedSomething = true;
22469                    }
22470                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22471                    pw.print("    "); pw.println(p.toString());
22472                }
22473                printedSomething = false;
22474                for (Map.Entry<String, PackageParser.Provider> entry :
22475                        mProvidersByAuthority.entrySet()) {
22476                    PackageParser.Provider p = entry.getValue();
22477                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22478                        continue;
22479                    }
22480                    if (!printedSomething) {
22481                        if (dumpState.onTitlePrinted())
22482                            pw.println();
22483                        pw.println("ContentProvider Authorities:");
22484                        printedSomething = true;
22485                    }
22486                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22487                    pw.print("    "); pw.println(p.toString());
22488                    if (p.info != null && p.info.applicationInfo != null) {
22489                        final String appInfo = p.info.applicationInfo.toString();
22490                        pw.print("      applicationInfo="); pw.println(appInfo);
22491                    }
22492                }
22493            }
22494
22495            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22496                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22497            }
22498
22499            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22500                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22501            }
22502
22503            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22504                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22505            }
22506
22507            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22508                if (dumpState.onTitlePrinted()) pw.println();
22509                pw.println("Package Changes:");
22510                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22511                final int K = mChangedPackages.size();
22512                for (int i = 0; i < K; i++) {
22513                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22514                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22515                    final int N = changes.size();
22516                    if (N == 0) {
22517                        pw.print("    "); pw.println("No packages changed");
22518                    } else {
22519                        for (int j = 0; j < N; j++) {
22520                            final String pkgName = changes.valueAt(j);
22521                            final int sequenceNumber = changes.keyAt(j);
22522                            pw.print("    ");
22523                            pw.print("seq=");
22524                            pw.print(sequenceNumber);
22525                            pw.print(", package=");
22526                            pw.println(pkgName);
22527                        }
22528                    }
22529                }
22530            }
22531
22532            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22533                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22534            }
22535
22536            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22537                // XXX should handle packageName != null by dumping only install data that
22538                // the given package is involved with.
22539                if (dumpState.onTitlePrinted()) pw.println();
22540
22541                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22542                ipw.println();
22543                ipw.println("Frozen packages:");
22544                ipw.increaseIndent();
22545                if (mFrozenPackages.size() == 0) {
22546                    ipw.println("(none)");
22547                } else {
22548                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22549                        ipw.println(mFrozenPackages.valueAt(i));
22550                    }
22551                }
22552                ipw.decreaseIndent();
22553            }
22554
22555            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22556                if (dumpState.onTitlePrinted()) pw.println();
22557
22558                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22559                ipw.println();
22560                ipw.println("Loaded volumes:");
22561                ipw.increaseIndent();
22562                if (mLoadedVolumes.size() == 0) {
22563                    ipw.println("(none)");
22564                } else {
22565                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22566                        ipw.println(mLoadedVolumes.valueAt(i));
22567                    }
22568                }
22569                ipw.decreaseIndent();
22570            }
22571
22572            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22573                if (dumpState.onTitlePrinted()) pw.println();
22574                dumpDexoptStateLPr(pw, packageName);
22575            }
22576
22577            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22578                if (dumpState.onTitlePrinted()) pw.println();
22579                dumpCompilerStatsLPr(pw, packageName);
22580            }
22581
22582            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22583                if (dumpState.onTitlePrinted()) pw.println();
22584                mSettings.dumpReadMessagesLPr(pw, dumpState);
22585
22586                pw.println();
22587                pw.println("Package warning messages:");
22588                BufferedReader in = null;
22589                String line = null;
22590                try {
22591                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22592                    while ((line = in.readLine()) != null) {
22593                        if (line.contains("ignored: updated version")) continue;
22594                        pw.println(line);
22595                    }
22596                } catch (IOException ignored) {
22597                } finally {
22598                    IoUtils.closeQuietly(in);
22599                }
22600            }
22601
22602            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22603                BufferedReader in = null;
22604                String line = null;
22605                try {
22606                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22607                    while ((line = in.readLine()) != null) {
22608                        if (line.contains("ignored: updated version")) continue;
22609                        pw.print("msg,");
22610                        pw.println(line);
22611                    }
22612                } catch (IOException ignored) {
22613                } finally {
22614                    IoUtils.closeQuietly(in);
22615                }
22616            }
22617        }
22618
22619        // PackageInstaller should be called outside of mPackages lock
22620        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22621            // XXX should handle packageName != null by dumping only install data that
22622            // the given package is involved with.
22623            if (dumpState.onTitlePrinted()) pw.println();
22624            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22625        }
22626    }
22627
22628    private void dumpProto(FileDescriptor fd) {
22629        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22630
22631        synchronized (mPackages) {
22632            final long requiredVerifierPackageToken =
22633                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22634            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22635            proto.write(
22636                    PackageServiceDumpProto.PackageShortProto.UID,
22637                    getPackageUid(
22638                            mRequiredVerifierPackage,
22639                            MATCH_DEBUG_TRIAGED_MISSING,
22640                            UserHandle.USER_SYSTEM));
22641            proto.end(requiredVerifierPackageToken);
22642
22643            if (mIntentFilterVerifierComponent != null) {
22644                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22645                final long verifierPackageToken =
22646                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22647                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22648                proto.write(
22649                        PackageServiceDumpProto.PackageShortProto.UID,
22650                        getPackageUid(
22651                                verifierPackageName,
22652                                MATCH_DEBUG_TRIAGED_MISSING,
22653                                UserHandle.USER_SYSTEM));
22654                proto.end(verifierPackageToken);
22655            }
22656
22657            dumpSharedLibrariesProto(proto);
22658            dumpFeaturesProto(proto);
22659            mSettings.dumpPackagesProto(proto);
22660            mSettings.dumpSharedUsersProto(proto);
22661            dumpMessagesProto(proto);
22662        }
22663        proto.flush();
22664    }
22665
22666    private void dumpMessagesProto(ProtoOutputStream proto) {
22667        BufferedReader in = null;
22668        String line = null;
22669        try {
22670            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22671            while ((line = in.readLine()) != null) {
22672                if (line.contains("ignored: updated version")) continue;
22673                proto.write(PackageServiceDumpProto.MESSAGES, line);
22674            }
22675        } catch (IOException ignored) {
22676        } finally {
22677            IoUtils.closeQuietly(in);
22678        }
22679    }
22680
22681    private void dumpFeaturesProto(ProtoOutputStream proto) {
22682        synchronized (mAvailableFeatures) {
22683            final int count = mAvailableFeatures.size();
22684            for (int i = 0; i < count; i++) {
22685                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22686                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22687                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22688                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22689                proto.end(featureToken);
22690            }
22691        }
22692    }
22693
22694    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22695        final int count = mSharedLibraries.size();
22696        for (int i = 0; i < count; i++) {
22697            final String libName = mSharedLibraries.keyAt(i);
22698            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22699            if (versionedLib == null) {
22700                continue;
22701            }
22702            final int versionCount = versionedLib.size();
22703            for (int j = 0; j < versionCount; j++) {
22704                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22705                final long sharedLibraryToken =
22706                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22707                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22708                final boolean isJar = (libEntry.path != null);
22709                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22710                if (isJar) {
22711                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22712                } else {
22713                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22714                }
22715                proto.end(sharedLibraryToken);
22716            }
22717        }
22718    }
22719
22720    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22721        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22722        ipw.println();
22723        ipw.println("Dexopt state:");
22724        ipw.increaseIndent();
22725        Collection<PackageParser.Package> packages = null;
22726        if (packageName != null) {
22727            PackageParser.Package targetPackage = mPackages.get(packageName);
22728            if (targetPackage != null) {
22729                packages = Collections.singletonList(targetPackage);
22730            } else {
22731                ipw.println("Unable to find package: " + packageName);
22732                return;
22733            }
22734        } else {
22735            packages = mPackages.values();
22736        }
22737
22738        for (PackageParser.Package pkg : packages) {
22739            ipw.println("[" + pkg.packageName + "]");
22740            ipw.increaseIndent();
22741            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22742            ipw.decreaseIndent();
22743        }
22744    }
22745
22746    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22747        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22748        ipw.println();
22749        ipw.println("Compiler stats:");
22750        ipw.increaseIndent();
22751        Collection<PackageParser.Package> packages = null;
22752        if (packageName != null) {
22753            PackageParser.Package targetPackage = mPackages.get(packageName);
22754            if (targetPackage != null) {
22755                packages = Collections.singletonList(targetPackage);
22756            } else {
22757                ipw.println("Unable to find package: " + packageName);
22758                return;
22759            }
22760        } else {
22761            packages = mPackages.values();
22762        }
22763
22764        for (PackageParser.Package pkg : packages) {
22765            ipw.println("[" + pkg.packageName + "]");
22766            ipw.increaseIndent();
22767
22768            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22769            if (stats == null) {
22770                ipw.println("(No recorded stats)");
22771            } else {
22772                stats.dump(ipw);
22773            }
22774            ipw.decreaseIndent();
22775        }
22776    }
22777
22778    private String dumpDomainString(String packageName) {
22779        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22780                .getList();
22781        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22782
22783        ArraySet<String> result = new ArraySet<>();
22784        if (iviList.size() > 0) {
22785            for (IntentFilterVerificationInfo ivi : iviList) {
22786                for (String host : ivi.getDomains()) {
22787                    result.add(host);
22788                }
22789            }
22790        }
22791        if (filters != null && filters.size() > 0) {
22792            for (IntentFilter filter : filters) {
22793                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22794                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22795                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22796                    result.addAll(filter.getHostsList());
22797                }
22798            }
22799        }
22800
22801        StringBuilder sb = new StringBuilder(result.size() * 16);
22802        for (String domain : result) {
22803            if (sb.length() > 0) sb.append(" ");
22804            sb.append(domain);
22805        }
22806        return sb.toString();
22807    }
22808
22809    // ------- apps on sdcard specific code -------
22810    static final boolean DEBUG_SD_INSTALL = false;
22811
22812    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22813
22814    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22815
22816    private boolean mMediaMounted = false;
22817
22818    static String getEncryptKey() {
22819        try {
22820            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22821                    SD_ENCRYPTION_KEYSTORE_NAME);
22822            if (sdEncKey == null) {
22823                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22824                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22825                if (sdEncKey == null) {
22826                    Slog.e(TAG, "Failed to create encryption keys");
22827                    return null;
22828                }
22829            }
22830            return sdEncKey;
22831        } catch (NoSuchAlgorithmException nsae) {
22832            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22833            return null;
22834        } catch (IOException ioe) {
22835            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22836            return null;
22837        }
22838    }
22839
22840    /*
22841     * Update media status on PackageManager.
22842     */
22843    @Override
22844    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22845        enforceSystemOrRoot("Media status can only be updated by the system");
22846        // reader; this apparently protects mMediaMounted, but should probably
22847        // be a different lock in that case.
22848        synchronized (mPackages) {
22849            Log.i(TAG, "Updating external media status from "
22850                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22851                    + (mediaStatus ? "mounted" : "unmounted"));
22852            if (DEBUG_SD_INSTALL)
22853                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22854                        + ", mMediaMounted=" + mMediaMounted);
22855            if (mediaStatus == mMediaMounted) {
22856                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22857                        : 0, -1);
22858                mHandler.sendMessage(msg);
22859                return;
22860            }
22861            mMediaMounted = mediaStatus;
22862        }
22863        // Queue up an async operation since the package installation may take a
22864        // little while.
22865        mHandler.post(new Runnable() {
22866            public void run() {
22867                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22868            }
22869        });
22870    }
22871
22872    /**
22873     * Called by StorageManagerService when the initial ASECs to scan are available.
22874     * Should block until all the ASEC containers are finished being scanned.
22875     */
22876    public void scanAvailableAsecs() {
22877        updateExternalMediaStatusInner(true, false, false);
22878    }
22879
22880    /*
22881     * Collect information of applications on external media, map them against
22882     * existing containers and update information based on current mount status.
22883     * Please note that we always have to report status if reportStatus has been
22884     * set to true especially when unloading packages.
22885     */
22886    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22887            boolean externalStorage) {
22888        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22889        int[] uidArr = EmptyArray.INT;
22890
22891        final String[] list = PackageHelper.getSecureContainerList();
22892        if (ArrayUtils.isEmpty(list)) {
22893            Log.i(TAG, "No secure containers found");
22894        } else {
22895            // Process list of secure containers and categorize them
22896            // as active or stale based on their package internal state.
22897
22898            // reader
22899            synchronized (mPackages) {
22900                for (String cid : list) {
22901                    // Leave stages untouched for now; installer service owns them
22902                    if (PackageInstallerService.isStageName(cid)) continue;
22903
22904                    if (DEBUG_SD_INSTALL)
22905                        Log.i(TAG, "Processing container " + cid);
22906                    String pkgName = getAsecPackageName(cid);
22907                    if (pkgName == null) {
22908                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22909                        continue;
22910                    }
22911                    if (DEBUG_SD_INSTALL)
22912                        Log.i(TAG, "Looking for pkg : " + pkgName);
22913
22914                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22915                    if (ps == null) {
22916                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22917                        continue;
22918                    }
22919
22920                    /*
22921                     * Skip packages that are not external if we're unmounting
22922                     * external storage.
22923                     */
22924                    if (externalStorage && !isMounted && !isExternal(ps)) {
22925                        continue;
22926                    }
22927
22928                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22929                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22930                    // The package status is changed only if the code path
22931                    // matches between settings and the container id.
22932                    if (ps.codePathString != null
22933                            && ps.codePathString.startsWith(args.getCodePath())) {
22934                        if (DEBUG_SD_INSTALL) {
22935                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22936                                    + " at code path: " + ps.codePathString);
22937                        }
22938
22939                        // We do have a valid package installed on sdcard
22940                        processCids.put(args, ps.codePathString);
22941                        final int uid = ps.appId;
22942                        if (uid != -1) {
22943                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22944                        }
22945                    } else {
22946                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22947                                + ps.codePathString);
22948                    }
22949                }
22950            }
22951
22952            Arrays.sort(uidArr);
22953        }
22954
22955        // Process packages with valid entries.
22956        if (isMounted) {
22957            if (DEBUG_SD_INSTALL)
22958                Log.i(TAG, "Loading packages");
22959            loadMediaPackages(processCids, uidArr, externalStorage);
22960            startCleaningPackages();
22961            mInstallerService.onSecureContainersAvailable();
22962        } else {
22963            if (DEBUG_SD_INSTALL)
22964                Log.i(TAG, "Unloading packages");
22965            unloadMediaPackages(processCids, uidArr, reportStatus);
22966        }
22967    }
22968
22969    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22970            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22971        final int size = infos.size();
22972        final String[] packageNames = new String[size];
22973        final int[] packageUids = new int[size];
22974        for (int i = 0; i < size; i++) {
22975            final ApplicationInfo info = infos.get(i);
22976            packageNames[i] = info.packageName;
22977            packageUids[i] = info.uid;
22978        }
22979        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22980                finishedReceiver);
22981    }
22982
22983    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22984            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22985        sendResourcesChangedBroadcast(mediaStatus, replacing,
22986                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22987    }
22988
22989    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22990            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22991        int size = pkgList.length;
22992        if (size > 0) {
22993            // Send broadcasts here
22994            Bundle extras = new Bundle();
22995            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22996            if (uidArr != null) {
22997                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22998            }
22999            if (replacing) {
23000                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23001            }
23002            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23003                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23004            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23005        }
23006    }
23007
23008   /*
23009     * Look at potentially valid container ids from processCids If package
23010     * information doesn't match the one on record or package scanning fails,
23011     * the cid is added to list of removeCids. We currently don't delete stale
23012     * containers.
23013     */
23014    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23015            boolean externalStorage) {
23016        ArrayList<String> pkgList = new ArrayList<String>();
23017        Set<AsecInstallArgs> keys = processCids.keySet();
23018
23019        for (AsecInstallArgs args : keys) {
23020            String codePath = processCids.get(args);
23021            if (DEBUG_SD_INSTALL)
23022                Log.i(TAG, "Loading container : " + args.cid);
23023            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23024            try {
23025                // Make sure there are no container errors first.
23026                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23027                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23028                            + " when installing from sdcard");
23029                    continue;
23030                }
23031                // Check code path here.
23032                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23033                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23034                            + " does not match one in settings " + codePath);
23035                    continue;
23036                }
23037                // Parse package
23038                int parseFlags = mDefParseFlags;
23039                if (args.isExternalAsec()) {
23040                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23041                }
23042                if (args.isFwdLocked()) {
23043                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23044                }
23045
23046                synchronized (mInstallLock) {
23047                    PackageParser.Package pkg = null;
23048                    try {
23049                        // Sadly we don't know the package name yet to freeze it
23050                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23051                                SCAN_IGNORE_FROZEN, 0, null);
23052                    } catch (PackageManagerException e) {
23053                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23054                    }
23055                    // Scan the package
23056                    if (pkg != null) {
23057                        /*
23058                         * TODO why is the lock being held? doPostInstall is
23059                         * called in other places without the lock. This needs
23060                         * to be straightened out.
23061                         */
23062                        // writer
23063                        synchronized (mPackages) {
23064                            retCode = PackageManager.INSTALL_SUCCEEDED;
23065                            pkgList.add(pkg.packageName);
23066                            // Post process args
23067                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23068                                    pkg.applicationInfo.uid);
23069                        }
23070                    } else {
23071                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23072                    }
23073                }
23074
23075            } finally {
23076                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23077                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23078                }
23079            }
23080        }
23081        // writer
23082        synchronized (mPackages) {
23083            // If the platform SDK has changed since the last time we booted,
23084            // we need to re-grant app permission to catch any new ones that
23085            // appear. This is really a hack, and means that apps can in some
23086            // cases get permissions that the user didn't initially explicitly
23087            // allow... it would be nice to have some better way to handle
23088            // this situation.
23089            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23090                    : mSettings.getInternalVersion();
23091            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23092                    : StorageManager.UUID_PRIVATE_INTERNAL;
23093
23094            int updateFlags = UPDATE_PERMISSIONS_ALL;
23095            if (ver.sdkVersion != mSdkVersion) {
23096                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23097                        + mSdkVersion + "; regranting permissions for external");
23098                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23099            }
23100            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23101
23102            // Yay, everything is now upgraded
23103            ver.forceCurrent();
23104
23105            // can downgrade to reader
23106            // Persist settings
23107            mSettings.writeLPr();
23108        }
23109        // Send a broadcast to let everyone know we are done processing
23110        if (pkgList.size() > 0) {
23111            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23112        }
23113    }
23114
23115   /*
23116     * Utility method to unload a list of specified containers
23117     */
23118    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23119        // Just unmount all valid containers.
23120        for (AsecInstallArgs arg : cidArgs) {
23121            synchronized (mInstallLock) {
23122                arg.doPostDeleteLI(false);
23123           }
23124       }
23125   }
23126
23127    /*
23128     * Unload packages mounted on external media. This involves deleting package
23129     * data from internal structures, sending broadcasts about disabled packages,
23130     * gc'ing to free up references, unmounting all secure containers
23131     * corresponding to packages on external media, and posting a
23132     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23133     * that we always have to post this message if status has been requested no
23134     * matter what.
23135     */
23136    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23137            final boolean reportStatus) {
23138        if (DEBUG_SD_INSTALL)
23139            Log.i(TAG, "unloading media packages");
23140        ArrayList<String> pkgList = new ArrayList<String>();
23141        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23142        final Set<AsecInstallArgs> keys = processCids.keySet();
23143        for (AsecInstallArgs args : keys) {
23144            String pkgName = args.getPackageName();
23145            if (DEBUG_SD_INSTALL)
23146                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23147            // Delete package internally
23148            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23149            synchronized (mInstallLock) {
23150                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23151                final boolean res;
23152                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23153                        "unloadMediaPackages")) {
23154                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23155                            null);
23156                }
23157                if (res) {
23158                    pkgList.add(pkgName);
23159                } else {
23160                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23161                    failedList.add(args);
23162                }
23163            }
23164        }
23165
23166        // reader
23167        synchronized (mPackages) {
23168            // We didn't update the settings after removing each package;
23169            // write them now for all packages.
23170            mSettings.writeLPr();
23171        }
23172
23173        // We have to absolutely send UPDATED_MEDIA_STATUS only
23174        // after confirming that all the receivers processed the ordered
23175        // broadcast when packages get disabled, force a gc to clean things up.
23176        // and unload all the containers.
23177        if (pkgList.size() > 0) {
23178            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23179                    new IIntentReceiver.Stub() {
23180                public void performReceive(Intent intent, int resultCode, String data,
23181                        Bundle extras, boolean ordered, boolean sticky,
23182                        int sendingUser) throws RemoteException {
23183                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23184                            reportStatus ? 1 : 0, 1, keys);
23185                    mHandler.sendMessage(msg);
23186                }
23187            });
23188        } else {
23189            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23190                    keys);
23191            mHandler.sendMessage(msg);
23192        }
23193    }
23194
23195    private void loadPrivatePackages(final VolumeInfo vol) {
23196        mHandler.post(new Runnable() {
23197            @Override
23198            public void run() {
23199                loadPrivatePackagesInner(vol);
23200            }
23201        });
23202    }
23203
23204    private void loadPrivatePackagesInner(VolumeInfo vol) {
23205        final String volumeUuid = vol.fsUuid;
23206        if (TextUtils.isEmpty(volumeUuid)) {
23207            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23208            return;
23209        }
23210
23211        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23212        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23213        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23214
23215        final VersionInfo ver;
23216        final List<PackageSetting> packages;
23217        synchronized (mPackages) {
23218            ver = mSettings.findOrCreateVersion(volumeUuid);
23219            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23220        }
23221
23222        for (PackageSetting ps : packages) {
23223            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23224            synchronized (mInstallLock) {
23225                final PackageParser.Package pkg;
23226                try {
23227                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23228                    loaded.add(pkg.applicationInfo);
23229
23230                } catch (PackageManagerException e) {
23231                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23232                }
23233
23234                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23235                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23236                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23237                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23238                }
23239            }
23240        }
23241
23242        // Reconcile app data for all started/unlocked users
23243        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23244        final UserManager um = mContext.getSystemService(UserManager.class);
23245        UserManagerInternal umInternal = getUserManagerInternal();
23246        for (UserInfo user : um.getUsers()) {
23247            final int flags;
23248            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23249                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23250            } else if (umInternal.isUserRunning(user.id)) {
23251                flags = StorageManager.FLAG_STORAGE_DE;
23252            } else {
23253                continue;
23254            }
23255
23256            try {
23257                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23258                synchronized (mInstallLock) {
23259                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23260                }
23261            } catch (IllegalStateException e) {
23262                // Device was probably ejected, and we'll process that event momentarily
23263                Slog.w(TAG, "Failed to prepare storage: " + e);
23264            }
23265        }
23266
23267        synchronized (mPackages) {
23268            int updateFlags = UPDATE_PERMISSIONS_ALL;
23269            if (ver.sdkVersion != mSdkVersion) {
23270                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23271                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23272                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23273            }
23274            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23275
23276            // Yay, everything is now upgraded
23277            ver.forceCurrent();
23278
23279            mSettings.writeLPr();
23280        }
23281
23282        for (PackageFreezer freezer : freezers) {
23283            freezer.close();
23284        }
23285
23286        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23287        sendResourcesChangedBroadcast(true, false, loaded, null);
23288        mLoadedVolumes.add(vol.getId());
23289    }
23290
23291    private void unloadPrivatePackages(final VolumeInfo vol) {
23292        mHandler.post(new Runnable() {
23293            @Override
23294            public void run() {
23295                unloadPrivatePackagesInner(vol);
23296            }
23297        });
23298    }
23299
23300    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23301        final String volumeUuid = vol.fsUuid;
23302        if (TextUtils.isEmpty(volumeUuid)) {
23303            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23304            return;
23305        }
23306
23307        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23308        synchronized (mInstallLock) {
23309        synchronized (mPackages) {
23310            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23311            for (PackageSetting ps : packages) {
23312                if (ps.pkg == null) continue;
23313
23314                final ApplicationInfo info = ps.pkg.applicationInfo;
23315                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23316                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23317
23318                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23319                        "unloadPrivatePackagesInner")) {
23320                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23321                            false, null)) {
23322                        unloaded.add(info);
23323                    } else {
23324                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23325                    }
23326                }
23327
23328                // Try very hard to release any references to this package
23329                // so we don't risk the system server being killed due to
23330                // open FDs
23331                AttributeCache.instance().removePackage(ps.name);
23332            }
23333
23334            mSettings.writeLPr();
23335        }
23336        }
23337
23338        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23339        sendResourcesChangedBroadcast(false, false, unloaded, null);
23340        mLoadedVolumes.remove(vol.getId());
23341
23342        // Try very hard to release any references to this path so we don't risk
23343        // the system server being killed due to open FDs
23344        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23345
23346        for (int i = 0; i < 3; i++) {
23347            System.gc();
23348            System.runFinalization();
23349        }
23350    }
23351
23352    private void assertPackageKnown(String volumeUuid, String packageName)
23353            throws PackageManagerException {
23354        synchronized (mPackages) {
23355            // Normalize package name to handle renamed packages
23356            packageName = normalizePackageNameLPr(packageName);
23357
23358            final PackageSetting ps = mSettings.mPackages.get(packageName);
23359            if (ps == null) {
23360                throw new PackageManagerException("Package " + packageName + " is unknown");
23361            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23362                throw new PackageManagerException(
23363                        "Package " + packageName + " found on unknown volume " + volumeUuid
23364                                + "; expected volume " + ps.volumeUuid);
23365            }
23366        }
23367    }
23368
23369    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23370            throws PackageManagerException {
23371        synchronized (mPackages) {
23372            // Normalize package name to handle renamed packages
23373            packageName = normalizePackageNameLPr(packageName);
23374
23375            final PackageSetting ps = mSettings.mPackages.get(packageName);
23376            if (ps == null) {
23377                throw new PackageManagerException("Package " + packageName + " is unknown");
23378            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23379                throw new PackageManagerException(
23380                        "Package " + packageName + " found on unknown volume " + volumeUuid
23381                                + "; expected volume " + ps.volumeUuid);
23382            } else if (!ps.getInstalled(userId)) {
23383                throw new PackageManagerException(
23384                        "Package " + packageName + " not installed for user " + userId);
23385            }
23386        }
23387    }
23388
23389    private List<String> collectAbsoluteCodePaths() {
23390        synchronized (mPackages) {
23391            List<String> codePaths = new ArrayList<>();
23392            final int packageCount = mSettings.mPackages.size();
23393            for (int i = 0; i < packageCount; i++) {
23394                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23395                codePaths.add(ps.codePath.getAbsolutePath());
23396            }
23397            return codePaths;
23398        }
23399    }
23400
23401    /**
23402     * Examine all apps present on given mounted volume, and destroy apps that
23403     * aren't expected, either due to uninstallation or reinstallation on
23404     * another volume.
23405     */
23406    private void reconcileApps(String volumeUuid) {
23407        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23408        List<File> filesToDelete = null;
23409
23410        final File[] files = FileUtils.listFilesOrEmpty(
23411                Environment.getDataAppDirectory(volumeUuid));
23412        for (File file : files) {
23413            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23414                    && !PackageInstallerService.isStageName(file.getName());
23415            if (!isPackage) {
23416                // Ignore entries which are not packages
23417                continue;
23418            }
23419
23420            String absolutePath = file.getAbsolutePath();
23421
23422            boolean pathValid = false;
23423            final int absoluteCodePathCount = absoluteCodePaths.size();
23424            for (int i = 0; i < absoluteCodePathCount; i++) {
23425                String absoluteCodePath = absoluteCodePaths.get(i);
23426                if (absolutePath.startsWith(absoluteCodePath)) {
23427                    pathValid = true;
23428                    break;
23429                }
23430            }
23431
23432            if (!pathValid) {
23433                if (filesToDelete == null) {
23434                    filesToDelete = new ArrayList<>();
23435                }
23436                filesToDelete.add(file);
23437            }
23438        }
23439
23440        if (filesToDelete != null) {
23441            final int fileToDeleteCount = filesToDelete.size();
23442            for (int i = 0; i < fileToDeleteCount; i++) {
23443                File fileToDelete = filesToDelete.get(i);
23444                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23445                synchronized (mInstallLock) {
23446                    removeCodePathLI(fileToDelete);
23447                }
23448            }
23449        }
23450    }
23451
23452    /**
23453     * Reconcile all app data for the given user.
23454     * <p>
23455     * Verifies that directories exist and that ownership and labeling is
23456     * correct for all installed apps on all mounted volumes.
23457     */
23458    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23459        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23460        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23461            final String volumeUuid = vol.getFsUuid();
23462            synchronized (mInstallLock) {
23463                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23464            }
23465        }
23466    }
23467
23468    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23469            boolean migrateAppData) {
23470        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23471    }
23472
23473    /**
23474     * Reconcile all app data on given mounted volume.
23475     * <p>
23476     * Destroys app data that isn't expected, either due to uninstallation or
23477     * reinstallation on another volume.
23478     * <p>
23479     * Verifies that directories exist and that ownership and labeling is
23480     * correct for all installed apps.
23481     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23482     */
23483    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23484            boolean migrateAppData, boolean onlyCoreApps) {
23485        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23486                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23487        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23488
23489        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23490        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23491
23492        // First look for stale data that doesn't belong, and check if things
23493        // have changed since we did our last restorecon
23494        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23495            if (StorageManager.isFileEncryptedNativeOrEmulated()
23496                    && !StorageManager.isUserKeyUnlocked(userId)) {
23497                throw new RuntimeException(
23498                        "Yikes, someone asked us to reconcile CE storage while " + userId
23499                                + " was still locked; this would have caused massive data loss!");
23500            }
23501
23502            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23503            for (File file : files) {
23504                final String packageName = file.getName();
23505                try {
23506                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23507                } catch (PackageManagerException e) {
23508                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23509                    try {
23510                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23511                                StorageManager.FLAG_STORAGE_CE, 0);
23512                    } catch (InstallerException e2) {
23513                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23514                    }
23515                }
23516            }
23517        }
23518        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23519            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23520            for (File file : files) {
23521                final String packageName = file.getName();
23522                try {
23523                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23524                } catch (PackageManagerException e) {
23525                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23526                    try {
23527                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23528                                StorageManager.FLAG_STORAGE_DE, 0);
23529                    } catch (InstallerException e2) {
23530                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23531                    }
23532                }
23533            }
23534        }
23535
23536        // Ensure that data directories are ready to roll for all packages
23537        // installed for this volume and user
23538        final List<PackageSetting> packages;
23539        synchronized (mPackages) {
23540            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23541        }
23542        int preparedCount = 0;
23543        for (PackageSetting ps : packages) {
23544            final String packageName = ps.name;
23545            if (ps.pkg == null) {
23546                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23547                // TODO: might be due to legacy ASEC apps; we should circle back
23548                // and reconcile again once they're scanned
23549                continue;
23550            }
23551            // Skip non-core apps if requested
23552            if (onlyCoreApps && !ps.pkg.coreApp) {
23553                result.add(packageName);
23554                continue;
23555            }
23556
23557            if (ps.getInstalled(userId)) {
23558                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23559                preparedCount++;
23560            }
23561        }
23562
23563        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23564        return result;
23565    }
23566
23567    /**
23568     * Prepare app data for the given app just after it was installed or
23569     * upgraded. This method carefully only touches users that it's installed
23570     * for, and it forces a restorecon to handle any seinfo changes.
23571     * <p>
23572     * Verifies that directories exist and that ownership and labeling is
23573     * correct for all installed apps. If there is an ownership mismatch, it
23574     * will try recovering system apps by wiping data; third-party app data is
23575     * left intact.
23576     * <p>
23577     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23578     */
23579    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23580        final PackageSetting ps;
23581        synchronized (mPackages) {
23582            ps = mSettings.mPackages.get(pkg.packageName);
23583            mSettings.writeKernelMappingLPr(ps);
23584        }
23585
23586        final UserManager um = mContext.getSystemService(UserManager.class);
23587        UserManagerInternal umInternal = getUserManagerInternal();
23588        for (UserInfo user : um.getUsers()) {
23589            final int flags;
23590            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23591                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23592            } else if (umInternal.isUserRunning(user.id)) {
23593                flags = StorageManager.FLAG_STORAGE_DE;
23594            } else {
23595                continue;
23596            }
23597
23598            if (ps.getInstalled(user.id)) {
23599                // TODO: when user data is locked, mark that we're still dirty
23600                prepareAppDataLIF(pkg, user.id, flags);
23601            }
23602        }
23603    }
23604
23605    /**
23606     * Prepare app data for the given app.
23607     * <p>
23608     * Verifies that directories exist and that ownership and labeling is
23609     * correct for all installed apps. If there is an ownership mismatch, this
23610     * will try recovering system apps by wiping data; third-party app data is
23611     * left intact.
23612     */
23613    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23614        if (pkg == null) {
23615            Slog.wtf(TAG, "Package was null!", new Throwable());
23616            return;
23617        }
23618        prepareAppDataLeafLIF(pkg, userId, flags);
23619        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23620        for (int i = 0; i < childCount; i++) {
23621            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23622        }
23623    }
23624
23625    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23626            boolean maybeMigrateAppData) {
23627        prepareAppDataLIF(pkg, userId, flags);
23628
23629        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23630            // We may have just shuffled around app data directories, so
23631            // prepare them one more time
23632            prepareAppDataLIF(pkg, userId, flags);
23633        }
23634    }
23635
23636    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23637        if (DEBUG_APP_DATA) {
23638            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23639                    + Integer.toHexString(flags));
23640        }
23641
23642        final String volumeUuid = pkg.volumeUuid;
23643        final String packageName = pkg.packageName;
23644        final ApplicationInfo app = pkg.applicationInfo;
23645        final int appId = UserHandle.getAppId(app.uid);
23646
23647        Preconditions.checkNotNull(app.seInfo);
23648
23649        long ceDataInode = -1;
23650        try {
23651            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23652                    appId, app.seInfo, app.targetSdkVersion);
23653        } catch (InstallerException e) {
23654            if (app.isSystemApp()) {
23655                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23656                        + ", but trying to recover: " + e);
23657                destroyAppDataLeafLIF(pkg, userId, flags);
23658                try {
23659                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23660                            appId, app.seInfo, app.targetSdkVersion);
23661                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23662                } catch (InstallerException e2) {
23663                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23664                }
23665            } else {
23666                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23667            }
23668        }
23669
23670        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23671            // TODO: mark this structure as dirty so we persist it!
23672            synchronized (mPackages) {
23673                final PackageSetting ps = mSettings.mPackages.get(packageName);
23674                if (ps != null) {
23675                    ps.setCeDataInode(ceDataInode, userId);
23676                }
23677            }
23678        }
23679
23680        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23681    }
23682
23683    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23684        if (pkg == null) {
23685            Slog.wtf(TAG, "Package was null!", new Throwable());
23686            return;
23687        }
23688        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23689        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23690        for (int i = 0; i < childCount; i++) {
23691            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23692        }
23693    }
23694
23695    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23696        final String volumeUuid = pkg.volumeUuid;
23697        final String packageName = pkg.packageName;
23698        final ApplicationInfo app = pkg.applicationInfo;
23699
23700        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23701            // Create a native library symlink only if we have native libraries
23702            // and if the native libraries are 32 bit libraries. We do not provide
23703            // this symlink for 64 bit libraries.
23704            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23705                final String nativeLibPath = app.nativeLibraryDir;
23706                try {
23707                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23708                            nativeLibPath, userId);
23709                } catch (InstallerException e) {
23710                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23711                }
23712            }
23713        }
23714    }
23715
23716    /**
23717     * For system apps on non-FBE devices, this method migrates any existing
23718     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23719     * requested by the app.
23720     */
23721    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23722        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23723                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23724            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23725                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23726            try {
23727                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23728                        storageTarget);
23729            } catch (InstallerException e) {
23730                logCriticalInfo(Log.WARN,
23731                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23732            }
23733            return true;
23734        } else {
23735            return false;
23736        }
23737    }
23738
23739    public PackageFreezer freezePackage(String packageName, String killReason) {
23740        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23741    }
23742
23743    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23744        return new PackageFreezer(packageName, userId, killReason);
23745    }
23746
23747    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23748            String killReason) {
23749        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23750    }
23751
23752    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23753            String killReason) {
23754        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23755            return new PackageFreezer();
23756        } else {
23757            return freezePackage(packageName, userId, killReason);
23758        }
23759    }
23760
23761    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23762            String killReason) {
23763        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23764    }
23765
23766    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23767            String killReason) {
23768        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23769            return new PackageFreezer();
23770        } else {
23771            return freezePackage(packageName, userId, killReason);
23772        }
23773    }
23774
23775    /**
23776     * Class that freezes and kills the given package upon creation, and
23777     * unfreezes it upon closing. This is typically used when doing surgery on
23778     * app code/data to prevent the app from running while you're working.
23779     */
23780    private class PackageFreezer implements AutoCloseable {
23781        private final String mPackageName;
23782        private final PackageFreezer[] mChildren;
23783
23784        private final boolean mWeFroze;
23785
23786        private final AtomicBoolean mClosed = new AtomicBoolean();
23787        private final CloseGuard mCloseGuard = CloseGuard.get();
23788
23789        /**
23790         * Create and return a stub freezer that doesn't actually do anything,
23791         * typically used when someone requested
23792         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23793         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23794         */
23795        public PackageFreezer() {
23796            mPackageName = null;
23797            mChildren = null;
23798            mWeFroze = false;
23799            mCloseGuard.open("close");
23800        }
23801
23802        public PackageFreezer(String packageName, int userId, String killReason) {
23803            synchronized (mPackages) {
23804                mPackageName = packageName;
23805                mWeFroze = mFrozenPackages.add(mPackageName);
23806
23807                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23808                if (ps != null) {
23809                    killApplication(ps.name, ps.appId, userId, killReason);
23810                }
23811
23812                final PackageParser.Package p = mPackages.get(packageName);
23813                if (p != null && p.childPackages != null) {
23814                    final int N = p.childPackages.size();
23815                    mChildren = new PackageFreezer[N];
23816                    for (int i = 0; i < N; i++) {
23817                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23818                                userId, killReason);
23819                    }
23820                } else {
23821                    mChildren = null;
23822                }
23823            }
23824            mCloseGuard.open("close");
23825        }
23826
23827        @Override
23828        protected void finalize() throws Throwable {
23829            try {
23830                if (mCloseGuard != null) {
23831                    mCloseGuard.warnIfOpen();
23832                }
23833
23834                close();
23835            } finally {
23836                super.finalize();
23837            }
23838        }
23839
23840        @Override
23841        public void close() {
23842            mCloseGuard.close();
23843            if (mClosed.compareAndSet(false, true)) {
23844                synchronized (mPackages) {
23845                    if (mWeFroze) {
23846                        mFrozenPackages.remove(mPackageName);
23847                    }
23848
23849                    if (mChildren != null) {
23850                        for (PackageFreezer freezer : mChildren) {
23851                            freezer.close();
23852                        }
23853                    }
23854                }
23855            }
23856        }
23857    }
23858
23859    /**
23860     * Verify that given package is currently frozen.
23861     */
23862    private void checkPackageFrozen(String packageName) {
23863        synchronized (mPackages) {
23864            if (!mFrozenPackages.contains(packageName)) {
23865                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23866            }
23867        }
23868    }
23869
23870    @Override
23871    public int movePackage(final String packageName, final String volumeUuid) {
23872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23873
23874        final int callingUid = Binder.getCallingUid();
23875        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23876        final int moveId = mNextMoveId.getAndIncrement();
23877        mHandler.post(new Runnable() {
23878            @Override
23879            public void run() {
23880                try {
23881                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23882                } catch (PackageManagerException e) {
23883                    Slog.w(TAG, "Failed to move " + packageName, e);
23884                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23885                }
23886            }
23887        });
23888        return moveId;
23889    }
23890
23891    private void movePackageInternal(final String packageName, final String volumeUuid,
23892            final int moveId, final int callingUid, UserHandle user)
23893                    throws PackageManagerException {
23894        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23895        final PackageManager pm = mContext.getPackageManager();
23896
23897        final boolean currentAsec;
23898        final String currentVolumeUuid;
23899        final File codeFile;
23900        final String installerPackageName;
23901        final String packageAbiOverride;
23902        final int appId;
23903        final String seinfo;
23904        final String label;
23905        final int targetSdkVersion;
23906        final PackageFreezer freezer;
23907        final int[] installedUserIds;
23908
23909        // reader
23910        synchronized (mPackages) {
23911            final PackageParser.Package pkg = mPackages.get(packageName);
23912            final PackageSetting ps = mSettings.mPackages.get(packageName);
23913            if (pkg == null
23914                    || ps == null
23915                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23916                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23917            }
23918            if (pkg.applicationInfo.isSystemApp()) {
23919                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23920                        "Cannot move system application");
23921            }
23922
23923            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23924            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23925                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23926            if (isInternalStorage && !allow3rdPartyOnInternal) {
23927                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23928                        "3rd party apps are not allowed on internal storage");
23929            }
23930
23931            if (pkg.applicationInfo.isExternalAsec()) {
23932                currentAsec = true;
23933                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23934            } else if (pkg.applicationInfo.isForwardLocked()) {
23935                currentAsec = true;
23936                currentVolumeUuid = "forward_locked";
23937            } else {
23938                currentAsec = false;
23939                currentVolumeUuid = ps.volumeUuid;
23940
23941                final File probe = new File(pkg.codePath);
23942                final File probeOat = new File(probe, "oat");
23943                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23944                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23945                            "Move only supported for modern cluster style installs");
23946                }
23947            }
23948
23949            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23950                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23951                        "Package already moved to " + volumeUuid);
23952            }
23953            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23954                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23955                        "Device admin cannot be moved");
23956            }
23957
23958            if (mFrozenPackages.contains(packageName)) {
23959                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23960                        "Failed to move already frozen package");
23961            }
23962
23963            codeFile = new File(pkg.codePath);
23964            installerPackageName = ps.installerPackageName;
23965            packageAbiOverride = ps.cpuAbiOverrideString;
23966            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23967            seinfo = pkg.applicationInfo.seInfo;
23968            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23969            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23970            freezer = freezePackage(packageName, "movePackageInternal");
23971            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23972        }
23973
23974        final Bundle extras = new Bundle();
23975        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23976        extras.putString(Intent.EXTRA_TITLE, label);
23977        mMoveCallbacks.notifyCreated(moveId, extras);
23978
23979        int installFlags;
23980        final boolean moveCompleteApp;
23981        final File measurePath;
23982
23983        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23984            installFlags = INSTALL_INTERNAL;
23985            moveCompleteApp = !currentAsec;
23986            measurePath = Environment.getDataAppDirectory(volumeUuid);
23987        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23988            installFlags = INSTALL_EXTERNAL;
23989            moveCompleteApp = false;
23990            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23991        } else {
23992            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23993            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23994                    || !volume.isMountedWritable()) {
23995                freezer.close();
23996                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23997                        "Move location not mounted private volume");
23998            }
23999
24000            Preconditions.checkState(!currentAsec);
24001
24002            installFlags = INSTALL_INTERNAL;
24003            moveCompleteApp = true;
24004            measurePath = Environment.getDataAppDirectory(volumeUuid);
24005        }
24006
24007        // If we're moving app data around, we need all the users unlocked
24008        if (moveCompleteApp) {
24009            for (int userId : installedUserIds) {
24010                if (StorageManager.isFileEncryptedNativeOrEmulated()
24011                        && !StorageManager.isUserKeyUnlocked(userId)) {
24012                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24013                            "User " + userId + " must be unlocked");
24014                }
24015            }
24016        }
24017
24018        final PackageStats stats = new PackageStats(null, -1);
24019        synchronized (mInstaller) {
24020            for (int userId : installedUserIds) {
24021                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24022                    freezer.close();
24023                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24024                            "Failed to measure package size");
24025                }
24026            }
24027        }
24028
24029        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24030                + stats.dataSize);
24031
24032        final long startFreeBytes = measurePath.getUsableSpace();
24033        final long sizeBytes;
24034        if (moveCompleteApp) {
24035            sizeBytes = stats.codeSize + stats.dataSize;
24036        } else {
24037            sizeBytes = stats.codeSize;
24038        }
24039
24040        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24041            freezer.close();
24042            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24043                    "Not enough free space to move");
24044        }
24045
24046        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24047
24048        final CountDownLatch installedLatch = new CountDownLatch(1);
24049        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24050            @Override
24051            public void onUserActionRequired(Intent intent) throws RemoteException {
24052                throw new IllegalStateException();
24053            }
24054
24055            @Override
24056            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24057                    Bundle extras) throws RemoteException {
24058                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24059                        + PackageManager.installStatusToString(returnCode, msg));
24060
24061                installedLatch.countDown();
24062                freezer.close();
24063
24064                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24065                switch (status) {
24066                    case PackageInstaller.STATUS_SUCCESS:
24067                        mMoveCallbacks.notifyStatusChanged(moveId,
24068                                PackageManager.MOVE_SUCCEEDED);
24069                        break;
24070                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24071                        mMoveCallbacks.notifyStatusChanged(moveId,
24072                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24073                        break;
24074                    default:
24075                        mMoveCallbacks.notifyStatusChanged(moveId,
24076                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24077                        break;
24078                }
24079            }
24080        };
24081
24082        final MoveInfo move;
24083        if (moveCompleteApp) {
24084            // Kick off a thread to report progress estimates
24085            new Thread() {
24086                @Override
24087                public void run() {
24088                    while (true) {
24089                        try {
24090                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24091                                break;
24092                            }
24093                        } catch (InterruptedException ignored) {
24094                        }
24095
24096                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24097                        final int progress = 10 + (int) MathUtils.constrain(
24098                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24099                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24100                    }
24101                }
24102            }.start();
24103
24104            final String dataAppName = codeFile.getName();
24105            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24106                    dataAppName, appId, seinfo, targetSdkVersion);
24107        } else {
24108            move = null;
24109        }
24110
24111        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24112
24113        final Message msg = mHandler.obtainMessage(INIT_COPY);
24114        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24115        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24116                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24117                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24118                PackageManager.INSTALL_REASON_UNKNOWN);
24119        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24120        msg.obj = params;
24121
24122        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24123                System.identityHashCode(msg.obj));
24124        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24125                System.identityHashCode(msg.obj));
24126
24127        mHandler.sendMessage(msg);
24128    }
24129
24130    @Override
24131    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24132        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24133
24134        final int realMoveId = mNextMoveId.getAndIncrement();
24135        final Bundle extras = new Bundle();
24136        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24137        mMoveCallbacks.notifyCreated(realMoveId, extras);
24138
24139        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24140            @Override
24141            public void onCreated(int moveId, Bundle extras) {
24142                // Ignored
24143            }
24144
24145            @Override
24146            public void onStatusChanged(int moveId, int status, long estMillis) {
24147                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24148            }
24149        };
24150
24151        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24152        storage.setPrimaryStorageUuid(volumeUuid, callback);
24153        return realMoveId;
24154    }
24155
24156    @Override
24157    public int getMoveStatus(int moveId) {
24158        mContext.enforceCallingOrSelfPermission(
24159                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24160        return mMoveCallbacks.mLastStatus.get(moveId);
24161    }
24162
24163    @Override
24164    public void registerMoveCallback(IPackageMoveObserver callback) {
24165        mContext.enforceCallingOrSelfPermission(
24166                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24167        mMoveCallbacks.register(callback);
24168    }
24169
24170    @Override
24171    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24172        mContext.enforceCallingOrSelfPermission(
24173                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24174        mMoveCallbacks.unregister(callback);
24175    }
24176
24177    @Override
24178    public boolean setInstallLocation(int loc) {
24179        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24180                null);
24181        if (getInstallLocation() == loc) {
24182            return true;
24183        }
24184        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24185                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24186            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24187                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24188            return true;
24189        }
24190        return false;
24191   }
24192
24193    @Override
24194    public int getInstallLocation() {
24195        // allow instant app access
24196        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24197                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24198                PackageHelper.APP_INSTALL_AUTO);
24199    }
24200
24201    /** Called by UserManagerService */
24202    void cleanUpUser(UserManagerService userManager, int userHandle) {
24203        synchronized (mPackages) {
24204            mDirtyUsers.remove(userHandle);
24205            mUserNeedsBadging.delete(userHandle);
24206            mSettings.removeUserLPw(userHandle);
24207            mPendingBroadcasts.remove(userHandle);
24208            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24209            removeUnusedPackagesLPw(userManager, userHandle);
24210        }
24211    }
24212
24213    /**
24214     * We're removing userHandle and would like to remove any downloaded packages
24215     * that are no longer in use by any other user.
24216     * @param userHandle the user being removed
24217     */
24218    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24219        final boolean DEBUG_CLEAN_APKS = false;
24220        int [] users = userManager.getUserIds();
24221        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24222        while (psit.hasNext()) {
24223            PackageSetting ps = psit.next();
24224            if (ps.pkg == null) {
24225                continue;
24226            }
24227            final String packageName = ps.pkg.packageName;
24228            // Skip over if system app
24229            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24230                continue;
24231            }
24232            if (DEBUG_CLEAN_APKS) {
24233                Slog.i(TAG, "Checking package " + packageName);
24234            }
24235            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24236            if (keep) {
24237                if (DEBUG_CLEAN_APKS) {
24238                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24239                }
24240            } else {
24241                for (int i = 0; i < users.length; i++) {
24242                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24243                        keep = true;
24244                        if (DEBUG_CLEAN_APKS) {
24245                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24246                                    + users[i]);
24247                        }
24248                        break;
24249                    }
24250                }
24251            }
24252            if (!keep) {
24253                if (DEBUG_CLEAN_APKS) {
24254                    Slog.i(TAG, "  Removing package " + packageName);
24255                }
24256                mHandler.post(new Runnable() {
24257                    public void run() {
24258                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24259                                userHandle, 0);
24260                    } //end run
24261                });
24262            }
24263        }
24264    }
24265
24266    /** Called by UserManagerService */
24267    void createNewUser(int userId, String[] disallowedPackages) {
24268        synchronized (mInstallLock) {
24269            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24270        }
24271        synchronized (mPackages) {
24272            scheduleWritePackageRestrictionsLocked(userId);
24273            scheduleWritePackageListLocked(userId);
24274            applyFactoryDefaultBrowserLPw(userId);
24275            primeDomainVerificationsLPw(userId);
24276        }
24277    }
24278
24279    void onNewUserCreated(final int userId) {
24280        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24281        // If permission review for legacy apps is required, we represent
24282        // dagerous permissions for such apps as always granted runtime
24283        // permissions to keep per user flag state whether review is needed.
24284        // Hence, if a new user is added we have to propagate dangerous
24285        // permission grants for these legacy apps.
24286        if (mPermissionReviewRequired) {
24287            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24288                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24289        }
24290    }
24291
24292    @Override
24293    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24294        mContext.enforceCallingOrSelfPermission(
24295                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24296                "Only package verification agents can read the verifier device identity");
24297
24298        synchronized (mPackages) {
24299            return mSettings.getVerifierDeviceIdentityLPw();
24300        }
24301    }
24302
24303    @Override
24304    public void setPermissionEnforced(String permission, boolean enforced) {
24305        // TODO: Now that we no longer change GID for storage, this should to away.
24306        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24307                "setPermissionEnforced");
24308        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24309            synchronized (mPackages) {
24310                if (mSettings.mReadExternalStorageEnforced == null
24311                        || mSettings.mReadExternalStorageEnforced != enforced) {
24312                    mSettings.mReadExternalStorageEnforced = enforced;
24313                    mSettings.writeLPr();
24314                }
24315            }
24316            // kill any non-foreground processes so we restart them and
24317            // grant/revoke the GID.
24318            final IActivityManager am = ActivityManager.getService();
24319            if (am != null) {
24320                final long token = Binder.clearCallingIdentity();
24321                try {
24322                    am.killProcessesBelowForeground("setPermissionEnforcement");
24323                } catch (RemoteException e) {
24324                } finally {
24325                    Binder.restoreCallingIdentity(token);
24326                }
24327            }
24328        } else {
24329            throw new IllegalArgumentException("No selective enforcement for " + permission);
24330        }
24331    }
24332
24333    @Override
24334    @Deprecated
24335    public boolean isPermissionEnforced(String permission) {
24336        // allow instant applications
24337        return true;
24338    }
24339
24340    @Override
24341    public boolean isStorageLow() {
24342        // allow instant applications
24343        final long token = Binder.clearCallingIdentity();
24344        try {
24345            final DeviceStorageMonitorInternal
24346                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24347            if (dsm != null) {
24348                return dsm.isMemoryLow();
24349            } else {
24350                return false;
24351            }
24352        } finally {
24353            Binder.restoreCallingIdentity(token);
24354        }
24355    }
24356
24357    @Override
24358    public IPackageInstaller getPackageInstaller() {
24359        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24360            return null;
24361        }
24362        return mInstallerService;
24363    }
24364
24365    private boolean userNeedsBadging(int userId) {
24366        int index = mUserNeedsBadging.indexOfKey(userId);
24367        if (index < 0) {
24368            final UserInfo userInfo;
24369            final long token = Binder.clearCallingIdentity();
24370            try {
24371                userInfo = sUserManager.getUserInfo(userId);
24372            } finally {
24373                Binder.restoreCallingIdentity(token);
24374            }
24375            final boolean b;
24376            if (userInfo != null && userInfo.isManagedProfile()) {
24377                b = true;
24378            } else {
24379                b = false;
24380            }
24381            mUserNeedsBadging.put(userId, b);
24382            return b;
24383        }
24384        return mUserNeedsBadging.valueAt(index);
24385    }
24386
24387    @Override
24388    public KeySet getKeySetByAlias(String packageName, String alias) {
24389        if (packageName == null || alias == null) {
24390            return null;
24391        }
24392        synchronized(mPackages) {
24393            final PackageParser.Package pkg = mPackages.get(packageName);
24394            if (pkg == null) {
24395                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24396                throw new IllegalArgumentException("Unknown package: " + packageName);
24397            }
24398            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24399            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24400                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24401                throw new IllegalArgumentException("Unknown package: " + packageName);
24402            }
24403            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24404            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24405        }
24406    }
24407
24408    @Override
24409    public KeySet getSigningKeySet(String packageName) {
24410        if (packageName == null) {
24411            return null;
24412        }
24413        synchronized(mPackages) {
24414            final int callingUid = Binder.getCallingUid();
24415            final int callingUserId = UserHandle.getUserId(callingUid);
24416            final PackageParser.Package pkg = mPackages.get(packageName);
24417            if (pkg == null) {
24418                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24419                throw new IllegalArgumentException("Unknown package: " + packageName);
24420            }
24421            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24422            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24423                // filter and pretend the package doesn't exist
24424                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24425                        + ", uid:" + callingUid);
24426                throw new IllegalArgumentException("Unknown package: " + packageName);
24427            }
24428            if (pkg.applicationInfo.uid != callingUid
24429                    && Process.SYSTEM_UID != callingUid) {
24430                throw new SecurityException("May not access signing KeySet of other apps.");
24431            }
24432            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24433            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24434        }
24435    }
24436
24437    @Override
24438    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24439        final int callingUid = Binder.getCallingUid();
24440        if (getInstantAppPackageName(callingUid) != null) {
24441            return false;
24442        }
24443        if (packageName == null || ks == null) {
24444            return false;
24445        }
24446        synchronized(mPackages) {
24447            final PackageParser.Package pkg = mPackages.get(packageName);
24448            if (pkg == null
24449                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24450                            UserHandle.getUserId(callingUid))) {
24451                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24452                throw new IllegalArgumentException("Unknown package: " + packageName);
24453            }
24454            IBinder ksh = ks.getToken();
24455            if (ksh instanceof KeySetHandle) {
24456                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24457                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24458            }
24459            return false;
24460        }
24461    }
24462
24463    @Override
24464    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24465        final int callingUid = Binder.getCallingUid();
24466        if (getInstantAppPackageName(callingUid) != null) {
24467            return false;
24468        }
24469        if (packageName == null || ks == null) {
24470            return false;
24471        }
24472        synchronized(mPackages) {
24473            final PackageParser.Package pkg = mPackages.get(packageName);
24474            if (pkg == null
24475                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24476                            UserHandle.getUserId(callingUid))) {
24477                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24478                throw new IllegalArgumentException("Unknown package: " + packageName);
24479            }
24480            IBinder ksh = ks.getToken();
24481            if (ksh instanceof KeySetHandle) {
24482                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24483                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24484            }
24485            return false;
24486        }
24487    }
24488
24489    private void deletePackageIfUnusedLPr(final String packageName) {
24490        PackageSetting ps = mSettings.mPackages.get(packageName);
24491        if (ps == null) {
24492            return;
24493        }
24494        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24495            // TODO Implement atomic delete if package is unused
24496            // It is currently possible that the package will be deleted even if it is installed
24497            // after this method returns.
24498            mHandler.post(new Runnable() {
24499                public void run() {
24500                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24501                            0, PackageManager.DELETE_ALL_USERS);
24502                }
24503            });
24504        }
24505    }
24506
24507    /**
24508     * Check and throw if the given before/after packages would be considered a
24509     * downgrade.
24510     */
24511    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24512            throws PackageManagerException {
24513        if (after.versionCode < before.mVersionCode) {
24514            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24515                    "Update version code " + after.versionCode + " is older than current "
24516                    + before.mVersionCode);
24517        } else if (after.versionCode == before.mVersionCode) {
24518            if (after.baseRevisionCode < before.baseRevisionCode) {
24519                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24520                        "Update base revision code " + after.baseRevisionCode
24521                        + " is older than current " + before.baseRevisionCode);
24522            }
24523
24524            if (!ArrayUtils.isEmpty(after.splitNames)) {
24525                for (int i = 0; i < after.splitNames.length; i++) {
24526                    final String splitName = after.splitNames[i];
24527                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24528                    if (j != -1) {
24529                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24530                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24531                                    "Update split " + splitName + " revision code "
24532                                    + after.splitRevisionCodes[i] + " is older than current "
24533                                    + before.splitRevisionCodes[j]);
24534                        }
24535                    }
24536                }
24537            }
24538        }
24539    }
24540
24541    private static class MoveCallbacks extends Handler {
24542        private static final int MSG_CREATED = 1;
24543        private static final int MSG_STATUS_CHANGED = 2;
24544
24545        private final RemoteCallbackList<IPackageMoveObserver>
24546                mCallbacks = new RemoteCallbackList<>();
24547
24548        private final SparseIntArray mLastStatus = new SparseIntArray();
24549
24550        public MoveCallbacks(Looper looper) {
24551            super(looper);
24552        }
24553
24554        public void register(IPackageMoveObserver callback) {
24555            mCallbacks.register(callback);
24556        }
24557
24558        public void unregister(IPackageMoveObserver callback) {
24559            mCallbacks.unregister(callback);
24560        }
24561
24562        @Override
24563        public void handleMessage(Message msg) {
24564            final SomeArgs args = (SomeArgs) msg.obj;
24565            final int n = mCallbacks.beginBroadcast();
24566            for (int i = 0; i < n; i++) {
24567                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24568                try {
24569                    invokeCallback(callback, msg.what, args);
24570                } catch (RemoteException ignored) {
24571                }
24572            }
24573            mCallbacks.finishBroadcast();
24574            args.recycle();
24575        }
24576
24577        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24578                throws RemoteException {
24579            switch (what) {
24580                case MSG_CREATED: {
24581                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24582                    break;
24583                }
24584                case MSG_STATUS_CHANGED: {
24585                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24586                    break;
24587                }
24588            }
24589        }
24590
24591        private void notifyCreated(int moveId, Bundle extras) {
24592            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24593
24594            final SomeArgs args = SomeArgs.obtain();
24595            args.argi1 = moveId;
24596            args.arg2 = extras;
24597            obtainMessage(MSG_CREATED, args).sendToTarget();
24598        }
24599
24600        private void notifyStatusChanged(int moveId, int status) {
24601            notifyStatusChanged(moveId, status, -1);
24602        }
24603
24604        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24605            Slog.v(TAG, "Move " + moveId + " status " + status);
24606
24607            final SomeArgs args = SomeArgs.obtain();
24608            args.argi1 = moveId;
24609            args.argi2 = status;
24610            args.arg3 = estMillis;
24611            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24612
24613            synchronized (mLastStatus) {
24614                mLastStatus.put(moveId, status);
24615            }
24616        }
24617    }
24618
24619    private final static class OnPermissionChangeListeners extends Handler {
24620        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24621
24622        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24623                new RemoteCallbackList<>();
24624
24625        public OnPermissionChangeListeners(Looper looper) {
24626            super(looper);
24627        }
24628
24629        @Override
24630        public void handleMessage(Message msg) {
24631            switch (msg.what) {
24632                case MSG_ON_PERMISSIONS_CHANGED: {
24633                    final int uid = msg.arg1;
24634                    handleOnPermissionsChanged(uid);
24635                } break;
24636            }
24637        }
24638
24639        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24640            mPermissionListeners.register(listener);
24641
24642        }
24643
24644        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24645            mPermissionListeners.unregister(listener);
24646        }
24647
24648        public void onPermissionsChanged(int uid) {
24649            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24650                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24651            }
24652        }
24653
24654        private void handleOnPermissionsChanged(int uid) {
24655            final int count = mPermissionListeners.beginBroadcast();
24656            try {
24657                for (int i = 0; i < count; i++) {
24658                    IOnPermissionsChangeListener callback = mPermissionListeners
24659                            .getBroadcastItem(i);
24660                    try {
24661                        callback.onPermissionsChanged(uid);
24662                    } catch (RemoteException e) {
24663                        Log.e(TAG, "Permission listener is dead", e);
24664                    }
24665                }
24666            } finally {
24667                mPermissionListeners.finishBroadcast();
24668            }
24669        }
24670    }
24671
24672    private class PackageManagerInternalImpl extends PackageManagerInternal {
24673        @Override
24674        public void setLocationPackagesProvider(PackagesProvider provider) {
24675            synchronized (mPackages) {
24676                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24677            }
24678        }
24679
24680        @Override
24681        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24682            synchronized (mPackages) {
24683                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24684            }
24685        }
24686
24687        @Override
24688        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24689            synchronized (mPackages) {
24690                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24691            }
24692        }
24693
24694        @Override
24695        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24696            synchronized (mPackages) {
24697                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24698            }
24699        }
24700
24701        @Override
24702        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24703            synchronized (mPackages) {
24704                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24705            }
24706        }
24707
24708        @Override
24709        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24710            synchronized (mPackages) {
24711                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24712            }
24713        }
24714
24715        @Override
24716        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24717            synchronized (mPackages) {
24718                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24719                        packageName, userId);
24720            }
24721        }
24722
24723        @Override
24724        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24725            synchronized (mPackages) {
24726                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24727                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24728                        packageName, userId);
24729            }
24730        }
24731
24732        @Override
24733        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24734            synchronized (mPackages) {
24735                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24736                        packageName, userId);
24737            }
24738        }
24739
24740        @Override
24741        public void setKeepUninstalledPackages(final List<String> packageList) {
24742            Preconditions.checkNotNull(packageList);
24743            List<String> removedFromList = null;
24744            synchronized (mPackages) {
24745                if (mKeepUninstalledPackages != null) {
24746                    final int packagesCount = mKeepUninstalledPackages.size();
24747                    for (int i = 0; i < packagesCount; i++) {
24748                        String oldPackage = mKeepUninstalledPackages.get(i);
24749                        if (packageList != null && packageList.contains(oldPackage)) {
24750                            continue;
24751                        }
24752                        if (removedFromList == null) {
24753                            removedFromList = new ArrayList<>();
24754                        }
24755                        removedFromList.add(oldPackage);
24756                    }
24757                }
24758                mKeepUninstalledPackages = new ArrayList<>(packageList);
24759                if (removedFromList != null) {
24760                    final int removedCount = removedFromList.size();
24761                    for (int i = 0; i < removedCount; i++) {
24762                        deletePackageIfUnusedLPr(removedFromList.get(i));
24763                    }
24764                }
24765            }
24766        }
24767
24768        @Override
24769        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24770            synchronized (mPackages) {
24771                // If we do not support permission review, done.
24772                if (!mPermissionReviewRequired) {
24773                    return false;
24774                }
24775
24776                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24777                if (packageSetting == null) {
24778                    return false;
24779                }
24780
24781                // Permission review applies only to apps not supporting the new permission model.
24782                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24783                    return false;
24784                }
24785
24786                // Legacy apps have the permission and get user consent on launch.
24787                PermissionsState permissionsState = packageSetting.getPermissionsState();
24788                return permissionsState.isPermissionReviewRequired(userId);
24789            }
24790        }
24791
24792        @Override
24793        public PackageInfo getPackageInfo(
24794                String packageName, int flags, int filterCallingUid, int userId) {
24795            return PackageManagerService.this
24796                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24797                            flags, filterCallingUid, userId);
24798        }
24799
24800        @Override
24801        public ApplicationInfo getApplicationInfo(
24802                String packageName, int flags, int filterCallingUid, int userId) {
24803            return PackageManagerService.this
24804                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24805        }
24806
24807        @Override
24808        public ActivityInfo getActivityInfo(
24809                ComponentName component, int flags, int filterCallingUid, int userId) {
24810            return PackageManagerService.this
24811                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24812        }
24813
24814        @Override
24815        public List<ResolveInfo> queryIntentActivities(
24816                Intent intent, int flags, int filterCallingUid, int userId) {
24817            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24818            return PackageManagerService.this
24819                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24820                            userId, false /*resolveForStart*/);
24821        }
24822
24823        @Override
24824        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24825                int userId) {
24826            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24827        }
24828
24829        @Override
24830        public void setDeviceAndProfileOwnerPackages(
24831                int deviceOwnerUserId, String deviceOwnerPackage,
24832                SparseArray<String> profileOwnerPackages) {
24833            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24834                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24835        }
24836
24837        @Override
24838        public boolean isPackageDataProtected(int userId, String packageName) {
24839            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24840        }
24841
24842        @Override
24843        public boolean isPackageEphemeral(int userId, String packageName) {
24844            synchronized (mPackages) {
24845                final PackageSetting ps = mSettings.mPackages.get(packageName);
24846                return ps != null ? ps.getInstantApp(userId) : false;
24847            }
24848        }
24849
24850        @Override
24851        public boolean wasPackageEverLaunched(String packageName, int userId) {
24852            synchronized (mPackages) {
24853                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24854            }
24855        }
24856
24857        @Override
24858        public void grantRuntimePermission(String packageName, String name, int userId,
24859                boolean overridePolicy) {
24860            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24861                    overridePolicy);
24862        }
24863
24864        @Override
24865        public void revokeRuntimePermission(String packageName, String name, int userId,
24866                boolean overridePolicy) {
24867            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24868                    overridePolicy);
24869        }
24870
24871        @Override
24872        public String getNameForUid(int uid) {
24873            return PackageManagerService.this.getNameForUid(uid);
24874        }
24875
24876        @Override
24877        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24878                Intent origIntent, String resolvedType, String callingPackage,
24879                Bundle verificationBundle, int userId) {
24880            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24881                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24882                    userId);
24883        }
24884
24885        @Override
24886        public void grantEphemeralAccess(int userId, Intent intent,
24887                int targetAppId, int ephemeralAppId) {
24888            synchronized (mPackages) {
24889                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24890                        targetAppId, ephemeralAppId);
24891            }
24892        }
24893
24894        @Override
24895        public boolean isInstantAppInstallerComponent(ComponentName component) {
24896            synchronized (mPackages) {
24897                return mInstantAppInstallerActivity != null
24898                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24899            }
24900        }
24901
24902        @Override
24903        public void pruneInstantApps() {
24904            mInstantAppRegistry.pruneInstantApps();
24905        }
24906
24907        @Override
24908        public String getSetupWizardPackageName() {
24909            return mSetupWizardPackage;
24910        }
24911
24912        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24913            if (policy != null) {
24914                mExternalSourcesPolicy = policy;
24915            }
24916        }
24917
24918        @Override
24919        public boolean isPackagePersistent(String packageName) {
24920            synchronized (mPackages) {
24921                PackageParser.Package pkg = mPackages.get(packageName);
24922                return pkg != null
24923                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24924                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24925                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24926                        : false;
24927            }
24928        }
24929
24930        @Override
24931        public List<PackageInfo> getOverlayPackages(int userId) {
24932            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24933            synchronized (mPackages) {
24934                for (PackageParser.Package p : mPackages.values()) {
24935                    if (p.mOverlayTarget != null) {
24936                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24937                        if (pkg != null) {
24938                            overlayPackages.add(pkg);
24939                        }
24940                    }
24941                }
24942            }
24943            return overlayPackages;
24944        }
24945
24946        @Override
24947        public List<String> getTargetPackageNames(int userId) {
24948            List<String> targetPackages = new ArrayList<>();
24949            synchronized (mPackages) {
24950                for (PackageParser.Package p : mPackages.values()) {
24951                    if (p.mOverlayTarget == null) {
24952                        targetPackages.add(p.packageName);
24953                    }
24954                }
24955            }
24956            return targetPackages;
24957        }
24958
24959        @Override
24960        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24961                @Nullable List<String> overlayPackageNames) {
24962            synchronized (mPackages) {
24963                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24964                    Slog.e(TAG, "failed to find package " + targetPackageName);
24965                    return false;
24966                }
24967                ArrayList<String> overlayPaths = null;
24968                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24969                    final int N = overlayPackageNames.size();
24970                    overlayPaths = new ArrayList<>(N);
24971                    for (int i = 0; i < N; i++) {
24972                        final String packageName = overlayPackageNames.get(i);
24973                        final PackageParser.Package pkg = mPackages.get(packageName);
24974                        if (pkg == null) {
24975                            Slog.e(TAG, "failed to find package " + packageName);
24976                            return false;
24977                        }
24978                        overlayPaths.add(pkg.baseCodePath);
24979                    }
24980                }
24981
24982                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24983                ps.setOverlayPaths(overlayPaths, userId);
24984                return true;
24985            }
24986        }
24987
24988        @Override
24989        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24990                int flags, int userId) {
24991            return resolveIntentInternal(
24992                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24993        }
24994
24995        @Override
24996        public ResolveInfo resolveService(Intent intent, String resolvedType,
24997                int flags, int userId, int callingUid) {
24998            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24999        }
25000
25001        @Override
25002        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25003            synchronized (mPackages) {
25004                mIsolatedOwners.put(isolatedUid, ownerUid);
25005            }
25006        }
25007
25008        @Override
25009        public void removeIsolatedUid(int isolatedUid) {
25010            synchronized (mPackages) {
25011                mIsolatedOwners.delete(isolatedUid);
25012            }
25013        }
25014
25015        @Override
25016        public int getUidTargetSdkVersion(int uid) {
25017            synchronized (mPackages) {
25018                return getUidTargetSdkVersionLockedLPr(uid);
25019            }
25020        }
25021
25022        @Override
25023        public boolean canAccessInstantApps(int callingUid, int userId) {
25024            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25025        }
25026    }
25027
25028    @Override
25029    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25030        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25031        synchronized (mPackages) {
25032            final long identity = Binder.clearCallingIdentity();
25033            try {
25034                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25035                        packageNames, userId);
25036            } finally {
25037                Binder.restoreCallingIdentity(identity);
25038            }
25039        }
25040    }
25041
25042    @Override
25043    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25044        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25045        synchronized (mPackages) {
25046            final long identity = Binder.clearCallingIdentity();
25047            try {
25048                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25049                        packageNames, userId);
25050            } finally {
25051                Binder.restoreCallingIdentity(identity);
25052            }
25053        }
25054    }
25055
25056    private static void enforceSystemOrPhoneCaller(String tag) {
25057        int callingUid = Binder.getCallingUid();
25058        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25059            throw new SecurityException(
25060                    "Cannot call " + tag + " from UID " + callingUid);
25061        }
25062    }
25063
25064    boolean isHistoricalPackageUsageAvailable() {
25065        return mPackageUsage.isHistoricalPackageUsageAvailable();
25066    }
25067
25068    /**
25069     * Return a <b>copy</b> of the collection of packages known to the package manager.
25070     * @return A copy of the values of mPackages.
25071     */
25072    Collection<PackageParser.Package> getPackages() {
25073        synchronized (mPackages) {
25074            return new ArrayList<>(mPackages.values());
25075        }
25076    }
25077
25078    /**
25079     * Logs process start information (including base APK hash) to the security log.
25080     * @hide
25081     */
25082    @Override
25083    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25084            String apkFile, int pid) {
25085        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25086            return;
25087        }
25088        if (!SecurityLog.isLoggingEnabled()) {
25089            return;
25090        }
25091        Bundle data = new Bundle();
25092        data.putLong("startTimestamp", System.currentTimeMillis());
25093        data.putString("processName", processName);
25094        data.putInt("uid", uid);
25095        data.putString("seinfo", seinfo);
25096        data.putString("apkFile", apkFile);
25097        data.putInt("pid", pid);
25098        Message msg = mProcessLoggingHandler.obtainMessage(
25099                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25100        msg.setData(data);
25101        mProcessLoggingHandler.sendMessage(msg);
25102    }
25103
25104    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25105        return mCompilerStats.getPackageStats(pkgName);
25106    }
25107
25108    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25109        return getOrCreateCompilerPackageStats(pkg.packageName);
25110    }
25111
25112    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25113        return mCompilerStats.getOrCreatePackageStats(pkgName);
25114    }
25115
25116    public void deleteCompilerPackageStats(String pkgName) {
25117        mCompilerStats.deletePackageStats(pkgName);
25118    }
25119
25120    @Override
25121    public int getInstallReason(String packageName, int userId) {
25122        final int callingUid = Binder.getCallingUid();
25123        enforceCrossUserPermission(callingUid, userId,
25124                true /* requireFullPermission */, false /* checkShell */,
25125                "get install reason");
25126        synchronized (mPackages) {
25127            final PackageSetting ps = mSettings.mPackages.get(packageName);
25128            if (filterAppAccessLPr(ps, callingUid, userId)) {
25129                return PackageManager.INSTALL_REASON_UNKNOWN;
25130            }
25131            if (ps != null) {
25132                return ps.getInstallReason(userId);
25133            }
25134        }
25135        return PackageManager.INSTALL_REASON_UNKNOWN;
25136    }
25137
25138    @Override
25139    public boolean canRequestPackageInstalls(String packageName, int userId) {
25140        return canRequestPackageInstallsInternal(packageName, 0, userId,
25141                true /* throwIfPermNotDeclared*/);
25142    }
25143
25144    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25145            boolean throwIfPermNotDeclared) {
25146        int callingUid = Binder.getCallingUid();
25147        int uid = getPackageUid(packageName, 0, userId);
25148        if (callingUid != uid && callingUid != Process.ROOT_UID
25149                && callingUid != Process.SYSTEM_UID) {
25150            throw new SecurityException(
25151                    "Caller uid " + callingUid + " does not own package " + packageName);
25152        }
25153        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25154        if (info == null) {
25155            return false;
25156        }
25157        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25158            return false;
25159        }
25160        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25161        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25162        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25163            if (throwIfPermNotDeclared) {
25164                throw new SecurityException("Need to declare " + appOpPermission
25165                        + " to call this api");
25166            } else {
25167                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25168                return false;
25169            }
25170        }
25171        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25172            return false;
25173        }
25174        if (mExternalSourcesPolicy != null) {
25175            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25176            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25177                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25178            }
25179        }
25180        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25181    }
25182
25183    @Override
25184    public ComponentName getInstantAppResolverSettingsComponent() {
25185        return mInstantAppResolverSettingsComponent;
25186    }
25187
25188    @Override
25189    public ComponentName getInstantAppInstallerComponent() {
25190        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25191            return null;
25192        }
25193        return mInstantAppInstallerActivity == null
25194                ? null : mInstantAppInstallerActivity.getComponentName();
25195    }
25196
25197    @Override
25198    public String getInstantAppAndroidId(String packageName, int userId) {
25199        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25200                "getInstantAppAndroidId");
25201        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25202                true /* requireFullPermission */, false /* checkShell */,
25203                "getInstantAppAndroidId");
25204        // Make sure the target is an Instant App.
25205        if (!isInstantApp(packageName, userId)) {
25206            return null;
25207        }
25208        synchronized (mPackages) {
25209            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25210        }
25211    }
25212
25213    boolean canHaveOatDir(String packageName) {
25214        synchronized (mPackages) {
25215            PackageParser.Package p = mPackages.get(packageName);
25216            if (p == null) {
25217                return false;
25218            }
25219            return p.canHaveOatDir();
25220        }
25221    }
25222
25223    private String getOatDir(PackageParser.Package pkg) {
25224        if (!pkg.canHaveOatDir()) {
25225            return null;
25226        }
25227        File codePath = new File(pkg.codePath);
25228        if (codePath.isDirectory()) {
25229            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25230        }
25231        return null;
25232    }
25233
25234    void deleteOatArtifactsOfPackage(String packageName) {
25235        final String[] instructionSets;
25236        final List<String> codePaths;
25237        final String oatDir;
25238        final PackageParser.Package pkg;
25239        synchronized (mPackages) {
25240            pkg = mPackages.get(packageName);
25241        }
25242        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25243        codePaths = pkg.getAllCodePaths();
25244        oatDir = getOatDir(pkg);
25245
25246        for (String codePath : codePaths) {
25247            for (String isa : instructionSets) {
25248                try {
25249                    mInstaller.deleteOdex(codePath, isa, oatDir);
25250                } catch (InstallerException e) {
25251                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25252                }
25253            }
25254        }
25255    }
25256
25257    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25258        Set<String> unusedPackages = new HashSet<>();
25259        long currentTimeInMillis = System.currentTimeMillis();
25260        synchronized (mPackages) {
25261            for (PackageParser.Package pkg : mPackages.values()) {
25262                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25263                if (ps == null) {
25264                    continue;
25265                }
25266                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25267                        pkg.packageName);
25268                if (PackageManagerServiceUtils
25269                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25270                                downgradeTimeThresholdMillis, packageUseInfo,
25271                                pkg.getLatestPackageUseTimeInMills(),
25272                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25273                    unusedPackages.add(pkg.packageName);
25274                }
25275            }
25276        }
25277        return unusedPackages;
25278    }
25279}
25280
25281interface PackageSender {
25282    void sendPackageBroadcast(final String action, final String pkg,
25283        final Bundle extras, final int flags, final String targetPkg,
25284        final IIntentReceiver finishedReceiver, final int[] userIds);
25285    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25286        int appId, int... userIds);
25287}
25288