PackageManagerService.java revision 1b37daa810c929938a642f56cb7aeb75c4f89766
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.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.TimingsTraceLog;
233import android.util.DisplayMetrics;
234import android.util.EventLog;
235import android.util.ExceptionUtils;
236import android.util.Log;
237import android.util.LogPrinter;
238import android.util.MathUtils;
239import android.util.PackageUtils;
240import android.util.Pair;
241import android.util.PrintStreamPrinter;
242import android.util.Slog;
243import android.util.SparseArray;
244import android.util.SparseBooleanArray;
245import android.util.SparseIntArray;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexLogger;
289import com.android.server.pm.dex.DexManager;
290import com.android.server.pm.dex.DexoptOptions;
291import com.android.server.pm.dex.PackageDexUsage;
292import com.android.server.storage.DeviceStorageMonitorInternal;
293
294import dalvik.system.CloseGuard;
295import dalvik.system.DexFile;
296import dalvik.system.VMRuntime;
297
298import libcore.io.IoUtils;
299import libcore.io.Streams;
300import libcore.util.EmptyArray;
301
302import org.xmlpull.v1.XmlPullParser;
303import org.xmlpull.v1.XmlPullParserException;
304import org.xmlpull.v1.XmlSerializer;
305
306import java.io.BufferedOutputStream;
307import java.io.BufferedReader;
308import java.io.ByteArrayInputStream;
309import java.io.ByteArrayOutputStream;
310import java.io.File;
311import java.io.FileDescriptor;
312import java.io.FileInputStream;
313import java.io.FileOutputStream;
314import java.io.FileReader;
315import java.io.FilenameFilter;
316import java.io.IOException;
317import java.io.InputStream;
318import java.io.OutputStream;
319import java.io.PrintWriter;
320import java.lang.annotation.Retention;
321import java.lang.annotation.RetentionPolicy;
322import java.nio.charset.StandardCharsets;
323import java.security.DigestInputStream;
324import java.security.MessageDigest;
325import java.security.NoSuchAlgorithmException;
326import java.security.PublicKey;
327import java.security.SecureRandom;
328import java.security.cert.Certificate;
329import java.security.cert.CertificateEncodingException;
330import java.security.cert.CertificateException;
331import java.text.SimpleDateFormat;
332import java.util.ArrayList;
333import java.util.Arrays;
334import java.util.Collection;
335import java.util.Collections;
336import java.util.Comparator;
337import java.util.Date;
338import java.util.HashMap;
339import java.util.HashSet;
340import java.util.Iterator;
341import java.util.LinkedHashSet;
342import java.util.List;
343import java.util.Map;
344import java.util.Objects;
345import java.util.Set;
346import java.util.concurrent.CountDownLatch;
347import java.util.concurrent.Future;
348import java.util.concurrent.TimeUnit;
349import java.util.concurrent.atomic.AtomicBoolean;
350import java.util.concurrent.atomic.AtomicInteger;
351import java.util.zip.GZIPInputStream;
352
353/**
354 * Keep track of all those APKs everywhere.
355 * <p>
356 * Internally there are two important locks:
357 * <ul>
358 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
359 * and other related state. It is a fine-grained lock that should only be held
360 * momentarily, as it's one of the most contended locks in the system.
361 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
362 * operations typically involve heavy lifting of application data on disk. Since
363 * {@code installd} is single-threaded, and it's operations can often be slow,
364 * this lock should never be acquired while already holding {@link #mPackages}.
365 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
366 * holding {@link #mInstallLock}.
367 * </ul>
368 * Many internal methods rely on the caller to hold the appropriate locks, and
369 * this contract is expressed through method name suffixes:
370 * <ul>
371 * <li>fooLI(): the caller must hold {@link #mInstallLock}
372 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
373 * being modified must be frozen
374 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
375 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
376 * </ul>
377 * <p>
378 * Because this class is very central to the platform's security; please run all
379 * CTS and unit tests whenever making modifications:
380 *
381 * <pre>
382 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
383 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
384 * </pre>
385 */
386public class PackageManagerService extends IPackageManager.Stub
387        implements PackageSender {
388    static final String TAG = "PackageManager";
389    static final boolean DEBUG_SETTINGS = false;
390    static final boolean DEBUG_PREFERRED = false;
391    static final boolean DEBUG_UPGRADE = false;
392    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
393    private static final boolean DEBUG_BACKUP = false;
394    private static final boolean DEBUG_INSTALL = false;
395    private static final boolean DEBUG_REMOVE = false;
396    private static final boolean DEBUG_BROADCASTS = false;
397    private static final boolean DEBUG_SHOW_INFO = false;
398    private static final boolean DEBUG_PACKAGE_INFO = false;
399    private static final boolean DEBUG_INTENT_MATCHING = false;
400    private static final boolean DEBUG_PACKAGE_SCANNING = false;
401    private static final boolean DEBUG_VERIFY = false;
402    private static final boolean DEBUG_FILTERS = false;
403    private static final boolean DEBUG_PERMISSIONS = false;
404    private static final boolean DEBUG_SHARED_LIBRARIES = false;
405    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
406
407    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
408    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
409    // user, but by default initialize to this.
410    public static final boolean DEBUG_DEXOPT = false;
411
412    private static final boolean DEBUG_ABI_SELECTION = false;
413    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
414    private static final boolean DEBUG_TRIAGED_MISSING = false;
415    private static final boolean DEBUG_APP_DATA = false;
416
417    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
418    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
419
420    private static final boolean HIDE_EPHEMERAL_APIS = false;
421
422    private static final boolean ENABLE_FREE_CACHE_V2 =
423            SystemProperties.getBoolean("fw.free_cache_v2", true);
424
425    private static final int RADIO_UID = Process.PHONE_UID;
426    private static final int LOG_UID = Process.LOG_UID;
427    private static final int NFC_UID = Process.NFC_UID;
428    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
429    private static final int SHELL_UID = Process.SHELL_UID;
430    private static final int SE_UID = Process.SE_UID;
431
432    // Cap the size of permission trees that 3rd party apps can define
433    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
434
435    // Suffix used during package installation when copying/moving
436    // package apks to install directory.
437    private static final String INSTALL_PACKAGE_SUFFIX = "-";
438
439    static final int SCAN_NO_DEX = 1<<1;
440    static final int SCAN_FORCE_DEX = 1<<2;
441    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
442    static final int SCAN_NEW_INSTALL = 1<<4;
443    static final int SCAN_UPDATE_TIME = 1<<5;
444    static final int SCAN_BOOTING = 1<<6;
445    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
446    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
447    static final int SCAN_REPLACING = 1<<9;
448    static final int SCAN_REQUIRE_KNOWN = 1<<10;
449    static final int SCAN_MOVE = 1<<11;
450    static final int SCAN_INITIAL = 1<<12;
451    static final int SCAN_CHECK_ONLY = 1<<13;
452    static final int SCAN_DONT_KILL_APP = 1<<14;
453    static final int SCAN_IGNORE_FROZEN = 1<<15;
454    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
455    static final int SCAN_AS_INSTANT_APP = 1<<17;
456    static final int SCAN_AS_FULL_APP = 1<<18;
457    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
458    /** Should not be with the scan flags */
459    static final int FLAGS_REMOVE_CHATTY = 1<<31;
460
461    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
462    /** Extension of the compressed packages */
463    private final static String COMPRESSED_EXTENSION = ".gz";
464    /** Suffix of stub packages on the system partition */
465    private final static String STUB_SUFFIX = "-Stub";
466
467    private static final int[] EMPTY_INT_ARRAY = new int[0];
468
469    private static final int TYPE_UNKNOWN = 0;
470    private static final int TYPE_ACTIVITY = 1;
471    private static final int TYPE_RECEIVER = 2;
472    private static final int TYPE_SERVICE = 3;
473    private static final int TYPE_PROVIDER = 4;
474    @IntDef(prefix = { "TYPE_" }, value = {
475            TYPE_UNKNOWN,
476            TYPE_ACTIVITY,
477            TYPE_RECEIVER,
478            TYPE_SERVICE,
479            TYPE_PROVIDER,
480    })
481    @Retention(RetentionPolicy.SOURCE)
482    public @interface ComponentType {}
483
484    /**
485     * Timeout (in milliseconds) after which the watchdog should declare that
486     * our handler thread is wedged.  The usual default for such things is one
487     * minute but we sometimes do very lengthy I/O operations on this thread,
488     * such as installing multi-gigabyte applications, so ours needs to be longer.
489     */
490    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
491
492    /**
493     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
494     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
495     * settings entry if available, otherwise we use the hardcoded default.  If it's been
496     * more than this long since the last fstrim, we force one during the boot sequence.
497     *
498     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
499     * one gets run at the next available charging+idle time.  This final mandatory
500     * no-fstrim check kicks in only of the other scheduling criteria is never met.
501     */
502    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
503
504    /**
505     * Whether verification is enabled by default.
506     */
507    private static final boolean DEFAULT_VERIFY_ENABLE = true;
508
509    /**
510     * The default maximum time to wait for the verification agent to return in
511     * milliseconds.
512     */
513    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
514
515    /**
516     * The default response for package verification timeout.
517     *
518     * This can be either PackageManager.VERIFICATION_ALLOW or
519     * PackageManager.VERIFICATION_REJECT.
520     */
521    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
522
523    static final String PLATFORM_PACKAGE_NAME = "android";
524
525    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
526
527    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
528            DEFAULT_CONTAINER_PACKAGE,
529            "com.android.defcontainer.DefaultContainerService");
530
531    private static final String KILL_APP_REASON_GIDS_CHANGED =
532            "permission grant or revoke changed gids";
533
534    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
535            "permissions revoked";
536
537    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
538
539    private static final String PACKAGE_SCHEME = "package";
540
541    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
542
543    /** Permission grant: not grant the permission. */
544    private static final int GRANT_DENIED = 1;
545
546    /** Permission grant: grant the permission as an install permission. */
547    private static final int GRANT_INSTALL = 2;
548
549    /** Permission grant: grant the permission as a runtime one. */
550    private static final int GRANT_RUNTIME = 3;
551
552    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
553    private static final int GRANT_UPGRADE = 4;
554
555    /** Canonical intent used to identify what counts as a "web browser" app */
556    private static final Intent sBrowserIntent;
557    static {
558        sBrowserIntent = new Intent();
559        sBrowserIntent.setAction(Intent.ACTION_VIEW);
560        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
561        sBrowserIntent.setData(Uri.parse("http:"));
562    }
563
564    /**
565     * The set of all protected actions [i.e. those actions for which a high priority
566     * intent filter is disallowed].
567     */
568    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
569    static {
570        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
571        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
572        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
573        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
574    }
575
576    // Compilation reasons.
577    public static final int REASON_FIRST_BOOT = 0;
578    public static final int REASON_BOOT = 1;
579    public static final int REASON_INSTALL = 2;
580    public static final int REASON_BACKGROUND_DEXOPT = 3;
581    public static final int REASON_AB_OTA = 4;
582    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
583    public static final int REASON_SHARED = 6;
584
585    public static final int REASON_LAST = REASON_SHARED;
586
587    /** All dangerous permission names in the same order as the events in MetricsEvent */
588    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
589            Manifest.permission.READ_CALENDAR,
590            Manifest.permission.WRITE_CALENDAR,
591            Manifest.permission.CAMERA,
592            Manifest.permission.READ_CONTACTS,
593            Manifest.permission.WRITE_CONTACTS,
594            Manifest.permission.GET_ACCOUNTS,
595            Manifest.permission.ACCESS_FINE_LOCATION,
596            Manifest.permission.ACCESS_COARSE_LOCATION,
597            Manifest.permission.RECORD_AUDIO,
598            Manifest.permission.READ_PHONE_STATE,
599            Manifest.permission.CALL_PHONE,
600            Manifest.permission.READ_CALL_LOG,
601            Manifest.permission.WRITE_CALL_LOG,
602            Manifest.permission.ADD_VOICEMAIL,
603            Manifest.permission.USE_SIP,
604            Manifest.permission.PROCESS_OUTGOING_CALLS,
605            Manifest.permission.READ_CELL_BROADCASTS,
606            Manifest.permission.BODY_SENSORS,
607            Manifest.permission.SEND_SMS,
608            Manifest.permission.RECEIVE_SMS,
609            Manifest.permission.READ_SMS,
610            Manifest.permission.RECEIVE_WAP_PUSH,
611            Manifest.permission.RECEIVE_MMS,
612            Manifest.permission.READ_EXTERNAL_STORAGE,
613            Manifest.permission.WRITE_EXTERNAL_STORAGE,
614            Manifest.permission.READ_PHONE_NUMBERS,
615            Manifest.permission.ANSWER_PHONE_CALLS,
616            Manifest.permission.ACCEPT_HANDOVER);
617
618
619    /**
620     * Version number for the package parser cache. Increment this whenever the format or
621     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
622     */
623    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
624
625    /**
626     * Whether the package parser cache is enabled.
627     */
628    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
629
630    final ServiceThread mHandlerThread;
631
632    final PackageHandler mHandler;
633
634    private final ProcessLoggingHandler mProcessLoggingHandler;
635
636    /**
637     * Messages for {@link #mHandler} that need to wait for system ready before
638     * being dispatched.
639     */
640    private ArrayList<Message> mPostSystemReadyMessages;
641
642    final int mSdkVersion = Build.VERSION.SDK_INT;
643
644    final Context mContext;
645    final boolean mFactoryTest;
646    final boolean mOnlyCore;
647    final DisplayMetrics mMetrics;
648    final int mDefParseFlags;
649    final String[] mSeparateProcesses;
650    final boolean mIsUpgrade;
651    final boolean mIsPreNUpgrade;
652    final boolean mIsPreNMR1Upgrade;
653
654    // Have we told the Activity Manager to whitelist the default container service by uid yet?
655    @GuardedBy("mPackages")
656    boolean mDefaultContainerWhitelisted = false;
657
658    @GuardedBy("mPackages")
659    private boolean mDexOptDialogShown;
660
661    /** The location for ASEC container files on internal storage. */
662    final String mAsecInternalPath;
663
664    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
665    // LOCK HELD.  Can be called with mInstallLock held.
666    @GuardedBy("mInstallLock")
667    final Installer mInstaller;
668
669    /** Directory where installed third-party apps stored */
670    final File mAppInstallDir;
671
672    /**
673     * Directory to which applications installed internally have their
674     * 32 bit native libraries copied.
675     */
676    private File mAppLib32InstallDir;
677
678    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
679    // apps.
680    final File mDrmAppPrivateInstallDir;
681
682    // ----------------------------------------------------------------
683
684    // Lock for state used when installing and doing other long running
685    // operations.  Methods that must be called with this lock held have
686    // the suffix "LI".
687    final Object mInstallLock = new Object();
688
689    // ----------------------------------------------------------------
690
691    // Keys are String (package name), values are Package.  This also serves
692    // as the lock for the global state.  Methods that must be called with
693    // this lock held have the prefix "LP".
694    @GuardedBy("mPackages")
695    final ArrayMap<String, PackageParser.Package> mPackages =
696            new ArrayMap<String, PackageParser.Package>();
697
698    final ArrayMap<String, Set<String>> mKnownCodebase =
699            new ArrayMap<String, Set<String>>();
700
701    // Keys are isolated uids and values are the uid of the application
702    // that created the isolated proccess.
703    @GuardedBy("mPackages")
704    final SparseIntArray mIsolatedOwners = new SparseIntArray();
705
706    /**
707     * Tracks new system packages [received in an OTA] that we expect to
708     * find updated user-installed versions. Keys are package name, values
709     * are package location.
710     */
711    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
712    /**
713     * Tracks high priority intent filters for protected actions. During boot, certain
714     * filter actions are protected and should never be allowed to have a high priority
715     * intent filter for them. However, there is one, and only one exception -- the
716     * setup wizard. It must be able to define a high priority intent filter for these
717     * actions to ensure there are no escapes from the wizard. We need to delay processing
718     * of these during boot as we need to look at all of the system packages in order
719     * to know which component is the setup wizard.
720     */
721    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
722    /**
723     * Whether or not processing protected filters should be deferred.
724     */
725    private boolean mDeferProtectedFilters = true;
726
727    /**
728     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
729     */
730    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
731    /**
732     * Whether or not system app permissions should be promoted from install to runtime.
733     */
734    boolean mPromoteSystemApps;
735
736    @GuardedBy("mPackages")
737    final Settings mSettings;
738
739    /**
740     * Set of package names that are currently "frozen", which means active
741     * surgery is being done on the code/data for that package. The platform
742     * will refuse to launch frozen packages to avoid race conditions.
743     *
744     * @see PackageFreezer
745     */
746    @GuardedBy("mPackages")
747    final ArraySet<String> mFrozenPackages = new ArraySet<>();
748
749    final ProtectedPackages mProtectedPackages;
750
751    @GuardedBy("mLoadedVolumes")
752    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
753
754    boolean mFirstBoot;
755
756    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
757
758    // System configuration read by SystemConfig.
759    final int[] mGlobalGids;
760    final SparseArray<ArraySet<String>> mSystemPermissions;
761    @GuardedBy("mAvailableFeatures")
762    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
763
764    // If mac_permissions.xml was found for seinfo labeling.
765    boolean mFoundPolicyFile;
766
767    private final InstantAppRegistry mInstantAppRegistry;
768
769    @GuardedBy("mPackages")
770    int mChangedPackagesSequenceNumber;
771    /**
772     * List of changed [installed, removed or updated] packages.
773     * mapping from user id -> sequence number -> package name
774     */
775    @GuardedBy("mPackages")
776    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
777    /**
778     * The sequence number of the last change to a package.
779     * mapping from user id -> package name -> sequence number
780     */
781    @GuardedBy("mPackages")
782    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
783
784    class PackageParserCallback implements PackageParser.Callback {
785        @Override public final boolean hasFeature(String feature) {
786            return PackageManagerService.this.hasSystemFeature(feature, 0);
787        }
788
789        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
790                Collection<PackageParser.Package> allPackages, String targetPackageName) {
791            List<PackageParser.Package> overlayPackages = null;
792            for (PackageParser.Package p : allPackages) {
793                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
794                    if (overlayPackages == null) {
795                        overlayPackages = new ArrayList<PackageParser.Package>();
796                    }
797                    overlayPackages.add(p);
798                }
799            }
800            if (overlayPackages != null) {
801                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
802                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
803                        return p1.mOverlayPriority - p2.mOverlayPriority;
804                    }
805                };
806                Collections.sort(overlayPackages, cmp);
807            }
808            return overlayPackages;
809        }
810
811        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
812                String targetPackageName, String targetPath) {
813            if ("android".equals(targetPackageName)) {
814                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
815                // native AssetManager.
816                return null;
817            }
818            List<PackageParser.Package> overlayPackages =
819                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
820            if (overlayPackages == null || overlayPackages.isEmpty()) {
821                return null;
822            }
823            List<String> overlayPathList = null;
824            for (PackageParser.Package overlayPackage : overlayPackages) {
825                if (targetPath == null) {
826                    if (overlayPathList == null) {
827                        overlayPathList = new ArrayList<String>();
828                    }
829                    overlayPathList.add(overlayPackage.baseCodePath);
830                    continue;
831                }
832
833                try {
834                    // Creates idmaps for system to parse correctly the Android manifest of the
835                    // target package.
836                    //
837                    // OverlayManagerService will update each of them with a correct gid from its
838                    // target package app id.
839                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
840                            UserHandle.getSharedAppGid(
841                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
842                    if (overlayPathList == null) {
843                        overlayPathList = new ArrayList<String>();
844                    }
845                    overlayPathList.add(overlayPackage.baseCodePath);
846                } catch (InstallerException e) {
847                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
848                            overlayPackage.baseCodePath);
849                }
850            }
851            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
852        }
853
854        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
855            synchronized (mPackages) {
856                return getStaticOverlayPathsLocked(
857                        mPackages.values(), targetPackageName, targetPath);
858            }
859        }
860
861        @Override public final String[] getOverlayApks(String targetPackageName) {
862            return getStaticOverlayPaths(targetPackageName, null);
863        }
864
865        @Override public final String[] getOverlayPaths(String targetPackageName,
866                String targetPath) {
867            return getStaticOverlayPaths(targetPackageName, targetPath);
868        }
869    };
870
871    class ParallelPackageParserCallback extends PackageParserCallback {
872        List<PackageParser.Package> mOverlayPackages = null;
873
874        void findStaticOverlayPackages() {
875            synchronized (mPackages) {
876                for (PackageParser.Package p : mPackages.values()) {
877                    if (p.mIsStaticOverlay) {
878                        if (mOverlayPackages == null) {
879                            mOverlayPackages = new ArrayList<PackageParser.Package>();
880                        }
881                        mOverlayPackages.add(p);
882                    }
883                }
884            }
885        }
886
887        @Override
888        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
889            // We can trust mOverlayPackages without holding mPackages because package uninstall
890            // can't happen while running parallel parsing.
891            // Moreover holding mPackages on each parsing thread causes dead-lock.
892            return mOverlayPackages == null ? null :
893                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
894        }
895    }
896
897    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
898    final ParallelPackageParserCallback mParallelPackageParserCallback =
899            new ParallelPackageParserCallback();
900
901    public static final class SharedLibraryEntry {
902        public final @Nullable String path;
903        public final @Nullable String apk;
904        public final @NonNull SharedLibraryInfo info;
905
906        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
907                String declaringPackageName, int declaringPackageVersionCode) {
908            path = _path;
909            apk = _apk;
910            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
911                    declaringPackageName, declaringPackageVersionCode), null);
912        }
913    }
914
915    // Currently known shared libraries.
916    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
917    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
918            new ArrayMap<>();
919
920    // All available activities, for your resolving pleasure.
921    final ActivityIntentResolver mActivities =
922            new ActivityIntentResolver();
923
924    // All available receivers, for your resolving pleasure.
925    final ActivityIntentResolver mReceivers =
926            new ActivityIntentResolver();
927
928    // All available services, for your resolving pleasure.
929    final ServiceIntentResolver mServices = new ServiceIntentResolver();
930
931    // All available providers, for your resolving pleasure.
932    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
933
934    // Mapping from provider base names (first directory in content URI codePath)
935    // to the provider information.
936    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
937            new ArrayMap<String, PackageParser.Provider>();
938
939    // Mapping from instrumentation class names to info about them.
940    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
941            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
942
943    // Mapping from permission names to info about them.
944    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
945            new ArrayMap<String, PackageParser.PermissionGroup>();
946
947    // Packages whose data we have transfered into another package, thus
948    // should no longer exist.
949    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
950
951    // Broadcast actions that are only available to the system.
952    @GuardedBy("mProtectedBroadcasts")
953    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
954
955    /** List of packages waiting for verification. */
956    final SparseArray<PackageVerificationState> mPendingVerification
957            = new SparseArray<PackageVerificationState>();
958
959    /** Set of packages associated with each app op permission. */
960    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
961
962    final PackageInstallerService mInstallerService;
963
964    private final PackageDexOptimizer mPackageDexOptimizer;
965    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
966    // is used by other apps).
967    private final DexManager mDexManager;
968
969    private AtomicInteger mNextMoveId = new AtomicInteger();
970    private final MoveCallbacks mMoveCallbacks;
971
972    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
973
974    // Cache of users who need badging.
975    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
976
977    /** Token for keys in mPendingVerification. */
978    private int mPendingVerificationToken = 0;
979
980    volatile boolean mSystemReady;
981    volatile boolean mSafeMode;
982    volatile boolean mHasSystemUidErrors;
983    private volatile boolean mEphemeralAppsDisabled;
984
985    ApplicationInfo mAndroidApplication;
986    final ActivityInfo mResolveActivity = new ActivityInfo();
987    final ResolveInfo mResolveInfo = new ResolveInfo();
988    ComponentName mResolveComponentName;
989    PackageParser.Package mPlatformPackage;
990    ComponentName mCustomResolverComponentName;
991
992    boolean mResolverReplaced = false;
993
994    private final @Nullable ComponentName mIntentFilterVerifierComponent;
995    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
996
997    private int mIntentFilterVerificationToken = 0;
998
999    /** The service connection to the ephemeral resolver */
1000    final EphemeralResolverConnection mInstantAppResolverConnection;
1001    /** Component used to show resolver settings for Instant Apps */
1002    final ComponentName mInstantAppResolverSettingsComponent;
1003
1004    /** Activity used to install instant applications */
1005    ActivityInfo mInstantAppInstallerActivity;
1006    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1007
1008    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1009            = new SparseArray<IntentFilterVerificationState>();
1010
1011    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1012
1013    // List of packages names to keep cached, even if they are uninstalled for all users
1014    private List<String> mKeepUninstalledPackages;
1015
1016    private UserManagerInternal mUserManagerInternal;
1017
1018    private DeviceIdleController.LocalService mDeviceIdleController;
1019
1020    private File mCacheDir;
1021
1022    private ArraySet<String> mPrivappPermissionsViolations;
1023
1024    private Future<?> mPrepareAppDataFuture;
1025
1026    private static class IFVerificationParams {
1027        PackageParser.Package pkg;
1028        boolean replacing;
1029        int userId;
1030        int verifierUid;
1031
1032        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1033                int _userId, int _verifierUid) {
1034            pkg = _pkg;
1035            replacing = _replacing;
1036            userId = _userId;
1037            replacing = _replacing;
1038            verifierUid = _verifierUid;
1039        }
1040    }
1041
1042    private interface IntentFilterVerifier<T extends IntentFilter> {
1043        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1044                                               T filter, String packageName);
1045        void startVerifications(int userId);
1046        void receiveVerificationResponse(int verificationId);
1047    }
1048
1049    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1050        private Context mContext;
1051        private ComponentName mIntentFilterVerifierComponent;
1052        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1053
1054        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1055            mContext = context;
1056            mIntentFilterVerifierComponent = verifierComponent;
1057        }
1058
1059        private String getDefaultScheme() {
1060            return IntentFilter.SCHEME_HTTPS;
1061        }
1062
1063        @Override
1064        public void startVerifications(int userId) {
1065            // Launch verifications requests
1066            int count = mCurrentIntentFilterVerifications.size();
1067            for (int n=0; n<count; n++) {
1068                int verificationId = mCurrentIntentFilterVerifications.get(n);
1069                final IntentFilterVerificationState ivs =
1070                        mIntentFilterVerificationStates.get(verificationId);
1071
1072                String packageName = ivs.getPackageName();
1073
1074                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1075                final int filterCount = filters.size();
1076                ArraySet<String> domainsSet = new ArraySet<>();
1077                for (int m=0; m<filterCount; m++) {
1078                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1079                    domainsSet.addAll(filter.getHostsList());
1080                }
1081                synchronized (mPackages) {
1082                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1083                            packageName, domainsSet) != null) {
1084                        scheduleWriteSettingsLocked();
1085                    }
1086                }
1087                sendVerificationRequest(verificationId, ivs);
1088            }
1089            mCurrentIntentFilterVerifications.clear();
1090        }
1091
1092        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1093            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1096                    verificationId);
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1099                    getDefaultScheme());
1100            verificationIntent.putExtra(
1101                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1102                    ivs.getHostsString());
1103            verificationIntent.putExtra(
1104                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1105                    ivs.getPackageName());
1106            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1107            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1108
1109            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1110            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1111                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1112                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1113
1114            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1115            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1116                    "Sending IntentFilter verification broadcast");
1117        }
1118
1119        public void receiveVerificationResponse(int verificationId) {
1120            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1121
1122            final boolean verified = ivs.isVerified();
1123
1124            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1125            final int count = filters.size();
1126            if (DEBUG_DOMAIN_VERIFICATION) {
1127                Slog.i(TAG, "Received verification response " + verificationId
1128                        + " for " + count + " filters, verified=" + verified);
1129            }
1130            for (int n=0; n<count; n++) {
1131                PackageParser.ActivityIntentInfo filter = filters.get(n);
1132                filter.setVerified(verified);
1133
1134                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1135                        + " verified with result:" + verified + " and hosts:"
1136                        + ivs.getHostsString());
1137            }
1138
1139            mIntentFilterVerificationStates.remove(verificationId);
1140
1141            final String packageName = ivs.getPackageName();
1142            IntentFilterVerificationInfo ivi = null;
1143
1144            synchronized (mPackages) {
1145                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1146            }
1147            if (ivi == null) {
1148                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1149                        + verificationId + " packageName:" + packageName);
1150                return;
1151            }
1152            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1153                    "Updating IntentFilterVerificationInfo for package " + packageName
1154                            +" verificationId:" + verificationId);
1155
1156            synchronized (mPackages) {
1157                if (verified) {
1158                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1159                } else {
1160                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1161                }
1162                scheduleWriteSettingsLocked();
1163
1164                final int userId = ivs.getUserId();
1165                if (userId != UserHandle.USER_ALL) {
1166                    final int userStatus =
1167                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1168
1169                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1170                    boolean needUpdate = false;
1171
1172                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1173                    // already been set by the User thru the Disambiguation dialog
1174                    switch (userStatus) {
1175                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1176                            if (verified) {
1177                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1178                            } else {
1179                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1180                            }
1181                            needUpdate = true;
1182                            break;
1183
1184                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1185                            if (verified) {
1186                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1187                                needUpdate = true;
1188                            }
1189                            break;
1190
1191                        default:
1192                            // Nothing to do
1193                    }
1194
1195                    if (needUpdate) {
1196                        mSettings.updateIntentFilterVerificationStatusLPw(
1197                                packageName, updatedStatus, userId);
1198                        scheduleWritePackageRestrictionsLocked(userId);
1199                    }
1200                }
1201            }
1202        }
1203
1204        @Override
1205        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1206                    ActivityIntentInfo filter, String packageName) {
1207            if (!hasValidDomains(filter)) {
1208                return false;
1209            }
1210            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1211            if (ivs == null) {
1212                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1213                        packageName);
1214            }
1215            if (DEBUG_DOMAIN_VERIFICATION) {
1216                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1217            }
1218            ivs.addFilter(filter);
1219            return true;
1220        }
1221
1222        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1223                int userId, int verificationId, String packageName) {
1224            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1225                    verifierUid, userId, packageName);
1226            ivs.setPendingState();
1227            synchronized (mPackages) {
1228                mIntentFilterVerificationStates.append(verificationId, ivs);
1229                mCurrentIntentFilterVerifications.add(verificationId);
1230            }
1231            return ivs;
1232        }
1233    }
1234
1235    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1236        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1237                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1238                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1239    }
1240
1241    // Set of pending broadcasts for aggregating enable/disable of components.
1242    static class PendingPackageBroadcasts {
1243        // for each user id, a map of <package name -> components within that package>
1244        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1245
1246        public PendingPackageBroadcasts() {
1247            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1248        }
1249
1250        public ArrayList<String> get(int userId, String packageName) {
1251            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1252            return packages.get(packageName);
1253        }
1254
1255        public void put(int userId, String packageName, ArrayList<String> components) {
1256            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1257            packages.put(packageName, components);
1258        }
1259
1260        public void remove(int userId, String packageName) {
1261            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1262            if (packages != null) {
1263                packages.remove(packageName);
1264            }
1265        }
1266
1267        public void remove(int userId) {
1268            mUidMap.remove(userId);
1269        }
1270
1271        public int userIdCount() {
1272            return mUidMap.size();
1273        }
1274
1275        public int userIdAt(int n) {
1276            return mUidMap.keyAt(n);
1277        }
1278
1279        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1280            return mUidMap.get(userId);
1281        }
1282
1283        public int size() {
1284            // total number of pending broadcast entries across all userIds
1285            int num = 0;
1286            for (int i = 0; i< mUidMap.size(); i++) {
1287                num += mUidMap.valueAt(i).size();
1288            }
1289            return num;
1290        }
1291
1292        public void clear() {
1293            mUidMap.clear();
1294        }
1295
1296        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1297            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1298            if (map == null) {
1299                map = new ArrayMap<String, ArrayList<String>>();
1300                mUidMap.put(userId, map);
1301            }
1302            return map;
1303        }
1304    }
1305    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1306
1307    // Service Connection to remote media container service to copy
1308    // package uri's from external media onto secure containers
1309    // or internal storage.
1310    private IMediaContainerService mContainerService = null;
1311
1312    static final int SEND_PENDING_BROADCAST = 1;
1313    static final int MCS_BOUND = 3;
1314    static final int END_COPY = 4;
1315    static final int INIT_COPY = 5;
1316    static final int MCS_UNBIND = 6;
1317    static final int START_CLEANING_PACKAGE = 7;
1318    static final int FIND_INSTALL_LOC = 8;
1319    static final int POST_INSTALL = 9;
1320    static final int MCS_RECONNECT = 10;
1321    static final int MCS_GIVE_UP = 11;
1322    static final int UPDATED_MEDIA_STATUS = 12;
1323    static final int WRITE_SETTINGS = 13;
1324    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1325    static final int PACKAGE_VERIFIED = 15;
1326    static final int CHECK_PENDING_VERIFICATION = 16;
1327    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1328    static final int INTENT_FILTER_VERIFIED = 18;
1329    static final int WRITE_PACKAGE_LIST = 19;
1330    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1331
1332    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1333
1334    // Delay time in millisecs
1335    static final int BROADCAST_DELAY = 10 * 1000;
1336
1337    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1338            2 * 60 * 60 * 1000L; /* two hours */
1339
1340    static UserManagerService sUserManager;
1341
1342    // Stores a list of users whose package restrictions file needs to be updated
1343    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1344
1345    final private DefaultContainerConnection mDefContainerConn =
1346            new DefaultContainerConnection();
1347    class DefaultContainerConnection implements ServiceConnection {
1348        public void onServiceConnected(ComponentName name, IBinder service) {
1349            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1350            final IMediaContainerService imcs = IMediaContainerService.Stub
1351                    .asInterface(Binder.allowBlocking(service));
1352            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1353        }
1354
1355        public void onServiceDisconnected(ComponentName name) {
1356            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1357        }
1358    }
1359
1360    // Recordkeeping of restore-after-install operations that are currently in flight
1361    // between the Package Manager and the Backup Manager
1362    static class PostInstallData {
1363        public InstallArgs args;
1364        public PackageInstalledInfo res;
1365
1366        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1367            args = _a;
1368            res = _r;
1369        }
1370    }
1371
1372    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1373    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1374
1375    // XML tags for backup/restore of various bits of state
1376    private static final String TAG_PREFERRED_BACKUP = "pa";
1377    private static final String TAG_DEFAULT_APPS = "da";
1378    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1379
1380    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1381    private static final String TAG_ALL_GRANTS = "rt-grants";
1382    private static final String TAG_GRANT = "grant";
1383    private static final String ATTR_PACKAGE_NAME = "pkg";
1384
1385    private static final String TAG_PERMISSION = "perm";
1386    private static final String ATTR_PERMISSION_NAME = "name";
1387    private static final String ATTR_IS_GRANTED = "g";
1388    private static final String ATTR_USER_SET = "set";
1389    private static final String ATTR_USER_FIXED = "fixed";
1390    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1391
1392    // System/policy permission grants are not backed up
1393    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1394            FLAG_PERMISSION_POLICY_FIXED
1395            | FLAG_PERMISSION_SYSTEM_FIXED
1396            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1397
1398    // And we back up these user-adjusted states
1399    private static final int USER_RUNTIME_GRANT_MASK =
1400            FLAG_PERMISSION_USER_SET
1401            | FLAG_PERMISSION_USER_FIXED
1402            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1403
1404    final @Nullable String mRequiredVerifierPackage;
1405    final @NonNull String mRequiredInstallerPackage;
1406    final @NonNull String mRequiredUninstallerPackage;
1407    final @Nullable String mSetupWizardPackage;
1408    final @Nullable String mStorageManagerPackage;
1409    final @NonNull String mServicesSystemSharedLibraryPackageName;
1410    final @NonNull String mSharedSystemSharedLibraryPackageName;
1411
1412    final boolean mPermissionReviewRequired;
1413
1414    private final PackageUsage mPackageUsage = new PackageUsage();
1415    private final CompilerStats mCompilerStats = new CompilerStats();
1416
1417    class PackageHandler extends Handler {
1418        private boolean mBound = false;
1419        final ArrayList<HandlerParams> mPendingInstalls =
1420            new ArrayList<HandlerParams>();
1421
1422        private boolean connectToService() {
1423            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1424                    " DefaultContainerService");
1425            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1427            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1428                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1429                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430                mBound = true;
1431                return true;
1432            }
1433            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1434            return false;
1435        }
1436
1437        private void disconnectService() {
1438            mContainerService = null;
1439            mBound = false;
1440            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1441            mContext.unbindService(mDefContainerConn);
1442            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1443        }
1444
1445        PackageHandler(Looper looper) {
1446            super(looper);
1447        }
1448
1449        public void handleMessage(Message msg) {
1450            try {
1451                doHandleMessage(msg);
1452            } finally {
1453                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1454            }
1455        }
1456
1457        void doHandleMessage(Message msg) {
1458            switch (msg.what) {
1459                case INIT_COPY: {
1460                    HandlerParams params = (HandlerParams) msg.obj;
1461                    int idx = mPendingInstalls.size();
1462                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1463                    // If a bind was already initiated we dont really
1464                    // need to do anything. The pending install
1465                    // will be processed later on.
1466                    if (!mBound) {
1467                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1468                                System.identityHashCode(mHandler));
1469                        // If this is the only one pending we might
1470                        // have to bind to the service again.
1471                        if (!connectToService()) {
1472                            Slog.e(TAG, "Failed to bind to media container service");
1473                            params.serviceError();
1474                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475                                    System.identityHashCode(mHandler));
1476                            if (params.traceMethod != null) {
1477                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1478                                        params.traceCookie);
1479                            }
1480                            return;
1481                        } else {
1482                            // Once we bind to the service, the first
1483                            // pending request will be processed.
1484                            mPendingInstalls.add(idx, params);
1485                        }
1486                    } else {
1487                        mPendingInstalls.add(idx, params);
1488                        // Already bound to the service. Just make
1489                        // sure we trigger off processing the first request.
1490                        if (idx == 0) {
1491                            mHandler.sendEmptyMessage(MCS_BOUND);
1492                        }
1493                    }
1494                    break;
1495                }
1496                case MCS_BOUND: {
1497                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1498                    if (msg.obj != null) {
1499                        mContainerService = (IMediaContainerService) msg.obj;
1500                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1501                                System.identityHashCode(mHandler));
1502                    }
1503                    if (mContainerService == null) {
1504                        if (!mBound) {
1505                            // Something seriously wrong since we are not bound and we are not
1506                            // waiting for connection. Bail out.
1507                            Slog.e(TAG, "Cannot bind to media container service");
1508                            for (HandlerParams params : mPendingInstalls) {
1509                                // Indicate service bind error
1510                                params.serviceError();
1511                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1512                                        System.identityHashCode(params));
1513                                if (params.traceMethod != null) {
1514                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1515                                            params.traceMethod, params.traceCookie);
1516                                }
1517                                return;
1518                            }
1519                            mPendingInstalls.clear();
1520                        } else {
1521                            Slog.w(TAG, "Waiting to connect to media container service");
1522                        }
1523                    } else if (mPendingInstalls.size() > 0) {
1524                        HandlerParams params = mPendingInstalls.get(0);
1525                        if (params != null) {
1526                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1527                                    System.identityHashCode(params));
1528                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1529                            if (params.startCopy()) {
1530                                // We are done...  look for more work or to
1531                                // go idle.
1532                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1533                                        "Checking for more work or unbind...");
1534                                // Delete pending install
1535                                if (mPendingInstalls.size() > 0) {
1536                                    mPendingInstalls.remove(0);
1537                                }
1538                                if (mPendingInstalls.size() == 0) {
1539                                    if (mBound) {
1540                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1541                                                "Posting delayed MCS_UNBIND");
1542                                        removeMessages(MCS_UNBIND);
1543                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1544                                        // Unbind after a little delay, to avoid
1545                                        // continual thrashing.
1546                                        sendMessageDelayed(ubmsg, 10000);
1547                                    }
1548                                } else {
1549                                    // There are more pending requests in queue.
1550                                    // Just post MCS_BOUND message to trigger processing
1551                                    // of next pending install.
1552                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1553                                            "Posting MCS_BOUND for next work");
1554                                    mHandler.sendEmptyMessage(MCS_BOUND);
1555                                }
1556                            }
1557                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1558                        }
1559                    } else {
1560                        // Should never happen ideally.
1561                        Slog.w(TAG, "Empty queue");
1562                    }
1563                    break;
1564                }
1565                case MCS_RECONNECT: {
1566                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1567                    if (mPendingInstalls.size() > 0) {
1568                        if (mBound) {
1569                            disconnectService();
1570                        }
1571                        if (!connectToService()) {
1572                            Slog.e(TAG, "Failed to bind to media container service");
1573                            for (HandlerParams params : mPendingInstalls) {
1574                                // Indicate service bind error
1575                                params.serviceError();
1576                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1577                                        System.identityHashCode(params));
1578                            }
1579                            mPendingInstalls.clear();
1580                        }
1581                    }
1582                    break;
1583                }
1584                case MCS_UNBIND: {
1585                    // If there is no actual work left, then time to unbind.
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1587
1588                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1589                        if (mBound) {
1590                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1591
1592                            disconnectService();
1593                        }
1594                    } else if (mPendingInstalls.size() > 0) {
1595                        // There are more pending requests in queue.
1596                        // Just post MCS_BOUND message to trigger processing
1597                        // of next pending install.
1598                        mHandler.sendEmptyMessage(MCS_BOUND);
1599                    }
1600
1601                    break;
1602                }
1603                case MCS_GIVE_UP: {
1604                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1605                    HandlerParams params = mPendingInstalls.remove(0);
1606                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1607                            System.identityHashCode(params));
1608                    break;
1609                }
1610                case SEND_PENDING_BROADCAST: {
1611                    String packages[];
1612                    ArrayList<String> components[];
1613                    int size = 0;
1614                    int uids[];
1615                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1616                    synchronized (mPackages) {
1617                        if (mPendingBroadcasts == null) {
1618                            return;
1619                        }
1620                        size = mPendingBroadcasts.size();
1621                        if (size <= 0) {
1622                            // Nothing to be done. Just return
1623                            return;
1624                        }
1625                        packages = new String[size];
1626                        components = new ArrayList[size];
1627                        uids = new int[size];
1628                        int i = 0;  // filling out the above arrays
1629
1630                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1631                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1632                            Iterator<Map.Entry<String, ArrayList<String>>> it
1633                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1634                                            .entrySet().iterator();
1635                            while (it.hasNext() && i < size) {
1636                                Map.Entry<String, ArrayList<String>> ent = it.next();
1637                                packages[i] = ent.getKey();
1638                                components[i] = ent.getValue();
1639                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1640                                uids[i] = (ps != null)
1641                                        ? UserHandle.getUid(packageUserId, ps.appId)
1642                                        : -1;
1643                                i++;
1644                            }
1645                        }
1646                        size = i;
1647                        mPendingBroadcasts.clear();
1648                    }
1649                    // Send broadcasts
1650                    for (int i = 0; i < size; i++) {
1651                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1652                    }
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1654                    break;
1655                }
1656                case START_CLEANING_PACKAGE: {
1657                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1658                    final String packageName = (String)msg.obj;
1659                    final int userId = msg.arg1;
1660                    final boolean andCode = msg.arg2 != 0;
1661                    synchronized (mPackages) {
1662                        if (userId == UserHandle.USER_ALL) {
1663                            int[] users = sUserManager.getUserIds();
1664                            for (int user : users) {
1665                                mSettings.addPackageToCleanLPw(
1666                                        new PackageCleanItem(user, packageName, andCode));
1667                            }
1668                        } else {
1669                            mSettings.addPackageToCleanLPw(
1670                                    new PackageCleanItem(userId, packageName, andCode));
1671                        }
1672                    }
1673                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1674                    startCleaningPackages();
1675                } break;
1676                case POST_INSTALL: {
1677                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1678
1679                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1680                    final boolean didRestore = (msg.arg2 != 0);
1681                    mRunningInstalls.delete(msg.arg1);
1682
1683                    if (data != null) {
1684                        InstallArgs args = data.args;
1685                        PackageInstalledInfo parentRes = data.res;
1686
1687                        final boolean grantPermissions = (args.installFlags
1688                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1689                        final boolean killApp = (args.installFlags
1690                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1691                        final boolean virtualPreload = ((args.installFlags
1692                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1693                        final String[] grantedPermissions = args.installGrantPermissions;
1694
1695                        // Handle the parent package
1696                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1697                                virtualPreload, grantedPermissions, didRestore,
1698                                args.installerPackageName, args.observer);
1699
1700                        // Handle the child packages
1701                        final int childCount = (parentRes.addedChildPackages != null)
1702                                ? parentRes.addedChildPackages.size() : 0;
1703                        for (int i = 0; i < childCount; i++) {
1704                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1705                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1706                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1707                                    args.installerPackageName, args.observer);
1708                        }
1709
1710                        // Log tracing if needed
1711                        if (args.traceMethod != null) {
1712                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1713                                    args.traceCookie);
1714                        }
1715                    } else {
1716                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1717                    }
1718
1719                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1720                } break;
1721                case UPDATED_MEDIA_STATUS: {
1722                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1723                    boolean reportStatus = msg.arg1 == 1;
1724                    boolean doGc = msg.arg2 == 1;
1725                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1726                    if (doGc) {
1727                        // Force a gc to clear up stale containers.
1728                        Runtime.getRuntime().gc();
1729                    }
1730                    if (msg.obj != null) {
1731                        @SuppressWarnings("unchecked")
1732                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1733                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1734                        // Unload containers
1735                        unloadAllContainers(args);
1736                    }
1737                    if (reportStatus) {
1738                        try {
1739                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1740                                    "Invoking StorageManagerService call back");
1741                            PackageHelper.getStorageManager().finishMediaUpdate();
1742                        } catch (RemoteException e) {
1743                            Log.e(TAG, "StorageManagerService not running?");
1744                        }
1745                    }
1746                } break;
1747                case WRITE_SETTINGS: {
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1749                    synchronized (mPackages) {
1750                        removeMessages(WRITE_SETTINGS);
1751                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1752                        mSettings.writeLPr();
1753                        mDirtyUsers.clear();
1754                    }
1755                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1756                } break;
1757                case WRITE_PACKAGE_RESTRICTIONS: {
1758                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1759                    synchronized (mPackages) {
1760                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1761                        for (int userId : mDirtyUsers) {
1762                            mSettings.writePackageRestrictionsLPr(userId);
1763                        }
1764                        mDirtyUsers.clear();
1765                    }
1766                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1767                } break;
1768                case WRITE_PACKAGE_LIST: {
1769                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1770                    synchronized (mPackages) {
1771                        removeMessages(WRITE_PACKAGE_LIST);
1772                        mSettings.writePackageListLPr(msg.arg1);
1773                    }
1774                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1775                } break;
1776                case CHECK_PENDING_VERIFICATION: {
1777                    final int verificationId = msg.arg1;
1778                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1779
1780                    if ((state != null) && !state.timeoutExtended()) {
1781                        final InstallArgs args = state.getInstallArgs();
1782                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1783
1784                        Slog.i(TAG, "Verification timed out for " + originUri);
1785                        mPendingVerification.remove(verificationId);
1786
1787                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1788
1789                        final UserHandle user = args.getUser();
1790                        if (getDefaultVerificationResponse(user)
1791                                == PackageManager.VERIFICATION_ALLOW) {
1792                            Slog.i(TAG, "Continuing with installation of " + originUri);
1793                            state.setVerifierResponse(Binder.getCallingUid(),
1794                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1795                            broadcastPackageVerified(verificationId, originUri,
1796                                    PackageManager.VERIFICATION_ALLOW, user);
1797                            try {
1798                                ret = args.copyApk(mContainerService, true);
1799                            } catch (RemoteException e) {
1800                                Slog.e(TAG, "Could not contact the ContainerService");
1801                            }
1802                        } else {
1803                            broadcastPackageVerified(verificationId, originUri,
1804                                    PackageManager.VERIFICATION_REJECT, user);
1805                        }
1806
1807                        Trace.asyncTraceEnd(
1808                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1809
1810                        processPendingInstall(args, ret);
1811                        mHandler.sendEmptyMessage(MCS_UNBIND);
1812                    }
1813                    break;
1814                }
1815                case PACKAGE_VERIFIED: {
1816                    final int verificationId = msg.arg1;
1817
1818                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1819                    if (state == null) {
1820                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1821                        break;
1822                    }
1823
1824                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1825
1826                    state.setVerifierResponse(response.callerUid, response.code);
1827
1828                    if (state.isVerificationComplete()) {
1829                        mPendingVerification.remove(verificationId);
1830
1831                        final InstallArgs args = state.getInstallArgs();
1832                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1833
1834                        int ret;
1835                        if (state.isInstallAllowed()) {
1836                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1837                            broadcastPackageVerified(verificationId, originUri,
1838                                    response.code, state.getInstallArgs().getUser());
1839                            try {
1840                                ret = args.copyApk(mContainerService, true);
1841                            } catch (RemoteException e) {
1842                                Slog.e(TAG, "Could not contact the ContainerService");
1843                            }
1844                        } else {
1845                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1846                        }
1847
1848                        Trace.asyncTraceEnd(
1849                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1850
1851                        processPendingInstall(args, ret);
1852                        mHandler.sendEmptyMessage(MCS_UNBIND);
1853                    }
1854
1855                    break;
1856                }
1857                case START_INTENT_FILTER_VERIFICATIONS: {
1858                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1859                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1860                            params.replacing, params.pkg);
1861                    break;
1862                }
1863                case INTENT_FILTER_VERIFIED: {
1864                    final int verificationId = msg.arg1;
1865
1866                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1867                            verificationId);
1868                    if (state == null) {
1869                        Slog.w(TAG, "Invalid IntentFilter verification token "
1870                                + verificationId + " received");
1871                        break;
1872                    }
1873
1874                    final int userId = state.getUserId();
1875
1876                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                            "Processing IntentFilter verification with token:"
1878                            + verificationId + " and userId:" + userId);
1879
1880                    final IntentFilterVerificationResponse response =
1881                            (IntentFilterVerificationResponse) msg.obj;
1882
1883                    state.setVerifierResponse(response.callerUid, response.code);
1884
1885                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1886                            "IntentFilter verification with token:" + verificationId
1887                            + " and userId:" + userId
1888                            + " is settings verifier response with response code:"
1889                            + response.code);
1890
1891                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1892                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1893                                + response.getFailedDomainsString());
1894                    }
1895
1896                    if (state.isVerificationComplete()) {
1897                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1898                    } else {
1899                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1900                                "IntentFilter verification with token:" + verificationId
1901                                + " was not said to be complete");
1902                    }
1903
1904                    break;
1905                }
1906                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1907                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1908                            mInstantAppResolverConnection,
1909                            (InstantAppRequest) msg.obj,
1910                            mInstantAppInstallerActivity,
1911                            mHandler);
1912                }
1913            }
1914        }
1915    }
1916
1917    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1918            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1919            boolean launchedForRestore, String installerPackage,
1920            IPackageInstallObserver2 installObserver) {
1921        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1922            // Send the removed broadcasts
1923            if (res.removedInfo != null) {
1924                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1925            }
1926
1927            // Now that we successfully installed the package, grant runtime
1928            // permissions if requested before broadcasting the install. Also
1929            // for legacy apps in permission review mode we clear the permission
1930            // review flag which is used to emulate runtime permissions for
1931            // legacy apps.
1932            if (grantPermissions) {
1933                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1934            }
1935
1936            final boolean update = res.removedInfo != null
1937                    && res.removedInfo.removedPackage != null;
1938            final String installerPackageName =
1939                    res.installerPackageName != null
1940                            ? res.installerPackageName
1941                            : res.removedInfo != null
1942                                    ? res.removedInfo.installerPackageName
1943                                    : null;
1944
1945            // If this is the first time we have child packages for a disabled privileged
1946            // app that had no children, we grant requested runtime permissions to the new
1947            // children if the parent on the system image had them already granted.
1948            if (res.pkg.parentPackage != null) {
1949                synchronized (mPackages) {
1950                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1951                }
1952            }
1953
1954            synchronized (mPackages) {
1955                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1956            }
1957
1958            final String packageName = res.pkg.applicationInfo.packageName;
1959
1960            // Determine the set of users who are adding this package for
1961            // the first time vs. those who are seeing an update.
1962            int[] firstUsers = EMPTY_INT_ARRAY;
1963            int[] updateUsers = EMPTY_INT_ARRAY;
1964            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1965            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1966            for (int newUser : res.newUsers) {
1967                if (ps.getInstantApp(newUser)) {
1968                    continue;
1969                }
1970                if (allNewUsers) {
1971                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1972                    continue;
1973                }
1974                boolean isNew = true;
1975                for (int origUser : res.origUsers) {
1976                    if (origUser == newUser) {
1977                        isNew = false;
1978                        break;
1979                    }
1980                }
1981                if (isNew) {
1982                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1983                } else {
1984                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1985                }
1986            }
1987
1988            // Send installed broadcasts if the package is not a static shared lib.
1989            if (res.pkg.staticSharedLibName == null) {
1990                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1991
1992                // Send added for users that see the package for the first time
1993                // sendPackageAddedForNewUsers also deals with system apps
1994                int appId = UserHandle.getAppId(res.uid);
1995                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1996                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1997                        virtualPreload /*startReceiver*/, appId, firstUsers);
1998
1999                // Send added for users that don't see the package for the first time
2000                Bundle extras = new Bundle(1);
2001                extras.putInt(Intent.EXTRA_UID, res.uid);
2002                if (update) {
2003                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2004                }
2005                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2006                        extras, 0 /*flags*/,
2007                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2008                if (installerPackageName != null) {
2009                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2010                            extras, 0 /*flags*/,
2011                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2012                }
2013
2014                // Send replaced for users that don't see the package for the first time
2015                if (update) {
2016                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2017                            packageName, extras, 0 /*flags*/,
2018                            null /*targetPackage*/, null /*finishedReceiver*/,
2019                            updateUsers);
2020                    if (installerPackageName != null) {
2021                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2022                                extras, 0 /*flags*/,
2023                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2024                    }
2025                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2026                            null /*package*/, null /*extras*/, 0 /*flags*/,
2027                            packageName /*targetPackage*/,
2028                            null /*finishedReceiver*/, updateUsers);
2029                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2030                    // First-install and we did a restore, so we're responsible for the
2031                    // first-launch broadcast.
2032                    if (DEBUG_BACKUP) {
2033                        Slog.i(TAG, "Post-restore of " + packageName
2034                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2035                    }
2036                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2037                }
2038
2039                // Send broadcast package appeared if forward locked/external for all users
2040                // treat asec-hosted packages like removable media on upgrade
2041                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2042                    if (DEBUG_INSTALL) {
2043                        Slog.i(TAG, "upgrading pkg " + res.pkg
2044                                + " is ASEC-hosted -> AVAILABLE");
2045                    }
2046                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2047                    ArrayList<String> pkgList = new ArrayList<>(1);
2048                    pkgList.add(packageName);
2049                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2050                }
2051            }
2052
2053            // Work that needs to happen on first install within each user
2054            if (firstUsers != null && firstUsers.length > 0) {
2055                synchronized (mPackages) {
2056                    for (int userId : firstUsers) {
2057                        // If this app is a browser and it's newly-installed for some
2058                        // users, clear any default-browser state in those users. The
2059                        // app's nature doesn't depend on the user, so we can just check
2060                        // its browser nature in any user and generalize.
2061                        if (packageIsBrowser(packageName, userId)) {
2062                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2063                        }
2064
2065                        // We may also need to apply pending (restored) runtime
2066                        // permission grants within these users.
2067                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2068                    }
2069                }
2070            }
2071
2072            // Log current value of "unknown sources" setting
2073            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2074                    getUnknownSourcesSettings());
2075
2076            // Remove the replaced package's older resources safely now
2077            // We delete after a gc for applications  on sdcard.
2078            if (res.removedInfo != null && res.removedInfo.args != null) {
2079                Runtime.getRuntime().gc();
2080                synchronized (mInstallLock) {
2081                    res.removedInfo.args.doPostDeleteLI(true);
2082                }
2083            } else {
2084                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2085                // and not block here.
2086                VMRuntime.getRuntime().requestConcurrentGC();
2087            }
2088
2089            // Notify DexManager that the package was installed for new users.
2090            // The updated users should already be indexed and the package code paths
2091            // should not change.
2092            // Don't notify the manager for ephemeral apps as they are not expected to
2093            // survive long enough to benefit of background optimizations.
2094            for (int userId : firstUsers) {
2095                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2096                // There's a race currently where some install events may interleave with an uninstall.
2097                // This can lead to package info being null (b/36642664).
2098                if (info != null) {
2099                    mDexManager.notifyPackageInstalled(info, userId);
2100                }
2101            }
2102        }
2103
2104        // If someone is watching installs - notify them
2105        if (installObserver != null) {
2106            try {
2107                Bundle extras = extrasForInstallResult(res);
2108                installObserver.onPackageInstalled(res.name, res.returnCode,
2109                        res.returnMsg, extras);
2110            } catch (RemoteException e) {
2111                Slog.i(TAG, "Observer no longer exists.");
2112            }
2113        }
2114    }
2115
2116    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2117            PackageParser.Package pkg) {
2118        if (pkg.parentPackage == null) {
2119            return;
2120        }
2121        if (pkg.requestedPermissions == null) {
2122            return;
2123        }
2124        final PackageSetting disabledSysParentPs = mSettings
2125                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2126        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2127                || !disabledSysParentPs.isPrivileged()
2128                || (disabledSysParentPs.childPackageNames != null
2129                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2130            return;
2131        }
2132        final int[] allUserIds = sUserManager.getUserIds();
2133        final int permCount = pkg.requestedPermissions.size();
2134        for (int i = 0; i < permCount; i++) {
2135            String permission = pkg.requestedPermissions.get(i);
2136            BasePermission bp = mSettings.mPermissions.get(permission);
2137            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2138                continue;
2139            }
2140            for (int userId : allUserIds) {
2141                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2142                        permission, userId)) {
2143                    grantRuntimePermission(pkg.packageName, permission, userId);
2144                }
2145            }
2146        }
2147    }
2148
2149    private StorageEventListener mStorageListener = new StorageEventListener() {
2150        @Override
2151        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2152            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2153                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2154                    final String volumeUuid = vol.getFsUuid();
2155
2156                    // Clean up any users or apps that were removed or recreated
2157                    // while this volume was missing
2158                    sUserManager.reconcileUsers(volumeUuid);
2159                    reconcileApps(volumeUuid);
2160
2161                    // Clean up any install sessions that expired or were
2162                    // cancelled while this volume was missing
2163                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2164
2165                    loadPrivatePackages(vol);
2166
2167                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2168                    unloadPrivatePackages(vol);
2169                }
2170            }
2171
2172            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2173                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2174                    updateExternalMediaStatus(true, false);
2175                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2176                    updateExternalMediaStatus(false, false);
2177                }
2178            }
2179        }
2180
2181        @Override
2182        public void onVolumeForgotten(String fsUuid) {
2183            if (TextUtils.isEmpty(fsUuid)) {
2184                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2185                return;
2186            }
2187
2188            // Remove any apps installed on the forgotten volume
2189            synchronized (mPackages) {
2190                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2191                for (PackageSetting ps : packages) {
2192                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2193                    deletePackageVersioned(new VersionedPackage(ps.name,
2194                            PackageManager.VERSION_CODE_HIGHEST),
2195                            new LegacyPackageDeleteObserver(null).getBinder(),
2196                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2197                    // Try very hard to release any references to this package
2198                    // so we don't risk the system server being killed due to
2199                    // open FDs
2200                    AttributeCache.instance().removePackage(ps.name);
2201                }
2202
2203                mSettings.onVolumeForgotten(fsUuid);
2204                mSettings.writeLPr();
2205            }
2206        }
2207    };
2208
2209    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2210            String[] grantedPermissions) {
2211        for (int userId : userIds) {
2212            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2213        }
2214    }
2215
2216    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2217            String[] grantedPermissions) {
2218        PackageSetting ps = (PackageSetting) pkg.mExtras;
2219        if (ps == null) {
2220            return;
2221        }
2222
2223        PermissionsState permissionsState = ps.getPermissionsState();
2224
2225        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2226                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2227
2228        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2229                >= Build.VERSION_CODES.M;
2230
2231        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2232
2233        for (String permission : pkg.requestedPermissions) {
2234            final BasePermission bp;
2235            synchronized (mPackages) {
2236                bp = mSettings.mPermissions.get(permission);
2237            }
2238            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2239                    && (!instantApp || bp.isInstant())
2240                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2241                    && (grantedPermissions == null
2242                           || ArrayUtils.contains(grantedPermissions, permission))) {
2243                final int flags = permissionsState.getPermissionFlags(permission, userId);
2244                if (supportsRuntimePermissions) {
2245                    // Installer cannot change immutable permissions.
2246                    if ((flags & immutableFlags) == 0) {
2247                        grantRuntimePermission(pkg.packageName, permission, userId);
2248                    }
2249                } else if (mPermissionReviewRequired) {
2250                    // In permission review mode we clear the review flag when we
2251                    // are asked to install the app with all permissions granted.
2252                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2253                        updatePermissionFlags(permission, pkg.packageName,
2254                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2255                    }
2256                }
2257            }
2258        }
2259    }
2260
2261    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2262        Bundle extras = null;
2263        switch (res.returnCode) {
2264            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2265                extras = new Bundle();
2266                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2267                        res.origPermission);
2268                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2269                        res.origPackage);
2270                break;
2271            }
2272            case PackageManager.INSTALL_SUCCEEDED: {
2273                extras = new Bundle();
2274                extras.putBoolean(Intent.EXTRA_REPLACING,
2275                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2276                break;
2277            }
2278        }
2279        return extras;
2280    }
2281
2282    void scheduleWriteSettingsLocked() {
2283        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2284            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2285        }
2286    }
2287
2288    void scheduleWritePackageListLocked(int userId) {
2289        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2290            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2291            msg.arg1 = userId;
2292            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2293        }
2294    }
2295
2296    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2297        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2298        scheduleWritePackageRestrictionsLocked(userId);
2299    }
2300
2301    void scheduleWritePackageRestrictionsLocked(int userId) {
2302        final int[] userIds = (userId == UserHandle.USER_ALL)
2303                ? sUserManager.getUserIds() : new int[]{userId};
2304        for (int nextUserId : userIds) {
2305            if (!sUserManager.exists(nextUserId)) return;
2306            mDirtyUsers.add(nextUserId);
2307            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2308                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2309            }
2310        }
2311    }
2312
2313    public static PackageManagerService main(Context context, Installer installer,
2314            boolean factoryTest, boolean onlyCore) {
2315        // Self-check for initial settings.
2316        PackageManagerServiceCompilerMapping.checkProperties();
2317
2318        PackageManagerService m = new PackageManagerService(context, installer,
2319                factoryTest, onlyCore);
2320        m.enableSystemUserPackages();
2321        ServiceManager.addService("package", m);
2322        final PackageManagerNative pmn = m.new PackageManagerNative();
2323        ServiceManager.addService("package_native", pmn);
2324        return m;
2325    }
2326
2327    private void enableSystemUserPackages() {
2328        if (!UserManager.isSplitSystemUser()) {
2329            return;
2330        }
2331        // For system user, enable apps based on the following conditions:
2332        // - app is whitelisted or belong to one of these groups:
2333        //   -- system app which has no launcher icons
2334        //   -- system app which has INTERACT_ACROSS_USERS permission
2335        //   -- system IME app
2336        // - app is not in the blacklist
2337        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2338        Set<String> enableApps = new ArraySet<>();
2339        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2340                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2341                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2342        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2343        enableApps.addAll(wlApps);
2344        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2345                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2346        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2347        enableApps.removeAll(blApps);
2348        Log.i(TAG, "Applications installed for system user: " + enableApps);
2349        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2350                UserHandle.SYSTEM);
2351        final int allAppsSize = allAps.size();
2352        synchronized (mPackages) {
2353            for (int i = 0; i < allAppsSize; i++) {
2354                String pName = allAps.get(i);
2355                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2356                // Should not happen, but we shouldn't be failing if it does
2357                if (pkgSetting == null) {
2358                    continue;
2359                }
2360                boolean install = enableApps.contains(pName);
2361                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2362                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2363                            + " for system user");
2364                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2365                }
2366            }
2367            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2368        }
2369    }
2370
2371    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2372        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2373                Context.DISPLAY_SERVICE);
2374        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2375    }
2376
2377    /**
2378     * Requests that files preopted on a secondary system partition be copied to the data partition
2379     * if possible.  Note that the actual copying of the files is accomplished by init for security
2380     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2381     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2382     */
2383    private static void requestCopyPreoptedFiles() {
2384        final int WAIT_TIME_MS = 100;
2385        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2386        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2387            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2388            // We will wait for up to 100 seconds.
2389            final long timeStart = SystemClock.uptimeMillis();
2390            final long timeEnd = timeStart + 100 * 1000;
2391            long timeNow = timeStart;
2392            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2393                try {
2394                    Thread.sleep(WAIT_TIME_MS);
2395                } catch (InterruptedException e) {
2396                    // Do nothing
2397                }
2398                timeNow = SystemClock.uptimeMillis();
2399                if (timeNow > timeEnd) {
2400                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2401                    Slog.wtf(TAG, "cppreopt did not finish!");
2402                    break;
2403                }
2404            }
2405
2406            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2407        }
2408    }
2409
2410    public PackageManagerService(Context context, Installer installer,
2411            boolean factoryTest, boolean onlyCore) {
2412        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2413        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2414        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2415                SystemClock.uptimeMillis());
2416
2417        if (mSdkVersion <= 0) {
2418            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2419        }
2420
2421        mContext = context;
2422
2423        mPermissionReviewRequired = context.getResources().getBoolean(
2424                R.bool.config_permissionReviewRequired);
2425
2426        mFactoryTest = factoryTest;
2427        mOnlyCore = onlyCore;
2428        mMetrics = new DisplayMetrics();
2429        mSettings = new Settings(mPackages);
2430        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2431                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2439                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2440        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2441                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2442        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2443                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2444
2445        String separateProcesses = SystemProperties.get("debug.separate_processes");
2446        if (separateProcesses != null && separateProcesses.length() > 0) {
2447            if ("*".equals(separateProcesses)) {
2448                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2449                mSeparateProcesses = null;
2450                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2451            } else {
2452                mDefParseFlags = 0;
2453                mSeparateProcesses = separateProcesses.split(",");
2454                Slog.w(TAG, "Running with debug.separate_processes: "
2455                        + separateProcesses);
2456            }
2457        } else {
2458            mDefParseFlags = 0;
2459            mSeparateProcesses = null;
2460        }
2461
2462        mInstaller = installer;
2463        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2464                "*dexopt*");
2465        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2466                installer, mInstallLock);
2467        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2468                dexManagerListener);
2469        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2470
2471        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2472                FgThread.get().getLooper());
2473
2474        getDefaultDisplayMetrics(context, mMetrics);
2475
2476        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2477        SystemConfig systemConfig = SystemConfig.getInstance();
2478        mGlobalGids = systemConfig.getGlobalGids();
2479        mSystemPermissions = systemConfig.getSystemPermissions();
2480        mAvailableFeatures = systemConfig.getAvailableFeatures();
2481        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2482
2483        mProtectedPackages = new ProtectedPackages(mContext);
2484
2485        synchronized (mInstallLock) {
2486        // writer
2487        synchronized (mPackages) {
2488            mHandlerThread = new ServiceThread(TAG,
2489                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2490            mHandlerThread.start();
2491            mHandler = new PackageHandler(mHandlerThread.getLooper());
2492            mProcessLoggingHandler = new ProcessLoggingHandler();
2493            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2494
2495            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2496            mInstantAppRegistry = new InstantAppRegistry(this);
2497
2498            File dataDir = Environment.getDataDirectory();
2499            mAppInstallDir = new File(dataDir, "app");
2500            mAppLib32InstallDir = new File(dataDir, "app-lib");
2501            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2502            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2503            sUserManager = new UserManagerService(context, this,
2504                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2505
2506            // Propagate permission configuration in to package manager.
2507            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2508                    = systemConfig.getPermissions();
2509            for (int i=0; i<permConfig.size(); i++) {
2510                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2511                BasePermission bp = mSettings.mPermissions.get(perm.name);
2512                if (bp == null) {
2513                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2514                    mSettings.mPermissions.put(perm.name, bp);
2515                }
2516                if (perm.gids != null) {
2517                    bp.setGids(perm.gids, perm.perUser);
2518                }
2519            }
2520
2521            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2522            final int builtInLibCount = libConfig.size();
2523            for (int i = 0; i < builtInLibCount; i++) {
2524                String name = libConfig.keyAt(i);
2525                String path = libConfig.valueAt(i);
2526                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2527                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2528            }
2529
2530            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2531
2532            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2533            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2534            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2535
2536            // Clean up orphaned packages for which the code path doesn't exist
2537            // and they are an update to a system app - caused by bug/32321269
2538            final int packageSettingCount = mSettings.mPackages.size();
2539            for (int i = packageSettingCount - 1; i >= 0; i--) {
2540                PackageSetting ps = mSettings.mPackages.valueAt(i);
2541                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2542                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2543                    mSettings.mPackages.removeAt(i);
2544                    mSettings.enableSystemPackageLPw(ps.name);
2545                }
2546            }
2547
2548            if (mFirstBoot) {
2549                requestCopyPreoptedFiles();
2550            }
2551
2552            String customResolverActivity = Resources.getSystem().getString(
2553                    R.string.config_customResolverActivity);
2554            if (TextUtils.isEmpty(customResolverActivity)) {
2555                customResolverActivity = null;
2556            } else {
2557                mCustomResolverComponentName = ComponentName.unflattenFromString(
2558                        customResolverActivity);
2559            }
2560
2561            long startTime = SystemClock.uptimeMillis();
2562
2563            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2564                    startTime);
2565
2566            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2567            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2568
2569            if (bootClassPath == null) {
2570                Slog.w(TAG, "No BOOTCLASSPATH found!");
2571            }
2572
2573            if (systemServerClassPath == null) {
2574                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2575            }
2576
2577            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2578
2579            final VersionInfo ver = mSettings.getInternalVersion();
2580            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2581            if (mIsUpgrade) {
2582                logCriticalInfo(Log.INFO,
2583                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2584            }
2585
2586            // when upgrading from pre-M, promote system app permissions from install to runtime
2587            mPromoteSystemApps =
2588                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2589
2590            // When upgrading from pre-N, we need to handle package extraction like first boot,
2591            // as there is no profiling data available.
2592            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2593
2594            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2595
2596            // save off the names of pre-existing system packages prior to scanning; we don't
2597            // want to automatically grant runtime permissions for new system apps
2598            if (mPromoteSystemApps) {
2599                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2600                while (pkgSettingIter.hasNext()) {
2601                    PackageSetting ps = pkgSettingIter.next();
2602                    if (isSystemApp(ps)) {
2603                        mExistingSystemPackages.add(ps.name);
2604                    }
2605                }
2606            }
2607
2608            mCacheDir = preparePackageParserCache(mIsUpgrade);
2609
2610            // Set flag to monitor and not change apk file paths when
2611            // scanning install directories.
2612            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2613
2614            if (mIsUpgrade || mFirstBoot) {
2615                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2616            }
2617
2618            // Collect vendor overlay packages. (Do this before scanning any apps.)
2619            // For security and version matching reason, only consider
2620            // overlay packages if they reside in the right directory.
2621            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR
2624                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2625
2626            mParallelPackageParserCallback.findStaticOverlayPackages();
2627
2628            // Find base frameworks (resource packages without code).
2629            scanDirTracedLI(frameworkDir, mDefParseFlags
2630                    | PackageParser.PARSE_IS_SYSTEM
2631                    | PackageParser.PARSE_IS_SYSTEM_DIR
2632                    | PackageParser.PARSE_IS_PRIVILEGED,
2633                    scanFlags | SCAN_NO_DEX, 0);
2634
2635            // Collected privileged system packages.
2636            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2637            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2638                    | PackageParser.PARSE_IS_SYSTEM
2639                    | PackageParser.PARSE_IS_SYSTEM_DIR
2640                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2641
2642            // Collect ordinary system packages.
2643            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2644            scanDirTracedLI(systemAppDir, mDefParseFlags
2645                    | PackageParser.PARSE_IS_SYSTEM
2646                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2647
2648            // Collect all vendor packages.
2649            File vendorAppDir = new File("/vendor/app");
2650            try {
2651                vendorAppDir = vendorAppDir.getCanonicalFile();
2652            } catch (IOException e) {
2653                // failed to look up canonical path, continue with original one
2654            }
2655            scanDirTracedLI(vendorAppDir, mDefParseFlags
2656                    | PackageParser.PARSE_IS_SYSTEM
2657                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2658
2659            // Collect all OEM packages.
2660            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2661            scanDirTracedLI(oemAppDir, mDefParseFlags
2662                    | PackageParser.PARSE_IS_SYSTEM
2663                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2664
2665            // Prune any system packages that no longer exist.
2666            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2667            // Stub packages must either be replaced with full versions in the /data
2668            // partition or be disabled.
2669            final List<String> stubSystemApps = new ArrayList<>();
2670            if (!mOnlyCore) {
2671                // do this first before mucking with mPackages for the "expecting better" case
2672                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2673                while (pkgIterator.hasNext()) {
2674                    final PackageParser.Package pkg = pkgIterator.next();
2675                    if (pkg.isStub) {
2676                        stubSystemApps.add(pkg.packageName);
2677                    }
2678                }
2679
2680                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2681                while (psit.hasNext()) {
2682                    PackageSetting ps = psit.next();
2683
2684                    /*
2685                     * If this is not a system app, it can't be a
2686                     * disable system app.
2687                     */
2688                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2689                        continue;
2690                    }
2691
2692                    /*
2693                     * If the package is scanned, it's not erased.
2694                     */
2695                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2696                    if (scannedPkg != null) {
2697                        /*
2698                         * If the system app is both scanned and in the
2699                         * disabled packages list, then it must have been
2700                         * added via OTA. Remove it from the currently
2701                         * scanned package so the previously user-installed
2702                         * application can be scanned.
2703                         */
2704                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2705                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2706                                    + ps.name + "; removing system app.  Last known codePath="
2707                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2708                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2709                                    + scannedPkg.mVersionCode);
2710                            removePackageLI(scannedPkg, true);
2711                            mExpectingBetter.put(ps.name, ps.codePath);
2712                        }
2713
2714                        continue;
2715                    }
2716
2717                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2718                        psit.remove();
2719                        logCriticalInfo(Log.WARN, "System package " + ps.name
2720                                + " no longer exists; it's data will be wiped");
2721                        // Actual deletion of code and data will be handled by later
2722                        // reconciliation step
2723                    } else {
2724                        // we still have a disabled system package, but, it still might have
2725                        // been removed. check the code path still exists and check there's
2726                        // still a package. the latter can happen if an OTA keeps the same
2727                        // code path, but, changes the package name.
2728                        final PackageSetting disabledPs =
2729                                mSettings.getDisabledSystemPkgLPr(ps.name);
2730                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2731                                || disabledPs.pkg == null) {
2732                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2733                        }
2734                    }
2735                }
2736            }
2737
2738            //look for any incomplete package installations
2739            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2740            for (int i = 0; i < deletePkgsList.size(); i++) {
2741                // Actual deletion of code and data will be handled by later
2742                // reconciliation step
2743                final String packageName = deletePkgsList.get(i).name;
2744                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2745                synchronized (mPackages) {
2746                    mSettings.removePackageLPw(packageName);
2747                }
2748            }
2749
2750            //delete tmp files
2751            deleteTempPackageFiles();
2752
2753            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2754
2755            // Remove any shared userIDs that have no associated packages
2756            mSettings.pruneSharedUsersLPw();
2757            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2758            final int systemPackagesCount = mPackages.size();
2759            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2760                    + " ms, packageCount: " + systemPackagesCount
2761                    + " , timePerPackage: "
2762                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2763                    + " , cached: " + cachedSystemApps);
2764            if (mIsUpgrade && systemPackagesCount > 0) {
2765                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2766                        ((int) systemScanTime) / systemPackagesCount);
2767            }
2768            if (!mOnlyCore) {
2769                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2770                        SystemClock.uptimeMillis());
2771                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2772
2773                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2774                        | PackageParser.PARSE_FORWARD_LOCK,
2775                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2776
2777                // Remove disable package settings for updated system apps that were
2778                // removed via an OTA. If the update is no longer present, remove the
2779                // app completely. Otherwise, revoke their system privileges.
2780                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2781                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2782                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2783
2784                    final String msg;
2785                    if (deletedPkg == null) {
2786                        // should have found an update, but, we didn't; remove everything
2787                        msg = "Updated system package " + deletedAppName
2788                                + " no longer exists; removing its data";
2789                        // Actual deletion of code and data will be handled by later
2790                        // reconciliation step
2791                    } else {
2792                        // found an update; revoke system privileges
2793                        msg = "Updated system package + " + deletedAppName
2794                                + " no longer exists; revoking system privileges";
2795
2796                        // Don't do anything if a stub is removed from the system image. If
2797                        // we were to remove the uncompressed version from the /data partition,
2798                        // this is where it'd be done.
2799
2800                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2801                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2802                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2803                    }
2804                    logCriticalInfo(Log.WARN, msg);
2805                }
2806
2807                /*
2808                 * Make sure all system apps that we expected to appear on
2809                 * the userdata partition actually showed up. If they never
2810                 * appeared, crawl back and revive the system version.
2811                 */
2812                for (int i = 0; i < mExpectingBetter.size(); i++) {
2813                    final String packageName = mExpectingBetter.keyAt(i);
2814                    if (!mPackages.containsKey(packageName)) {
2815                        final File scanFile = mExpectingBetter.valueAt(i);
2816
2817                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2818                                + " but never showed up; reverting to system");
2819
2820                        int reparseFlags = mDefParseFlags;
2821                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2822                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2823                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2824                                    | PackageParser.PARSE_IS_PRIVILEGED;
2825                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2826                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2827                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2828                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2829                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2830                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2831                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2832                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2833                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2834                        } else {
2835                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2836                            continue;
2837                        }
2838
2839                        mSettings.enableSystemPackageLPw(packageName);
2840
2841                        try {
2842                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2843                        } catch (PackageManagerException e) {
2844                            Slog.e(TAG, "Failed to parse original system package: "
2845                                    + e.getMessage());
2846                        }
2847                    }
2848                }
2849
2850                // Uncompress and install any stubbed system applications.
2851                // This must be done last to ensure all stubs are replaced or disabled.
2852                decompressSystemApplications(stubSystemApps, scanFlags);
2853
2854                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2855                                - cachedSystemApps;
2856
2857                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2858                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2859                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2860                        + " ms, packageCount: " + dataPackagesCount
2861                        + " , timePerPackage: "
2862                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2863                        + " , cached: " + cachedNonSystemApps);
2864                if (mIsUpgrade && dataPackagesCount > 0) {
2865                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2866                            ((int) dataScanTime) / dataPackagesCount);
2867                }
2868            }
2869            mExpectingBetter.clear();
2870
2871            // Resolve the storage manager.
2872            mStorageManagerPackage = getStorageManagerPackageName();
2873
2874            // Resolve protected action filters. Only the setup wizard is allowed to
2875            // have a high priority filter for these actions.
2876            mSetupWizardPackage = getSetupWizardPackageName();
2877            if (mProtectedFilters.size() > 0) {
2878                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2879                    Slog.i(TAG, "No setup wizard;"
2880                        + " All protected intents capped to priority 0");
2881                }
2882                for (ActivityIntentInfo filter : mProtectedFilters) {
2883                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2884                        if (DEBUG_FILTERS) {
2885                            Slog.i(TAG, "Found setup wizard;"
2886                                + " allow priority " + filter.getPriority() + ";"
2887                                + " package: " + filter.activity.info.packageName
2888                                + " activity: " + filter.activity.className
2889                                + " priority: " + filter.getPriority());
2890                        }
2891                        // skip setup wizard; allow it to keep the high priority filter
2892                        continue;
2893                    }
2894                    if (DEBUG_FILTERS) {
2895                        Slog.i(TAG, "Protected action; cap priority to 0;"
2896                                + " package: " + filter.activity.info.packageName
2897                                + " activity: " + filter.activity.className
2898                                + " origPrio: " + filter.getPriority());
2899                    }
2900                    filter.setPriority(0);
2901                }
2902            }
2903            mDeferProtectedFilters = false;
2904            mProtectedFilters.clear();
2905
2906            // Now that we know all of the shared libraries, update all clients to have
2907            // the correct library paths.
2908            updateAllSharedLibrariesLPw(null);
2909
2910            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2911                // NOTE: We ignore potential failures here during a system scan (like
2912                // the rest of the commands above) because there's precious little we
2913                // can do about it. A settings error is reported, though.
2914                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2915            }
2916
2917            // Now that we know all the packages we are keeping,
2918            // read and update their last usage times.
2919            mPackageUsage.read(mPackages);
2920            mCompilerStats.read();
2921
2922            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2923                    SystemClock.uptimeMillis());
2924            Slog.i(TAG, "Time to scan packages: "
2925                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2926                    + " seconds");
2927
2928            // If the platform SDK has changed since the last time we booted,
2929            // we need to re-grant app permission to catch any new ones that
2930            // appear.  This is really a hack, and means that apps can in some
2931            // cases get permissions that the user didn't initially explicitly
2932            // allow...  it would be nice to have some better way to handle
2933            // this situation.
2934            int updateFlags = UPDATE_PERMISSIONS_ALL;
2935            if (ver.sdkVersion != mSdkVersion) {
2936                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2937                        + mSdkVersion + "; regranting permissions for internal storage");
2938                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2939            }
2940            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2941            ver.sdkVersion = mSdkVersion;
2942
2943            // If this is the first boot or an update from pre-M, and it is a normal
2944            // boot, then we need to initialize the default preferred apps across
2945            // all defined users.
2946            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2947                for (UserInfo user : sUserManager.getUsers(true)) {
2948                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2949                    applyFactoryDefaultBrowserLPw(user.id);
2950                    primeDomainVerificationsLPw(user.id);
2951                }
2952            }
2953
2954            // Prepare storage for system user really early during boot,
2955            // since core system apps like SettingsProvider and SystemUI
2956            // can't wait for user to start
2957            final int storageFlags;
2958            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2959                storageFlags = StorageManager.FLAG_STORAGE_DE;
2960            } else {
2961                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2962            }
2963            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2964                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2965                    true /* onlyCoreApps */);
2966            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2967                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2968                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2969                traceLog.traceBegin("AppDataFixup");
2970                try {
2971                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2972                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2973                } catch (InstallerException e) {
2974                    Slog.w(TAG, "Trouble fixing GIDs", e);
2975                }
2976                traceLog.traceEnd();
2977
2978                traceLog.traceBegin("AppDataPrepare");
2979                if (deferPackages == null || deferPackages.isEmpty()) {
2980                    return;
2981                }
2982                int count = 0;
2983                for (String pkgName : deferPackages) {
2984                    PackageParser.Package pkg = null;
2985                    synchronized (mPackages) {
2986                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2987                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2988                            pkg = ps.pkg;
2989                        }
2990                    }
2991                    if (pkg != null) {
2992                        synchronized (mInstallLock) {
2993                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2994                                    true /* maybeMigrateAppData */);
2995                        }
2996                        count++;
2997                    }
2998                }
2999                traceLog.traceEnd();
3000                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3001            }, "prepareAppData");
3002
3003            // If this is first boot after an OTA, and a normal boot, then
3004            // we need to clear code cache directories.
3005            // Note that we do *not* clear the application profiles. These remain valid
3006            // across OTAs and are used to drive profile verification (post OTA) and
3007            // profile compilation (without waiting to collect a fresh set of profiles).
3008            if (mIsUpgrade && !onlyCore) {
3009                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3010                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3011                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3012                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3013                        // No apps are running this early, so no need to freeze
3014                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3015                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3016                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3017                    }
3018                }
3019                ver.fingerprint = Build.FINGERPRINT;
3020            }
3021
3022            checkDefaultBrowser();
3023
3024            // clear only after permissions and other defaults have been updated
3025            mExistingSystemPackages.clear();
3026            mPromoteSystemApps = false;
3027
3028            // All the changes are done during package scanning.
3029            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3030
3031            // can downgrade to reader
3032            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3033            mSettings.writeLPr();
3034            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3035            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3036                    SystemClock.uptimeMillis());
3037
3038            if (!mOnlyCore) {
3039                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3040                mRequiredInstallerPackage = getRequiredInstallerLPr();
3041                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3042                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3043                if (mIntentFilterVerifierComponent != null) {
3044                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3045                            mIntentFilterVerifierComponent);
3046                } else {
3047                    mIntentFilterVerifier = null;
3048                }
3049                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3050                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3051                        SharedLibraryInfo.VERSION_UNDEFINED);
3052                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3053                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3054                        SharedLibraryInfo.VERSION_UNDEFINED);
3055            } else {
3056                mRequiredVerifierPackage = null;
3057                mRequiredInstallerPackage = null;
3058                mRequiredUninstallerPackage = null;
3059                mIntentFilterVerifierComponent = null;
3060                mIntentFilterVerifier = null;
3061                mServicesSystemSharedLibraryPackageName = null;
3062                mSharedSystemSharedLibraryPackageName = null;
3063            }
3064
3065            mInstallerService = new PackageInstallerService(context, this);
3066            final Pair<ComponentName, String> instantAppResolverComponent =
3067                    getInstantAppResolverLPr();
3068            if (instantAppResolverComponent != null) {
3069                if (DEBUG_EPHEMERAL) {
3070                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3071                }
3072                mInstantAppResolverConnection = new EphemeralResolverConnection(
3073                        mContext, instantAppResolverComponent.first,
3074                        instantAppResolverComponent.second);
3075                mInstantAppResolverSettingsComponent =
3076                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3077            } else {
3078                mInstantAppResolverConnection = null;
3079                mInstantAppResolverSettingsComponent = null;
3080            }
3081            updateInstantAppInstallerLocked(null);
3082
3083            // Read and update the usage of dex files.
3084            // Do this at the end of PM init so that all the packages have their
3085            // data directory reconciled.
3086            // At this point we know the code paths of the packages, so we can validate
3087            // the disk file and build the internal cache.
3088            // The usage file is expected to be small so loading and verifying it
3089            // should take a fairly small time compare to the other activities (e.g. package
3090            // scanning).
3091            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3092            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3093            for (int userId : currentUserIds) {
3094                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3095            }
3096            mDexManager.load(userPackages);
3097            if (mIsUpgrade) {
3098                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3099                        (int) (SystemClock.uptimeMillis() - startTime));
3100            }
3101        } // synchronized (mPackages)
3102        } // synchronized (mInstallLock)
3103
3104        // Now after opening every single application zip, make sure they
3105        // are all flushed.  Not really needed, but keeps things nice and
3106        // tidy.
3107        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3108        Runtime.getRuntime().gc();
3109        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3110
3111        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3112        FallbackCategoryProvider.loadFallbacks();
3113        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3114
3115        // The initial scanning above does many calls into installd while
3116        // holding the mPackages lock, but we're mostly interested in yelling
3117        // once we have a booted system.
3118        mInstaller.setWarnIfHeld(mPackages);
3119
3120        // Expose private service for system components to use.
3121        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3122        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3123    }
3124
3125    /**
3126     * Uncompress and install stub applications.
3127     * <p>In order to save space on the system partition, some applications are shipped in a
3128     * compressed form. In addition the compressed bits for the full application, the
3129     * system image contains a tiny stub comprised of only the Android manifest.
3130     * <p>During the first boot, attempt to uncompress and install the full application. If
3131     * the application can't be installed for any reason, disable the stub and prevent
3132     * uncompressing the full application during future boots.
3133     * <p>In order to forcefully attempt an installation of a full application, go to app
3134     * settings and enable the application.
3135     */
3136    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3137        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3138            final String pkgName = stubSystemApps.get(i);
3139            // skip if the system package is already disabled
3140            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3141                stubSystemApps.remove(i);
3142                continue;
3143            }
3144            // skip if the package isn't installed (?!); this should never happen
3145            final PackageParser.Package pkg = mPackages.get(pkgName);
3146            if (pkg == null) {
3147                stubSystemApps.remove(i);
3148                continue;
3149            }
3150            // skip if the package has been disabled by the user
3151            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3152            if (ps != null) {
3153                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3154                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3155                    stubSystemApps.remove(i);
3156                    continue;
3157                }
3158            }
3159
3160            if (DEBUG_COMPRESSION) {
3161                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3162            }
3163
3164            // uncompress the binary to its eventual destination on /data
3165            final File scanFile = decompressPackage(pkg);
3166            if (scanFile == null) {
3167                continue;
3168            }
3169
3170            // install the package to replace the stub on /system
3171            try {
3172                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3173                removePackageLI(pkg, true /*chatty*/);
3174                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3175                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3176                        UserHandle.USER_SYSTEM, "android");
3177                stubSystemApps.remove(i);
3178                continue;
3179            } catch (PackageManagerException e) {
3180                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3181            }
3182
3183            // any failed attempt to install the package will be cleaned up later
3184        }
3185
3186        // disable any stub still left; these failed to install the full application
3187        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3188            final String pkgName = stubSystemApps.get(i);
3189            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3190            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3191                    UserHandle.USER_SYSTEM, "android");
3192            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3193        }
3194    }
3195
3196    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3197        if (DEBUG_COMPRESSION) {
3198            Slog.i(TAG, "Decompress file"
3199                    + "; src: " + srcFile.getAbsolutePath()
3200                    + ", dst: " + dstFile.getAbsolutePath());
3201        }
3202        try (
3203                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3204                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3205        ) {
3206            Streams.copy(fileIn, fileOut);
3207            Os.chmod(dstFile.getAbsolutePath(), 0644);
3208            return PackageManager.INSTALL_SUCCEEDED;
3209        } catch (IOException e) {
3210            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3211                    + "; src: " + srcFile.getAbsolutePath()
3212                    + ", dst: " + dstFile.getAbsolutePath());
3213        }
3214        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3215    }
3216
3217    private File[] getCompressedFiles(String codePath) {
3218        final File stubCodePath = new File(codePath);
3219        final String stubName = stubCodePath.getName();
3220
3221        // The layout of a compressed package on a given partition is as follows :
3222        //
3223        // Compressed artifacts:
3224        //
3225        // /partition/ModuleName/foo.gz
3226        // /partation/ModuleName/bar.gz
3227        //
3228        // Stub artifact:
3229        //
3230        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3231        //
3232        // In other words, stub is on the same partition as the compressed artifacts
3233        // and in a directory that's suffixed with "-Stub".
3234        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3235        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3236            return null;
3237        }
3238
3239        final File stubParentDir = stubCodePath.getParentFile();
3240        if (stubParentDir == null) {
3241            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3242            return null;
3243        }
3244
3245        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3246        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3247            @Override
3248            public boolean accept(File dir, String name) {
3249                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3250            }
3251        });
3252
3253        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3254            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3255        }
3256
3257        return files;
3258    }
3259
3260    private boolean compressedFileExists(String codePath) {
3261        final File[] compressedFiles = getCompressedFiles(codePath);
3262        return compressedFiles != null && compressedFiles.length > 0;
3263    }
3264
3265    /**
3266     * Decompresses the given package on the system image onto
3267     * the /data partition.
3268     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3269     */
3270    private File decompressPackage(PackageParser.Package pkg) {
3271        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3272        if (compressedFiles == null || compressedFiles.length == 0) {
3273            if (DEBUG_COMPRESSION) {
3274                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3275            }
3276            return null;
3277        }
3278        final File dstCodePath =
3279                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3280        int ret = PackageManager.INSTALL_SUCCEEDED;
3281        try {
3282            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3283            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3284            for (File srcFile : compressedFiles) {
3285                final String srcFileName = srcFile.getName();
3286                final String dstFileName = srcFileName.substring(
3287                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3288                final File dstFile = new File(dstCodePath, dstFileName);
3289                ret = decompressFile(srcFile, dstFile);
3290                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3291                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3292                            + "; pkg: " + pkg.packageName
3293                            + ", file: " + dstFileName);
3294                    break;
3295                }
3296            }
3297        } catch (ErrnoException e) {
3298            logCriticalInfo(Log.ERROR, "Failed to decompress"
3299                    + "; pkg: " + pkg.packageName
3300                    + ", err: " + e.errno);
3301        }
3302        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3303            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3304            NativeLibraryHelper.Handle handle = null;
3305            try {
3306                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3307                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3308                        null /*abiOverride*/);
3309            } catch (IOException e) {
3310                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3311                        + "; pkg: " + pkg.packageName);
3312                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3313            } finally {
3314                IoUtils.closeQuietly(handle);
3315            }
3316        }
3317        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3318            if (dstCodePath == null || !dstCodePath.exists()) {
3319                return null;
3320            }
3321            removeCodePathLI(dstCodePath);
3322            return null;
3323        }
3324
3325        return dstCodePath;
3326    }
3327
3328    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3329        // we're only interested in updating the installer appliction when 1) it's not
3330        // already set or 2) the modified package is the installer
3331        if (mInstantAppInstallerActivity != null
3332                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3333                        .equals(modifiedPackage)) {
3334            return;
3335        }
3336        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3337    }
3338
3339    private static File preparePackageParserCache(boolean isUpgrade) {
3340        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3341            return null;
3342        }
3343
3344        // Disable package parsing on eng builds to allow for faster incremental development.
3345        if (Build.IS_ENG) {
3346            return null;
3347        }
3348
3349        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3350            Slog.i(TAG, "Disabling package parser cache due to system property.");
3351            return null;
3352        }
3353
3354        // The base directory for the package parser cache lives under /data/system/.
3355        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3356                "package_cache");
3357        if (cacheBaseDir == null) {
3358            return null;
3359        }
3360
3361        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3362        // This also serves to "GC" unused entries when the package cache version changes (which
3363        // can only happen during upgrades).
3364        if (isUpgrade) {
3365            FileUtils.deleteContents(cacheBaseDir);
3366        }
3367
3368
3369        // Return the versioned package cache directory. This is something like
3370        // "/data/system/package_cache/1"
3371        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3372
3373        // The following is a workaround to aid development on non-numbered userdebug
3374        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3375        // the system partition is newer.
3376        //
3377        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3378        // that starts with "eng." to signify that this is an engineering build and not
3379        // destined for release.
3380        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3381            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3382
3383            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3384            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3385            // in general and should not be used for production changes. In this specific case,
3386            // we know that they will work.
3387            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3388            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3389                FileUtils.deleteContents(cacheBaseDir);
3390                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3391            }
3392        }
3393
3394        return cacheDir;
3395    }
3396
3397    @Override
3398    public boolean isFirstBoot() {
3399        // allow instant applications
3400        return mFirstBoot;
3401    }
3402
3403    @Override
3404    public boolean isOnlyCoreApps() {
3405        // allow instant applications
3406        return mOnlyCore;
3407    }
3408
3409    @Override
3410    public boolean isUpgrade() {
3411        // allow instant applications
3412        return mIsUpgrade;
3413    }
3414
3415    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3416        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3417
3418        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3419                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3420                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3421        if (matches.size() == 1) {
3422            return matches.get(0).getComponentInfo().packageName;
3423        } else if (matches.size() == 0) {
3424            Log.e(TAG, "There should probably be a verifier, but, none were found");
3425            return null;
3426        }
3427        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3428    }
3429
3430    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3431        synchronized (mPackages) {
3432            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3433            if (libraryEntry == null) {
3434                throw new IllegalStateException("Missing required shared library:" + name);
3435            }
3436            return libraryEntry.apk;
3437        }
3438    }
3439
3440    private @NonNull String getRequiredInstallerLPr() {
3441        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3442        intent.addCategory(Intent.CATEGORY_DEFAULT);
3443        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3444
3445        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3446                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3447                UserHandle.USER_SYSTEM);
3448        if (matches.size() == 1) {
3449            ResolveInfo resolveInfo = matches.get(0);
3450            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3451                throw new RuntimeException("The installer must be a privileged app");
3452            }
3453            return matches.get(0).getComponentInfo().packageName;
3454        } else {
3455            throw new RuntimeException("There must be exactly one installer; found " + matches);
3456        }
3457    }
3458
3459    private @NonNull String getRequiredUninstallerLPr() {
3460        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3461        intent.addCategory(Intent.CATEGORY_DEFAULT);
3462        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3463
3464        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3465                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3466                UserHandle.USER_SYSTEM);
3467        if (resolveInfo == null ||
3468                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3469            throw new RuntimeException("There must be exactly one uninstaller; found "
3470                    + resolveInfo);
3471        }
3472        return resolveInfo.getComponentInfo().packageName;
3473    }
3474
3475    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3476        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3477
3478        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3479                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3480                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3481        ResolveInfo best = null;
3482        final int N = matches.size();
3483        for (int i = 0; i < N; i++) {
3484            final ResolveInfo cur = matches.get(i);
3485            final String packageName = cur.getComponentInfo().packageName;
3486            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3487                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3488                continue;
3489            }
3490
3491            if (best == null || cur.priority > best.priority) {
3492                best = cur;
3493            }
3494        }
3495
3496        if (best != null) {
3497            return best.getComponentInfo().getComponentName();
3498        }
3499        Slog.w(TAG, "Intent filter verifier not found");
3500        return null;
3501    }
3502
3503    @Override
3504    public @Nullable ComponentName getInstantAppResolverComponent() {
3505        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3506            return null;
3507        }
3508        synchronized (mPackages) {
3509            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3510            if (instantAppResolver == null) {
3511                return null;
3512            }
3513            return instantAppResolver.first;
3514        }
3515    }
3516
3517    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3518        final String[] packageArray =
3519                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3520        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3521            if (DEBUG_EPHEMERAL) {
3522                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3523            }
3524            return null;
3525        }
3526
3527        final int callingUid = Binder.getCallingUid();
3528        final int resolveFlags =
3529                MATCH_DIRECT_BOOT_AWARE
3530                | MATCH_DIRECT_BOOT_UNAWARE
3531                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3532        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3533        final Intent resolverIntent = new Intent(actionName);
3534        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3535                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3536        // temporarily look for the old action
3537        if (resolvers.size() == 0) {
3538            if (DEBUG_EPHEMERAL) {
3539                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3540            }
3541            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3542            resolverIntent.setAction(actionName);
3543            resolvers = queryIntentServicesInternal(resolverIntent, null,
3544                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3545        }
3546        final int N = resolvers.size();
3547        if (N == 0) {
3548            if (DEBUG_EPHEMERAL) {
3549                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3550            }
3551            return null;
3552        }
3553
3554        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3555        for (int i = 0; i < N; i++) {
3556            final ResolveInfo info = resolvers.get(i);
3557
3558            if (info.serviceInfo == null) {
3559                continue;
3560            }
3561
3562            final String packageName = info.serviceInfo.packageName;
3563            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3564                if (DEBUG_EPHEMERAL) {
3565                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3566                            + " pkg: " + packageName + ", info:" + info);
3567                }
3568                continue;
3569            }
3570
3571            if (DEBUG_EPHEMERAL) {
3572                Slog.v(TAG, "Ephemeral resolver found;"
3573                        + " pkg: " + packageName + ", info:" + info);
3574            }
3575            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3576        }
3577        if (DEBUG_EPHEMERAL) {
3578            Slog.v(TAG, "Ephemeral resolver NOT found");
3579        }
3580        return null;
3581    }
3582
3583    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3584        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3585        intent.addCategory(Intent.CATEGORY_DEFAULT);
3586        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3587
3588        final int resolveFlags =
3589                MATCH_DIRECT_BOOT_AWARE
3590                | MATCH_DIRECT_BOOT_UNAWARE
3591                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3592        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3593                resolveFlags, UserHandle.USER_SYSTEM);
3594        // temporarily look for the old action
3595        if (matches.isEmpty()) {
3596            if (DEBUG_EPHEMERAL) {
3597                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3598            }
3599            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3600            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3601                    resolveFlags, UserHandle.USER_SYSTEM);
3602        }
3603        Iterator<ResolveInfo> iter = matches.iterator();
3604        while (iter.hasNext()) {
3605            final ResolveInfo rInfo = iter.next();
3606            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3607            if (ps != null) {
3608                final PermissionsState permissionsState = ps.getPermissionsState();
3609                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3610                    continue;
3611                }
3612            }
3613            iter.remove();
3614        }
3615        if (matches.size() == 0) {
3616            return null;
3617        } else if (matches.size() == 1) {
3618            return (ActivityInfo) matches.get(0).getComponentInfo();
3619        } else {
3620            throw new RuntimeException(
3621                    "There must be at most one ephemeral installer; found " + matches);
3622        }
3623    }
3624
3625    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3626            @NonNull ComponentName resolver) {
3627        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3628                .addCategory(Intent.CATEGORY_DEFAULT)
3629                .setPackage(resolver.getPackageName());
3630        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3631        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3632                UserHandle.USER_SYSTEM);
3633        // temporarily look for the old action
3634        if (matches.isEmpty()) {
3635            if (DEBUG_EPHEMERAL) {
3636                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3637            }
3638            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3639            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3640                    UserHandle.USER_SYSTEM);
3641        }
3642        if (matches.isEmpty()) {
3643            return null;
3644        }
3645        return matches.get(0).getComponentInfo().getComponentName();
3646    }
3647
3648    private void primeDomainVerificationsLPw(int userId) {
3649        if (DEBUG_DOMAIN_VERIFICATION) {
3650            Slog.d(TAG, "Priming domain verifications in user " + userId);
3651        }
3652
3653        SystemConfig systemConfig = SystemConfig.getInstance();
3654        ArraySet<String> packages = systemConfig.getLinkedApps();
3655
3656        for (String packageName : packages) {
3657            PackageParser.Package pkg = mPackages.get(packageName);
3658            if (pkg != null) {
3659                if (!pkg.isSystemApp()) {
3660                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3661                    continue;
3662                }
3663
3664                ArraySet<String> domains = null;
3665                for (PackageParser.Activity a : pkg.activities) {
3666                    for (ActivityIntentInfo filter : a.intents) {
3667                        if (hasValidDomains(filter)) {
3668                            if (domains == null) {
3669                                domains = new ArraySet<String>();
3670                            }
3671                            domains.addAll(filter.getHostsList());
3672                        }
3673                    }
3674                }
3675
3676                if (domains != null && domains.size() > 0) {
3677                    if (DEBUG_DOMAIN_VERIFICATION) {
3678                        Slog.v(TAG, "      + " + packageName);
3679                    }
3680                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3681                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3682                    // and then 'always' in the per-user state actually used for intent resolution.
3683                    final IntentFilterVerificationInfo ivi;
3684                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3685                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3686                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3687                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3688                } else {
3689                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3690                            + "' does not handle web links");
3691                }
3692            } else {
3693                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3694            }
3695        }
3696
3697        scheduleWritePackageRestrictionsLocked(userId);
3698        scheduleWriteSettingsLocked();
3699    }
3700
3701    private void applyFactoryDefaultBrowserLPw(int userId) {
3702        // The default browser app's package name is stored in a string resource,
3703        // with a product-specific overlay used for vendor customization.
3704        String browserPkg = mContext.getResources().getString(
3705                com.android.internal.R.string.default_browser);
3706        if (!TextUtils.isEmpty(browserPkg)) {
3707            // non-empty string => required to be a known package
3708            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3709            if (ps == null) {
3710                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3711                browserPkg = null;
3712            } else {
3713                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3714            }
3715        }
3716
3717        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3718        // default.  If there's more than one, just leave everything alone.
3719        if (browserPkg == null) {
3720            calculateDefaultBrowserLPw(userId);
3721        }
3722    }
3723
3724    private void calculateDefaultBrowserLPw(int userId) {
3725        List<String> allBrowsers = resolveAllBrowserApps(userId);
3726        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3727        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3728    }
3729
3730    private List<String> resolveAllBrowserApps(int userId) {
3731        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3732        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3733                PackageManager.MATCH_ALL, userId);
3734
3735        final int count = list.size();
3736        List<String> result = new ArrayList<String>(count);
3737        for (int i=0; i<count; i++) {
3738            ResolveInfo info = list.get(i);
3739            if (info.activityInfo == null
3740                    || !info.handleAllWebDataURI
3741                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3742                    || result.contains(info.activityInfo.packageName)) {
3743                continue;
3744            }
3745            result.add(info.activityInfo.packageName);
3746        }
3747
3748        return result;
3749    }
3750
3751    private boolean packageIsBrowser(String packageName, int userId) {
3752        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3753                PackageManager.MATCH_ALL, userId);
3754        final int N = list.size();
3755        for (int i = 0; i < N; i++) {
3756            ResolveInfo info = list.get(i);
3757            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3758                return true;
3759            }
3760        }
3761        return false;
3762    }
3763
3764    private void checkDefaultBrowser() {
3765        final int myUserId = UserHandle.myUserId();
3766        final String packageName = getDefaultBrowserPackageName(myUserId);
3767        if (packageName != null) {
3768            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3769            if (info == null) {
3770                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3771                synchronized (mPackages) {
3772                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3773                }
3774            }
3775        }
3776    }
3777
3778    @Override
3779    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3780            throws RemoteException {
3781        try {
3782            return super.onTransact(code, data, reply, flags);
3783        } catch (RuntimeException e) {
3784            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3785                Slog.wtf(TAG, "Package Manager Crash", e);
3786            }
3787            throw e;
3788        }
3789    }
3790
3791    static int[] appendInts(int[] cur, int[] add) {
3792        if (add == null) return cur;
3793        if (cur == null) return add;
3794        final int N = add.length;
3795        for (int i=0; i<N; i++) {
3796            cur = appendInt(cur, add[i]);
3797        }
3798        return cur;
3799    }
3800
3801    /**
3802     * Returns whether or not a full application can see an instant application.
3803     * <p>
3804     * Currently, there are three cases in which this can occur:
3805     * <ol>
3806     * <li>The calling application is a "special" process. The special
3807     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3808     *     and {@code 0}</li>
3809     * <li>The calling application has the permission
3810     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3811     * <li>The calling application is the default launcher on the
3812     *     system partition.</li>
3813     * </ol>
3814     */
3815    private boolean canViewInstantApps(int callingUid, int userId) {
3816        if (callingUid == Process.SYSTEM_UID
3817                || callingUid == Process.SHELL_UID
3818                || callingUid == Process.ROOT_UID) {
3819            return true;
3820        }
3821        if (mContext.checkCallingOrSelfPermission(
3822                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3823            return true;
3824        }
3825        if (mContext.checkCallingOrSelfPermission(
3826                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3827            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3828            if (homeComponent != null
3829                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3830                return true;
3831            }
3832        }
3833        return false;
3834    }
3835
3836    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3837        if (!sUserManager.exists(userId)) return null;
3838        if (ps == null) {
3839            return null;
3840        }
3841        PackageParser.Package p = ps.pkg;
3842        if (p == null) {
3843            return null;
3844        }
3845        final int callingUid = Binder.getCallingUid();
3846        // Filter out ephemeral app metadata:
3847        //   * The system/shell/root can see metadata for any app
3848        //   * An installed app can see metadata for 1) other installed apps
3849        //     and 2) ephemeral apps that have explicitly interacted with it
3850        //   * Ephemeral apps can only see their own data and exposed installed apps
3851        //   * Holding a signature permission allows seeing instant apps
3852        if (filterAppAccessLPr(ps, callingUid, userId)) {
3853            return null;
3854        }
3855
3856        final PermissionsState permissionsState = ps.getPermissionsState();
3857
3858        // Compute GIDs only if requested
3859        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3860                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3861        // Compute granted permissions only if package has requested permissions
3862        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3863                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3864        final PackageUserState state = ps.readUserState(userId);
3865
3866        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3867                && ps.isSystem()) {
3868            flags |= MATCH_ANY_USER;
3869        }
3870
3871        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3872                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3873
3874        if (packageInfo == null) {
3875            return null;
3876        }
3877
3878        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3879                resolveExternalPackageNameLPr(p);
3880
3881        return packageInfo;
3882    }
3883
3884    @Override
3885    public void checkPackageStartable(String packageName, int userId) {
3886        final int callingUid = Binder.getCallingUid();
3887        if (getInstantAppPackageName(callingUid) != null) {
3888            throw new SecurityException("Instant applications don't have access to this method");
3889        }
3890        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3891        synchronized (mPackages) {
3892            final PackageSetting ps = mSettings.mPackages.get(packageName);
3893            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3894                throw new SecurityException("Package " + packageName + " was not found!");
3895            }
3896
3897            if (!ps.getInstalled(userId)) {
3898                throw new SecurityException(
3899                        "Package " + packageName + " was not installed for user " + userId + "!");
3900            }
3901
3902            if (mSafeMode && !ps.isSystem()) {
3903                throw new SecurityException("Package " + packageName + " not a system app!");
3904            }
3905
3906            if (mFrozenPackages.contains(packageName)) {
3907                throw new SecurityException("Package " + packageName + " is currently frozen!");
3908            }
3909
3910            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3911                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3912            }
3913        }
3914    }
3915
3916    @Override
3917    public boolean isPackageAvailable(String packageName, int userId) {
3918        if (!sUserManager.exists(userId)) return false;
3919        final int callingUid = Binder.getCallingUid();
3920        enforceCrossUserPermission(callingUid, userId,
3921                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3922        synchronized (mPackages) {
3923            PackageParser.Package p = mPackages.get(packageName);
3924            if (p != null) {
3925                final PackageSetting ps = (PackageSetting) p.mExtras;
3926                if (filterAppAccessLPr(ps, callingUid, userId)) {
3927                    return false;
3928                }
3929                if (ps != null) {
3930                    final PackageUserState state = ps.readUserState(userId);
3931                    if (state != null) {
3932                        return PackageParser.isAvailable(state);
3933                    }
3934                }
3935            }
3936        }
3937        return false;
3938    }
3939
3940    @Override
3941    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3942        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3943                flags, Binder.getCallingUid(), userId);
3944    }
3945
3946    @Override
3947    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3948            int flags, int userId) {
3949        return getPackageInfoInternal(versionedPackage.getPackageName(),
3950                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3951    }
3952
3953    /**
3954     * Important: The provided filterCallingUid is used exclusively to filter out packages
3955     * that can be seen based on user state. It's typically the original caller uid prior
3956     * to clearing. Because it can only be provided by trusted code, it's value can be
3957     * trusted and will be used as-is; unlike userId which will be validated by this method.
3958     */
3959    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3960            int flags, int filterCallingUid, int userId) {
3961        if (!sUserManager.exists(userId)) return null;
3962        flags = updateFlagsForPackage(flags, userId, packageName);
3963        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3964                false /* requireFullPermission */, false /* checkShell */, "get package info");
3965
3966        // reader
3967        synchronized (mPackages) {
3968            // Normalize package name to handle renamed packages and static libs
3969            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3970
3971            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3972            if (matchFactoryOnly) {
3973                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3974                if (ps != null) {
3975                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3976                        return null;
3977                    }
3978                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3979                        return null;
3980                    }
3981                    return generatePackageInfo(ps, flags, userId);
3982                }
3983            }
3984
3985            PackageParser.Package p = mPackages.get(packageName);
3986            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3987                return null;
3988            }
3989            if (DEBUG_PACKAGE_INFO)
3990                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3991            if (p != null) {
3992                final PackageSetting ps = (PackageSetting) p.mExtras;
3993                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3994                    return null;
3995                }
3996                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3997                    return null;
3998                }
3999                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4000            }
4001            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4002                final PackageSetting ps = mSettings.mPackages.get(packageName);
4003                if (ps == null) return null;
4004                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4005                    return null;
4006                }
4007                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4008                    return null;
4009                }
4010                return generatePackageInfo(ps, flags, userId);
4011            }
4012        }
4013        return null;
4014    }
4015
4016    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4017        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4018            return true;
4019        }
4020        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4021            return true;
4022        }
4023        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4024            return true;
4025        }
4026        return false;
4027    }
4028
4029    private boolean isComponentVisibleToInstantApp(
4030            @Nullable ComponentName component, @ComponentType int type) {
4031        if (type == TYPE_ACTIVITY) {
4032            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4033            return activity != null
4034                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4035                    : false;
4036        } else if (type == TYPE_RECEIVER) {
4037            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4038            return activity != null
4039                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4040                    : false;
4041        } else if (type == TYPE_SERVICE) {
4042            final PackageParser.Service service = mServices.mServices.get(component);
4043            return service != null
4044                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4045                    : false;
4046        } else if (type == TYPE_PROVIDER) {
4047            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4048            return provider != null
4049                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4050                    : false;
4051        } else if (type == TYPE_UNKNOWN) {
4052            return isComponentVisibleToInstantApp(component);
4053        }
4054        return false;
4055    }
4056
4057    /**
4058     * Returns whether or not access to the application should be filtered.
4059     * <p>
4060     * Access may be limited based upon whether the calling or target applications
4061     * are instant applications.
4062     *
4063     * @see #canAccessInstantApps(int)
4064     */
4065    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4066            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4067        // if we're in an isolated process, get the real calling UID
4068        if (Process.isIsolated(callingUid)) {
4069            callingUid = mIsolatedOwners.get(callingUid);
4070        }
4071        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4072        final boolean callerIsInstantApp = instantAppPkgName != null;
4073        if (ps == null) {
4074            if (callerIsInstantApp) {
4075                // pretend the application exists, but, needs to be filtered
4076                return true;
4077            }
4078            return false;
4079        }
4080        // if the target and caller are the same application, don't filter
4081        if (isCallerSameApp(ps.name, callingUid)) {
4082            return false;
4083        }
4084        if (callerIsInstantApp) {
4085            // request for a specific component; if it hasn't been explicitly exposed, filter
4086            if (component != null) {
4087                return !isComponentVisibleToInstantApp(component, componentType);
4088            }
4089            // request for application; if no components have been explicitly exposed, filter
4090            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4091        }
4092        if (ps.getInstantApp(userId)) {
4093            // caller can see all components of all instant applications, don't filter
4094            if (canViewInstantApps(callingUid, userId)) {
4095                return false;
4096            }
4097            // request for a specific instant application component, filter
4098            if (component != null) {
4099                return true;
4100            }
4101            // request for an instant application; if the caller hasn't been granted access, filter
4102            return !mInstantAppRegistry.isInstantAccessGranted(
4103                    userId, UserHandle.getAppId(callingUid), ps.appId);
4104        }
4105        return false;
4106    }
4107
4108    /**
4109     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4110     */
4111    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4112        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4113    }
4114
4115    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4116            int flags) {
4117        // Callers can access only the libs they depend on, otherwise they need to explicitly
4118        // ask for the shared libraries given the caller is allowed to access all static libs.
4119        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4120            // System/shell/root get to see all static libs
4121            final int appId = UserHandle.getAppId(uid);
4122            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4123                    || appId == Process.ROOT_UID) {
4124                return false;
4125            }
4126        }
4127
4128        // No package means no static lib as it is always on internal storage
4129        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4130            return false;
4131        }
4132
4133        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4134                ps.pkg.staticSharedLibVersion);
4135        if (libEntry == null) {
4136            return false;
4137        }
4138
4139        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4140        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4141        if (uidPackageNames == null) {
4142            return true;
4143        }
4144
4145        for (String uidPackageName : uidPackageNames) {
4146            if (ps.name.equals(uidPackageName)) {
4147                return false;
4148            }
4149            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4150            if (uidPs != null) {
4151                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4152                        libEntry.info.getName());
4153                if (index < 0) {
4154                    continue;
4155                }
4156                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4157                    return false;
4158                }
4159            }
4160        }
4161        return true;
4162    }
4163
4164    @Override
4165    public String[] currentToCanonicalPackageNames(String[] names) {
4166        final int callingUid = Binder.getCallingUid();
4167        if (getInstantAppPackageName(callingUid) != null) {
4168            return names;
4169        }
4170        final String[] out = new String[names.length];
4171        // reader
4172        synchronized (mPackages) {
4173            final int callingUserId = UserHandle.getUserId(callingUid);
4174            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4175            for (int i=names.length-1; i>=0; i--) {
4176                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4177                boolean translateName = false;
4178                if (ps != null && ps.realName != null) {
4179                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4180                    translateName = !targetIsInstantApp
4181                            || canViewInstantApps
4182                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4183                                    UserHandle.getAppId(callingUid), ps.appId);
4184                }
4185                out[i] = translateName ? ps.realName : names[i];
4186            }
4187        }
4188        return out;
4189    }
4190
4191    @Override
4192    public String[] canonicalToCurrentPackageNames(String[] names) {
4193        final int callingUid = Binder.getCallingUid();
4194        if (getInstantAppPackageName(callingUid) != null) {
4195            return names;
4196        }
4197        final String[] out = new String[names.length];
4198        // reader
4199        synchronized (mPackages) {
4200            final int callingUserId = UserHandle.getUserId(callingUid);
4201            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4202            for (int i=names.length-1; i>=0; i--) {
4203                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4204                boolean translateName = false;
4205                if (cur != null) {
4206                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4207                    final boolean targetIsInstantApp =
4208                            ps != null && ps.getInstantApp(callingUserId);
4209                    translateName = !targetIsInstantApp
4210                            || canViewInstantApps
4211                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4212                                    UserHandle.getAppId(callingUid), ps.appId);
4213                }
4214                out[i] = translateName ? cur : names[i];
4215            }
4216        }
4217        return out;
4218    }
4219
4220    @Override
4221    public int getPackageUid(String packageName, int flags, int userId) {
4222        if (!sUserManager.exists(userId)) return -1;
4223        final int callingUid = Binder.getCallingUid();
4224        flags = updateFlagsForPackage(flags, userId, packageName);
4225        enforceCrossUserPermission(callingUid, userId,
4226                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4227
4228        // reader
4229        synchronized (mPackages) {
4230            final PackageParser.Package p = mPackages.get(packageName);
4231            if (p != null && p.isMatch(flags)) {
4232                PackageSetting ps = (PackageSetting) p.mExtras;
4233                if (filterAppAccessLPr(ps, callingUid, userId)) {
4234                    return -1;
4235                }
4236                return UserHandle.getUid(userId, p.applicationInfo.uid);
4237            }
4238            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4239                final PackageSetting ps = mSettings.mPackages.get(packageName);
4240                if (ps != null && ps.isMatch(flags)
4241                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4242                    return UserHandle.getUid(userId, ps.appId);
4243                }
4244            }
4245        }
4246
4247        return -1;
4248    }
4249
4250    @Override
4251    public int[] getPackageGids(String packageName, int flags, int userId) {
4252        if (!sUserManager.exists(userId)) return null;
4253        final int callingUid = Binder.getCallingUid();
4254        flags = updateFlagsForPackage(flags, userId, packageName);
4255        enforceCrossUserPermission(callingUid, userId,
4256                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4257
4258        // reader
4259        synchronized (mPackages) {
4260            final PackageParser.Package p = mPackages.get(packageName);
4261            if (p != null && p.isMatch(flags)) {
4262                PackageSetting ps = (PackageSetting) p.mExtras;
4263                if (filterAppAccessLPr(ps, callingUid, userId)) {
4264                    return null;
4265                }
4266                // TODO: Shouldn't this be checking for package installed state for userId and
4267                // return null?
4268                return ps.getPermissionsState().computeGids(userId);
4269            }
4270            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4271                final PackageSetting ps = mSettings.mPackages.get(packageName);
4272                if (ps != null && ps.isMatch(flags)
4273                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4274                    return ps.getPermissionsState().computeGids(userId);
4275                }
4276            }
4277        }
4278
4279        return null;
4280    }
4281
4282    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4283        if (bp.perm != null) {
4284            return PackageParser.generatePermissionInfo(bp.perm, flags);
4285        }
4286        PermissionInfo pi = new PermissionInfo();
4287        pi.name = bp.name;
4288        pi.packageName = bp.sourcePackage;
4289        pi.nonLocalizedLabel = bp.name;
4290        pi.protectionLevel = bp.protectionLevel;
4291        return pi;
4292    }
4293
4294    @Override
4295    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4296        final int callingUid = Binder.getCallingUid();
4297        if (getInstantAppPackageName(callingUid) != null) {
4298            return null;
4299        }
4300        // reader
4301        synchronized (mPackages) {
4302            final BasePermission p = mSettings.mPermissions.get(name);
4303            if (p == null) {
4304                return null;
4305            }
4306            // If the caller is an app that targets pre 26 SDK drop protection flags.
4307            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4308            if (permissionInfo != null) {
4309                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4310                        permissionInfo.protectionLevel, packageName, callingUid);
4311                if (permissionInfo.protectionLevel != protectionLevel) {
4312                    // If we return different protection level, don't use the cached info
4313                    if (p.perm != null && p.perm.info == permissionInfo) {
4314                        permissionInfo = new PermissionInfo(permissionInfo);
4315                    }
4316                    permissionInfo.protectionLevel = protectionLevel;
4317                }
4318            }
4319            return permissionInfo;
4320        }
4321    }
4322
4323    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4324            String packageName, int uid) {
4325        // Signature permission flags area always reported
4326        final int protectionLevelMasked = protectionLevel
4327                & (PermissionInfo.PROTECTION_NORMAL
4328                | PermissionInfo.PROTECTION_DANGEROUS
4329                | PermissionInfo.PROTECTION_SIGNATURE);
4330        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4331            return protectionLevel;
4332        }
4333
4334        // System sees all flags.
4335        final int appId = UserHandle.getAppId(uid);
4336        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4337                || appId == Process.SHELL_UID) {
4338            return protectionLevel;
4339        }
4340
4341        // Normalize package name to handle renamed packages and static libs
4342        packageName = resolveInternalPackageNameLPr(packageName,
4343                PackageManager.VERSION_CODE_HIGHEST);
4344
4345        // Apps that target O see flags for all protection levels.
4346        final PackageSetting ps = mSettings.mPackages.get(packageName);
4347        if (ps == null) {
4348            return protectionLevel;
4349        }
4350        if (ps.appId != appId) {
4351            return protectionLevel;
4352        }
4353
4354        final PackageParser.Package pkg = mPackages.get(packageName);
4355        if (pkg == null) {
4356            return protectionLevel;
4357        }
4358        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4359            return protectionLevelMasked;
4360        }
4361
4362        return protectionLevel;
4363    }
4364
4365    @Override
4366    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4367            int flags) {
4368        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4369            return null;
4370        }
4371        // reader
4372        synchronized (mPackages) {
4373            if (group != null && !mPermissionGroups.containsKey(group)) {
4374                // This is thrown as NameNotFoundException
4375                return null;
4376            }
4377
4378            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4379            for (BasePermission p : mSettings.mPermissions.values()) {
4380                if (group == null) {
4381                    if (p.perm == null || p.perm.info.group == null) {
4382                        out.add(generatePermissionInfo(p, flags));
4383                    }
4384                } else {
4385                    if (p.perm != null && group.equals(p.perm.info.group)) {
4386                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4387                    }
4388                }
4389            }
4390            return new ParceledListSlice<>(out);
4391        }
4392    }
4393
4394    @Override
4395    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4396        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4397            return null;
4398        }
4399        // reader
4400        synchronized (mPackages) {
4401            return PackageParser.generatePermissionGroupInfo(
4402                    mPermissionGroups.get(name), flags);
4403        }
4404    }
4405
4406    @Override
4407    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4408        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4409            return ParceledListSlice.emptyList();
4410        }
4411        // reader
4412        synchronized (mPackages) {
4413            final int N = mPermissionGroups.size();
4414            ArrayList<PermissionGroupInfo> out
4415                    = new ArrayList<PermissionGroupInfo>(N);
4416            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4417                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4418            }
4419            return new ParceledListSlice<>(out);
4420        }
4421    }
4422
4423    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4424            int filterCallingUid, int userId) {
4425        if (!sUserManager.exists(userId)) return null;
4426        PackageSetting ps = mSettings.mPackages.get(packageName);
4427        if (ps != null) {
4428            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4429                return null;
4430            }
4431            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4432                return null;
4433            }
4434            if (ps.pkg == null) {
4435                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4436                if (pInfo != null) {
4437                    return pInfo.applicationInfo;
4438                }
4439                return null;
4440            }
4441            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4442                    ps.readUserState(userId), userId);
4443            if (ai != null) {
4444                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4445            }
4446            return ai;
4447        }
4448        return null;
4449    }
4450
4451    @Override
4452    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4453        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4454    }
4455
4456    /**
4457     * Important: The provided filterCallingUid is used exclusively to filter out applications
4458     * that can be seen based on user state. It's typically the original caller uid prior
4459     * to clearing. Because it can only be provided by trusted code, it's value can be
4460     * trusted and will be used as-is; unlike userId which will be validated by this method.
4461     */
4462    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4463            int filterCallingUid, int userId) {
4464        if (!sUserManager.exists(userId)) return null;
4465        flags = updateFlagsForApplication(flags, userId, packageName);
4466        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4467                false /* requireFullPermission */, false /* checkShell */, "get application info");
4468
4469        // writer
4470        synchronized (mPackages) {
4471            // Normalize package name to handle renamed packages and static libs
4472            packageName = resolveInternalPackageNameLPr(packageName,
4473                    PackageManager.VERSION_CODE_HIGHEST);
4474
4475            PackageParser.Package p = mPackages.get(packageName);
4476            if (DEBUG_PACKAGE_INFO) Log.v(
4477                    TAG, "getApplicationInfo " + packageName
4478                    + ": " + p);
4479            if (p != null) {
4480                PackageSetting ps = mSettings.mPackages.get(packageName);
4481                if (ps == null) return null;
4482                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4483                    return null;
4484                }
4485                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4486                    return null;
4487                }
4488                // Note: isEnabledLP() does not apply here - always return info
4489                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4490                        p, flags, ps.readUserState(userId), userId);
4491                if (ai != null) {
4492                    ai.packageName = resolveExternalPackageNameLPr(p);
4493                }
4494                return ai;
4495            }
4496            if ("android".equals(packageName)||"system".equals(packageName)) {
4497                return mAndroidApplication;
4498            }
4499            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4500                // Already generates the external package name
4501                return generateApplicationInfoFromSettingsLPw(packageName,
4502                        flags, filterCallingUid, userId);
4503            }
4504        }
4505        return null;
4506    }
4507
4508    private String normalizePackageNameLPr(String packageName) {
4509        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4510        return normalizedPackageName != null ? normalizedPackageName : packageName;
4511    }
4512
4513    @Override
4514    public void deletePreloadsFileCache() {
4515        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4516            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4517        }
4518        File dir = Environment.getDataPreloadsFileCacheDirectory();
4519        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4520        FileUtils.deleteContents(dir);
4521    }
4522
4523    @Override
4524    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4525            final int storageFlags, final IPackageDataObserver observer) {
4526        mContext.enforceCallingOrSelfPermission(
4527                android.Manifest.permission.CLEAR_APP_CACHE, null);
4528        mHandler.post(() -> {
4529            boolean success = false;
4530            try {
4531                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4532                success = true;
4533            } catch (IOException e) {
4534                Slog.w(TAG, e);
4535            }
4536            if (observer != null) {
4537                try {
4538                    observer.onRemoveCompleted(null, success);
4539                } catch (RemoteException e) {
4540                    Slog.w(TAG, e);
4541                }
4542            }
4543        });
4544    }
4545
4546    @Override
4547    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4548            final int storageFlags, final IntentSender pi) {
4549        mContext.enforceCallingOrSelfPermission(
4550                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4551        mHandler.post(() -> {
4552            boolean success = false;
4553            try {
4554                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4555                success = true;
4556            } catch (IOException e) {
4557                Slog.w(TAG, e);
4558            }
4559            if (pi != null) {
4560                try {
4561                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4562                } catch (SendIntentException e) {
4563                    Slog.w(TAG, e);
4564                }
4565            }
4566        });
4567    }
4568
4569    /**
4570     * Blocking call to clear various types of cached data across the system
4571     * until the requested bytes are available.
4572     */
4573    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4574        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4575        final File file = storage.findPathForUuid(volumeUuid);
4576        if (file.getUsableSpace() >= bytes) return;
4577
4578        if (ENABLE_FREE_CACHE_V2) {
4579            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4580                    volumeUuid);
4581            final boolean aggressive = (storageFlags
4582                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4583            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4584
4585            // 1. Pre-flight to determine if we have any chance to succeed
4586            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4587            if (internalVolume && (aggressive || SystemProperties
4588                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4589                deletePreloadsFileCache();
4590                if (file.getUsableSpace() >= bytes) return;
4591            }
4592
4593            // 3. Consider parsed APK data (aggressive only)
4594            if (internalVolume && aggressive) {
4595                FileUtils.deleteContents(mCacheDir);
4596                if (file.getUsableSpace() >= bytes) return;
4597            }
4598
4599            // 4. Consider cached app data (above quotas)
4600            try {
4601                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4602                        Installer.FLAG_FREE_CACHE_V2);
4603            } catch (InstallerException ignored) {
4604            }
4605            if (file.getUsableSpace() >= bytes) return;
4606
4607            // 5. Consider shared libraries with refcount=0 and age>min cache period
4608            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4609                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4610                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4611                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4612                return;
4613            }
4614
4615            // 6. Consider dexopt output (aggressive only)
4616            // TODO: Implement
4617
4618            // 7. Consider installed instant apps unused longer than min cache period
4619            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4620                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4621                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4622                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4623                return;
4624            }
4625
4626            // 8. Consider cached app data (below quotas)
4627            try {
4628                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4629                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4630            } catch (InstallerException ignored) {
4631            }
4632            if (file.getUsableSpace() >= bytes) return;
4633
4634            // 9. Consider DropBox entries
4635            // TODO: Implement
4636
4637            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4638            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4639                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4640                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4641                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4642                return;
4643            }
4644        } else {
4645            try {
4646                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4647            } catch (InstallerException ignored) {
4648            }
4649            if (file.getUsableSpace() >= bytes) return;
4650        }
4651
4652        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4653    }
4654
4655    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4656            throws IOException {
4657        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4658        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4659
4660        List<VersionedPackage> packagesToDelete = null;
4661        final long now = System.currentTimeMillis();
4662
4663        synchronized (mPackages) {
4664            final int[] allUsers = sUserManager.getUserIds();
4665            final int libCount = mSharedLibraries.size();
4666            for (int i = 0; i < libCount; i++) {
4667                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4668                if (versionedLib == null) {
4669                    continue;
4670                }
4671                final int versionCount = versionedLib.size();
4672                for (int j = 0; j < versionCount; j++) {
4673                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4674                    // Skip packages that are not static shared libs.
4675                    if (!libInfo.isStatic()) {
4676                        break;
4677                    }
4678                    // Important: We skip static shared libs used for some user since
4679                    // in such a case we need to keep the APK on the device. The check for
4680                    // a lib being used for any user is performed by the uninstall call.
4681                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4682                    // Resolve the package name - we use synthetic package names internally
4683                    final String internalPackageName = resolveInternalPackageNameLPr(
4684                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4685                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4686                    // Skip unused static shared libs cached less than the min period
4687                    // to prevent pruning a lib needed by a subsequently installed package.
4688                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4689                        continue;
4690                    }
4691                    if (packagesToDelete == null) {
4692                        packagesToDelete = new ArrayList<>();
4693                    }
4694                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4695                            declaringPackage.getVersionCode()));
4696                }
4697            }
4698        }
4699
4700        if (packagesToDelete != null) {
4701            final int packageCount = packagesToDelete.size();
4702            for (int i = 0; i < packageCount; i++) {
4703                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4704                // Delete the package synchronously (will fail of the lib used for any user).
4705                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4706                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4707                                == PackageManager.DELETE_SUCCEEDED) {
4708                    if (volume.getUsableSpace() >= neededSpace) {
4709                        return true;
4710                    }
4711                }
4712            }
4713        }
4714
4715        return false;
4716    }
4717
4718    /**
4719     * Update given flags based on encryption status of current user.
4720     */
4721    private int updateFlags(int flags, int userId) {
4722        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4723                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4724            // Caller expressed an explicit opinion about what encryption
4725            // aware/unaware components they want to see, so fall through and
4726            // give them what they want
4727        } else {
4728            // Caller expressed no opinion, so match based on user state
4729            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4730                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4731            } else {
4732                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4733            }
4734        }
4735        return flags;
4736    }
4737
4738    private UserManagerInternal getUserManagerInternal() {
4739        if (mUserManagerInternal == null) {
4740            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4741        }
4742        return mUserManagerInternal;
4743    }
4744
4745    private DeviceIdleController.LocalService getDeviceIdleController() {
4746        if (mDeviceIdleController == null) {
4747            mDeviceIdleController =
4748                    LocalServices.getService(DeviceIdleController.LocalService.class);
4749        }
4750        return mDeviceIdleController;
4751    }
4752
4753    /**
4754     * Update given flags when being used to request {@link PackageInfo}.
4755     */
4756    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4757        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4758        boolean triaged = true;
4759        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4760                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4761            // Caller is asking for component details, so they'd better be
4762            // asking for specific encryption matching behavior, or be triaged
4763            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4764                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4765                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4766                triaged = false;
4767            }
4768        }
4769        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4770                | PackageManager.MATCH_SYSTEM_ONLY
4771                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4772            triaged = false;
4773        }
4774        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4775            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4776                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4777                    + Debug.getCallers(5));
4778        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4779                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4780            // If the caller wants all packages and has a restricted profile associated with it,
4781            // then match all users. This is to make sure that launchers that need to access work
4782            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4783            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4784            flags |= PackageManager.MATCH_ANY_USER;
4785        }
4786        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4787            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4788                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4789        }
4790        return updateFlags(flags, userId);
4791    }
4792
4793    /**
4794     * Update given flags when being used to request {@link ApplicationInfo}.
4795     */
4796    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4797        return updateFlagsForPackage(flags, userId, cookie);
4798    }
4799
4800    /**
4801     * Update given flags when being used to request {@link ComponentInfo}.
4802     */
4803    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4804        if (cookie instanceof Intent) {
4805            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4806                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4807            }
4808        }
4809
4810        boolean triaged = true;
4811        // Caller is asking for component details, so they'd better be
4812        // asking for specific encryption matching behavior, or be triaged
4813        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4814                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4815                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4816            triaged = false;
4817        }
4818        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4819            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4820                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4821        }
4822
4823        return updateFlags(flags, userId);
4824    }
4825
4826    /**
4827     * Update given intent when being used to request {@link ResolveInfo}.
4828     */
4829    private Intent updateIntentForResolve(Intent intent) {
4830        if (intent.getSelector() != null) {
4831            intent = intent.getSelector();
4832        }
4833        if (DEBUG_PREFERRED) {
4834            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4835        }
4836        return intent;
4837    }
4838
4839    /**
4840     * Update given flags when being used to request {@link ResolveInfo}.
4841     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4842     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4843     * flag set. However, this flag is only honoured in three circumstances:
4844     * <ul>
4845     * <li>when called from a system process</li>
4846     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4847     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4848     * action and a {@code android.intent.category.BROWSABLE} category</li>
4849     * </ul>
4850     */
4851    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4852        return updateFlagsForResolve(flags, userId, intent, callingUid,
4853                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4854    }
4855    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4856            boolean wantInstantApps) {
4857        return updateFlagsForResolve(flags, userId, intent, callingUid,
4858                wantInstantApps, false /*onlyExposedExplicitly*/);
4859    }
4860    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4861            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4862        // Safe mode means we shouldn't match any third-party components
4863        if (mSafeMode) {
4864            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4865        }
4866        if (getInstantAppPackageName(callingUid) != null) {
4867            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4868            if (onlyExposedExplicitly) {
4869                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4870            }
4871            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4872            flags |= PackageManager.MATCH_INSTANT;
4873        } else {
4874            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4875            final boolean allowMatchInstant =
4876                    (wantInstantApps
4877                            && Intent.ACTION_VIEW.equals(intent.getAction())
4878                            && hasWebURI(intent))
4879                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4880            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4881                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4882            if (!allowMatchInstant) {
4883                flags &= ~PackageManager.MATCH_INSTANT;
4884            }
4885        }
4886        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4887    }
4888
4889    @Override
4890    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4891        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4892    }
4893
4894    /**
4895     * Important: The provided filterCallingUid is used exclusively to filter out activities
4896     * that can be seen based on user state. It's typically the original caller uid prior
4897     * to clearing. Because it can only be provided by trusted code, it's value can be
4898     * trusted and will be used as-is; unlike userId which will be validated by this method.
4899     */
4900    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4901            int filterCallingUid, int userId) {
4902        if (!sUserManager.exists(userId)) return null;
4903        flags = updateFlagsForComponent(flags, userId, component);
4904        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4905                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4906        synchronized (mPackages) {
4907            PackageParser.Activity a = mActivities.mActivities.get(component);
4908
4909            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4910            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4911                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4912                if (ps == null) return null;
4913                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4914                    return null;
4915                }
4916                return PackageParser.generateActivityInfo(
4917                        a, flags, ps.readUserState(userId), userId);
4918            }
4919            if (mResolveComponentName.equals(component)) {
4920                return PackageParser.generateActivityInfo(
4921                        mResolveActivity, flags, new PackageUserState(), userId);
4922            }
4923        }
4924        return null;
4925    }
4926
4927    @Override
4928    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4929            String resolvedType) {
4930        synchronized (mPackages) {
4931            if (component.equals(mResolveComponentName)) {
4932                // The resolver supports EVERYTHING!
4933                return true;
4934            }
4935            final int callingUid = Binder.getCallingUid();
4936            final int callingUserId = UserHandle.getUserId(callingUid);
4937            PackageParser.Activity a = mActivities.mActivities.get(component);
4938            if (a == null) {
4939                return false;
4940            }
4941            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4942            if (ps == null) {
4943                return false;
4944            }
4945            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4946                return false;
4947            }
4948            for (int i=0; i<a.intents.size(); i++) {
4949                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4950                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4951                    return true;
4952                }
4953            }
4954            return false;
4955        }
4956    }
4957
4958    @Override
4959    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4960        if (!sUserManager.exists(userId)) return null;
4961        final int callingUid = Binder.getCallingUid();
4962        flags = updateFlagsForComponent(flags, userId, component);
4963        enforceCrossUserPermission(callingUid, userId,
4964                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4965        synchronized (mPackages) {
4966            PackageParser.Activity a = mReceivers.mActivities.get(component);
4967            if (DEBUG_PACKAGE_INFO) Log.v(
4968                TAG, "getReceiverInfo " + component + ": " + a);
4969            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4970                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4971                if (ps == null) return null;
4972                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4973                    return null;
4974                }
4975                return PackageParser.generateActivityInfo(
4976                        a, flags, ps.readUserState(userId), userId);
4977            }
4978        }
4979        return null;
4980    }
4981
4982    @Override
4983    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4984            int flags, int userId) {
4985        if (!sUserManager.exists(userId)) return null;
4986        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4987        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4988            return null;
4989        }
4990
4991        flags = updateFlagsForPackage(flags, userId, null);
4992
4993        final boolean canSeeStaticLibraries =
4994                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4995                        == PERMISSION_GRANTED
4996                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4997                        == PERMISSION_GRANTED
4998                || canRequestPackageInstallsInternal(packageName,
4999                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5000                        false  /* throwIfPermNotDeclared*/)
5001                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5002                        == PERMISSION_GRANTED;
5003
5004        synchronized (mPackages) {
5005            List<SharedLibraryInfo> result = null;
5006
5007            final int libCount = mSharedLibraries.size();
5008            for (int i = 0; i < libCount; i++) {
5009                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5010                if (versionedLib == null) {
5011                    continue;
5012                }
5013
5014                final int versionCount = versionedLib.size();
5015                for (int j = 0; j < versionCount; j++) {
5016                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5017                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5018                        break;
5019                    }
5020                    final long identity = Binder.clearCallingIdentity();
5021                    try {
5022                        PackageInfo packageInfo = getPackageInfoVersioned(
5023                                libInfo.getDeclaringPackage(), flags
5024                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5025                        if (packageInfo == null) {
5026                            continue;
5027                        }
5028                    } finally {
5029                        Binder.restoreCallingIdentity(identity);
5030                    }
5031
5032                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5033                            libInfo.getVersion(), libInfo.getType(),
5034                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5035                            flags, userId));
5036
5037                    if (result == null) {
5038                        result = new ArrayList<>();
5039                    }
5040                    result.add(resLibInfo);
5041                }
5042            }
5043
5044            return result != null ? new ParceledListSlice<>(result) : null;
5045        }
5046    }
5047
5048    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5049            SharedLibraryInfo libInfo, int flags, int userId) {
5050        List<VersionedPackage> versionedPackages = null;
5051        final int packageCount = mSettings.mPackages.size();
5052        for (int i = 0; i < packageCount; i++) {
5053            PackageSetting ps = mSettings.mPackages.valueAt(i);
5054
5055            if (ps == null) {
5056                continue;
5057            }
5058
5059            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5060                continue;
5061            }
5062
5063            final String libName = libInfo.getName();
5064            if (libInfo.isStatic()) {
5065                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5066                if (libIdx < 0) {
5067                    continue;
5068                }
5069                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5070                    continue;
5071                }
5072                if (versionedPackages == null) {
5073                    versionedPackages = new ArrayList<>();
5074                }
5075                // If the dependent is a static shared lib, use the public package name
5076                String dependentPackageName = ps.name;
5077                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5078                    dependentPackageName = ps.pkg.manifestPackageName;
5079                }
5080                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5081            } else if (ps.pkg != null) {
5082                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5083                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5084                    if (versionedPackages == null) {
5085                        versionedPackages = new ArrayList<>();
5086                    }
5087                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5088                }
5089            }
5090        }
5091
5092        return versionedPackages;
5093    }
5094
5095    @Override
5096    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5097        if (!sUserManager.exists(userId)) return null;
5098        final int callingUid = Binder.getCallingUid();
5099        flags = updateFlagsForComponent(flags, userId, component);
5100        enforceCrossUserPermission(callingUid, userId,
5101                false /* requireFullPermission */, false /* checkShell */, "get service info");
5102        synchronized (mPackages) {
5103            PackageParser.Service s = mServices.mServices.get(component);
5104            if (DEBUG_PACKAGE_INFO) Log.v(
5105                TAG, "getServiceInfo " + component + ": " + s);
5106            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5107                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5108                if (ps == null) return null;
5109                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5110                    return null;
5111                }
5112                return PackageParser.generateServiceInfo(
5113                        s, flags, ps.readUserState(userId), userId);
5114            }
5115        }
5116        return null;
5117    }
5118
5119    @Override
5120    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5121        if (!sUserManager.exists(userId)) return null;
5122        final int callingUid = Binder.getCallingUid();
5123        flags = updateFlagsForComponent(flags, userId, component);
5124        enforceCrossUserPermission(callingUid, userId,
5125                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5126        synchronized (mPackages) {
5127            PackageParser.Provider p = mProviders.mProviders.get(component);
5128            if (DEBUG_PACKAGE_INFO) Log.v(
5129                TAG, "getProviderInfo " + component + ": " + p);
5130            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5131                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5132                if (ps == null) return null;
5133                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5134                    return null;
5135                }
5136                return PackageParser.generateProviderInfo(
5137                        p, flags, ps.readUserState(userId), userId);
5138            }
5139        }
5140        return null;
5141    }
5142
5143    @Override
5144    public String[] getSystemSharedLibraryNames() {
5145        // allow instant applications
5146        synchronized (mPackages) {
5147            Set<String> libs = null;
5148            final int libCount = mSharedLibraries.size();
5149            for (int i = 0; i < libCount; i++) {
5150                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5151                if (versionedLib == null) {
5152                    continue;
5153                }
5154                final int versionCount = versionedLib.size();
5155                for (int j = 0; j < versionCount; j++) {
5156                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5157                    if (!libEntry.info.isStatic()) {
5158                        if (libs == null) {
5159                            libs = new ArraySet<>();
5160                        }
5161                        libs.add(libEntry.info.getName());
5162                        break;
5163                    }
5164                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5165                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5166                            UserHandle.getUserId(Binder.getCallingUid()),
5167                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5168                        if (libs == null) {
5169                            libs = new ArraySet<>();
5170                        }
5171                        libs.add(libEntry.info.getName());
5172                        break;
5173                    }
5174                }
5175            }
5176
5177            if (libs != null) {
5178                String[] libsArray = new String[libs.size()];
5179                libs.toArray(libsArray);
5180                return libsArray;
5181            }
5182
5183            return null;
5184        }
5185    }
5186
5187    @Override
5188    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5189        // allow instant applications
5190        synchronized (mPackages) {
5191            return mServicesSystemSharedLibraryPackageName;
5192        }
5193    }
5194
5195    @Override
5196    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5197        // allow instant applications
5198        synchronized (mPackages) {
5199            return mSharedSystemSharedLibraryPackageName;
5200        }
5201    }
5202
5203    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5204        for (int i = userList.length - 1; i >= 0; --i) {
5205            final int userId = userList[i];
5206            // don't add instant app to the list of updates
5207            if (pkgSetting.getInstantApp(userId)) {
5208                continue;
5209            }
5210            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5211            if (changedPackages == null) {
5212                changedPackages = new SparseArray<>();
5213                mChangedPackages.put(userId, changedPackages);
5214            }
5215            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5216            if (sequenceNumbers == null) {
5217                sequenceNumbers = new HashMap<>();
5218                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5219            }
5220            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5221            if (sequenceNumber != null) {
5222                changedPackages.remove(sequenceNumber);
5223            }
5224            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5225            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5226        }
5227        mChangedPackagesSequenceNumber++;
5228    }
5229
5230    @Override
5231    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5232        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5233            return null;
5234        }
5235        synchronized (mPackages) {
5236            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5237                return null;
5238            }
5239            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5240            if (changedPackages == null) {
5241                return null;
5242            }
5243            final List<String> packageNames =
5244                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5245            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5246                final String packageName = changedPackages.get(i);
5247                if (packageName != null) {
5248                    packageNames.add(packageName);
5249                }
5250            }
5251            return packageNames.isEmpty()
5252                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5253        }
5254    }
5255
5256    @Override
5257    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5258        // allow instant applications
5259        ArrayList<FeatureInfo> res;
5260        synchronized (mAvailableFeatures) {
5261            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5262            res.addAll(mAvailableFeatures.values());
5263        }
5264        final FeatureInfo fi = new FeatureInfo();
5265        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5266                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5267        res.add(fi);
5268
5269        return new ParceledListSlice<>(res);
5270    }
5271
5272    @Override
5273    public boolean hasSystemFeature(String name, int version) {
5274        // allow instant applications
5275        synchronized (mAvailableFeatures) {
5276            final FeatureInfo feat = mAvailableFeatures.get(name);
5277            if (feat == null) {
5278                return false;
5279            } else {
5280                return feat.version >= version;
5281            }
5282        }
5283    }
5284
5285    @Override
5286    public int checkPermission(String permName, String pkgName, int userId) {
5287        if (!sUserManager.exists(userId)) {
5288            return PackageManager.PERMISSION_DENIED;
5289        }
5290        final int callingUid = Binder.getCallingUid();
5291
5292        synchronized (mPackages) {
5293            final PackageParser.Package p = mPackages.get(pkgName);
5294            if (p != null && p.mExtras != null) {
5295                final PackageSetting ps = (PackageSetting) p.mExtras;
5296                if (filterAppAccessLPr(ps, callingUid, userId)) {
5297                    return PackageManager.PERMISSION_DENIED;
5298                }
5299                final boolean instantApp = ps.getInstantApp(userId);
5300                final PermissionsState permissionsState = ps.getPermissionsState();
5301                if (permissionsState.hasPermission(permName, userId)) {
5302                    if (instantApp) {
5303                        BasePermission bp = mSettings.mPermissions.get(permName);
5304                        if (bp != null && bp.isInstant()) {
5305                            return PackageManager.PERMISSION_GRANTED;
5306                        }
5307                    } else {
5308                        return PackageManager.PERMISSION_GRANTED;
5309                    }
5310                }
5311                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5312                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5313                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5314                    return PackageManager.PERMISSION_GRANTED;
5315                }
5316            }
5317        }
5318
5319        return PackageManager.PERMISSION_DENIED;
5320    }
5321
5322    @Override
5323    public int checkUidPermission(String permName, int uid) {
5324        final int callingUid = Binder.getCallingUid();
5325        final int callingUserId = UserHandle.getUserId(callingUid);
5326        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5327        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5328        final int userId = UserHandle.getUserId(uid);
5329        if (!sUserManager.exists(userId)) {
5330            return PackageManager.PERMISSION_DENIED;
5331        }
5332
5333        synchronized (mPackages) {
5334            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5335            if (obj != null) {
5336                if (obj instanceof SharedUserSetting) {
5337                    if (isCallerInstantApp) {
5338                        return PackageManager.PERMISSION_DENIED;
5339                    }
5340                } else if (obj instanceof PackageSetting) {
5341                    final PackageSetting ps = (PackageSetting) obj;
5342                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5343                        return PackageManager.PERMISSION_DENIED;
5344                    }
5345                }
5346                final SettingBase settingBase = (SettingBase) obj;
5347                final PermissionsState permissionsState = settingBase.getPermissionsState();
5348                if (permissionsState.hasPermission(permName, userId)) {
5349                    if (isUidInstantApp) {
5350                        BasePermission bp = mSettings.mPermissions.get(permName);
5351                        if (bp != null && bp.isInstant()) {
5352                            return PackageManager.PERMISSION_GRANTED;
5353                        }
5354                    } else {
5355                        return PackageManager.PERMISSION_GRANTED;
5356                    }
5357                }
5358                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5359                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5360                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5361                    return PackageManager.PERMISSION_GRANTED;
5362                }
5363            } else {
5364                ArraySet<String> perms = mSystemPermissions.get(uid);
5365                if (perms != null) {
5366                    if (perms.contains(permName)) {
5367                        return PackageManager.PERMISSION_GRANTED;
5368                    }
5369                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5370                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5371                        return PackageManager.PERMISSION_GRANTED;
5372                    }
5373                }
5374            }
5375        }
5376
5377        return PackageManager.PERMISSION_DENIED;
5378    }
5379
5380    @Override
5381    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5382        if (UserHandle.getCallingUserId() != userId) {
5383            mContext.enforceCallingPermission(
5384                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5385                    "isPermissionRevokedByPolicy for user " + userId);
5386        }
5387
5388        if (checkPermission(permission, packageName, userId)
5389                == PackageManager.PERMISSION_GRANTED) {
5390            return false;
5391        }
5392
5393        final int callingUid = Binder.getCallingUid();
5394        if (getInstantAppPackageName(callingUid) != null) {
5395            if (!isCallerSameApp(packageName, callingUid)) {
5396                return false;
5397            }
5398        } else {
5399            if (isInstantApp(packageName, userId)) {
5400                return false;
5401            }
5402        }
5403
5404        final long identity = Binder.clearCallingIdentity();
5405        try {
5406            final int flags = getPermissionFlags(permission, packageName, userId);
5407            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5408        } finally {
5409            Binder.restoreCallingIdentity(identity);
5410        }
5411    }
5412
5413    @Override
5414    public String getPermissionControllerPackageName() {
5415        synchronized (mPackages) {
5416            return mRequiredInstallerPackage;
5417        }
5418    }
5419
5420    /**
5421     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5422     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5423     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5424     * @param message the message to log on security exception
5425     */
5426    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5427            boolean checkShell, String message) {
5428        if (userId < 0) {
5429            throw new IllegalArgumentException("Invalid userId " + userId);
5430        }
5431        if (checkShell) {
5432            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5433        }
5434        if (userId == UserHandle.getUserId(callingUid)) return;
5435        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5436            if (requireFullPermission) {
5437                mContext.enforceCallingOrSelfPermission(
5438                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5439            } else {
5440                try {
5441                    mContext.enforceCallingOrSelfPermission(
5442                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5443                } catch (SecurityException se) {
5444                    mContext.enforceCallingOrSelfPermission(
5445                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5446                }
5447            }
5448        }
5449    }
5450
5451    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5452        if (callingUid == Process.SHELL_UID) {
5453            if (userHandle >= 0
5454                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5455                throw new SecurityException("Shell does not have permission to access user "
5456                        + userHandle);
5457            } else if (userHandle < 0) {
5458                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5459                        + Debug.getCallers(3));
5460            }
5461        }
5462    }
5463
5464    private BasePermission findPermissionTreeLP(String permName) {
5465        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5466            if (permName.startsWith(bp.name) &&
5467                    permName.length() > bp.name.length() &&
5468                    permName.charAt(bp.name.length()) == '.') {
5469                return bp;
5470            }
5471        }
5472        return null;
5473    }
5474
5475    private BasePermission checkPermissionTreeLP(String permName) {
5476        if (permName != null) {
5477            BasePermission bp = findPermissionTreeLP(permName);
5478            if (bp != null) {
5479                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5480                    return bp;
5481                }
5482                throw new SecurityException("Calling uid "
5483                        + Binder.getCallingUid()
5484                        + " is not allowed to add to permission tree "
5485                        + bp.name + " owned by uid " + bp.uid);
5486            }
5487        }
5488        throw new SecurityException("No permission tree found for " + permName);
5489    }
5490
5491    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5492        if (s1 == null) {
5493            return s2 == null;
5494        }
5495        if (s2 == null) {
5496            return false;
5497        }
5498        if (s1.getClass() != s2.getClass()) {
5499            return false;
5500        }
5501        return s1.equals(s2);
5502    }
5503
5504    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5505        if (pi1.icon != pi2.icon) return false;
5506        if (pi1.logo != pi2.logo) return false;
5507        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5508        if (!compareStrings(pi1.name, pi2.name)) return false;
5509        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5510        // We'll take care of setting this one.
5511        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5512        // These are not currently stored in settings.
5513        //if (!compareStrings(pi1.group, pi2.group)) return false;
5514        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5515        //if (pi1.labelRes != pi2.labelRes) return false;
5516        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5517        return true;
5518    }
5519
5520    int permissionInfoFootprint(PermissionInfo info) {
5521        int size = info.name.length();
5522        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5523        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5524        return size;
5525    }
5526
5527    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5528        int size = 0;
5529        for (BasePermission perm : mSettings.mPermissions.values()) {
5530            if (perm.uid == tree.uid) {
5531                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5532            }
5533        }
5534        return size;
5535    }
5536
5537    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5538        // We calculate the max size of permissions defined by this uid and throw
5539        // if that plus the size of 'info' would exceed our stated maximum.
5540        if (tree.uid != Process.SYSTEM_UID) {
5541            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5542            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5543                throw new SecurityException("Permission tree size cap exceeded");
5544            }
5545        }
5546    }
5547
5548    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5549        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5550            throw new SecurityException("Instant apps can't add permissions");
5551        }
5552        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5553            throw new SecurityException("Label must be specified in permission");
5554        }
5555        BasePermission tree = checkPermissionTreeLP(info.name);
5556        BasePermission bp = mSettings.mPermissions.get(info.name);
5557        boolean added = bp == null;
5558        boolean changed = true;
5559        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5560        if (added) {
5561            enforcePermissionCapLocked(info, tree);
5562            bp = new BasePermission(info.name, tree.sourcePackage,
5563                    BasePermission.TYPE_DYNAMIC);
5564        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5565            throw new SecurityException(
5566                    "Not allowed to modify non-dynamic permission "
5567                    + info.name);
5568        } else {
5569            if (bp.protectionLevel == fixedLevel
5570                    && bp.perm.owner.equals(tree.perm.owner)
5571                    && bp.uid == tree.uid
5572                    && comparePermissionInfos(bp.perm.info, info)) {
5573                changed = false;
5574            }
5575        }
5576        bp.protectionLevel = fixedLevel;
5577        info = new PermissionInfo(info);
5578        info.protectionLevel = fixedLevel;
5579        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5580        bp.perm.info.packageName = tree.perm.info.packageName;
5581        bp.uid = tree.uid;
5582        if (added) {
5583            mSettings.mPermissions.put(info.name, bp);
5584        }
5585        if (changed) {
5586            if (!async) {
5587                mSettings.writeLPr();
5588            } else {
5589                scheduleWriteSettingsLocked();
5590            }
5591        }
5592        return added;
5593    }
5594
5595    @Override
5596    public boolean addPermission(PermissionInfo info) {
5597        synchronized (mPackages) {
5598            return addPermissionLocked(info, false);
5599        }
5600    }
5601
5602    @Override
5603    public boolean addPermissionAsync(PermissionInfo info) {
5604        synchronized (mPackages) {
5605            return addPermissionLocked(info, true);
5606        }
5607    }
5608
5609    @Override
5610    public void removePermission(String name) {
5611        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5612            throw new SecurityException("Instant applications don't have access to this method");
5613        }
5614        synchronized (mPackages) {
5615            checkPermissionTreeLP(name);
5616            BasePermission bp = mSettings.mPermissions.get(name);
5617            if (bp != null) {
5618                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5619                    throw new SecurityException(
5620                            "Not allowed to modify non-dynamic permission "
5621                            + name);
5622                }
5623                mSettings.mPermissions.remove(name);
5624                mSettings.writeLPr();
5625            }
5626        }
5627    }
5628
5629    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5630            PackageParser.Package pkg, BasePermission bp) {
5631        int index = pkg.requestedPermissions.indexOf(bp.name);
5632        if (index == -1) {
5633            throw new SecurityException("Package " + pkg.packageName
5634                    + " has not requested permission " + bp.name);
5635        }
5636        if (!bp.isRuntime() && !bp.isDevelopment()) {
5637            throw new SecurityException("Permission " + bp.name
5638                    + " is not a changeable permission type");
5639        }
5640    }
5641
5642    @Override
5643    public void grantRuntimePermission(String packageName, String name, final int userId) {
5644        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5645    }
5646
5647    private void grantRuntimePermission(String packageName, String name, final int userId,
5648            boolean overridePolicy) {
5649        if (!sUserManager.exists(userId)) {
5650            Log.e(TAG, "No such user:" + userId);
5651            return;
5652        }
5653        final int callingUid = Binder.getCallingUid();
5654
5655        mContext.enforceCallingOrSelfPermission(
5656                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5657                "grantRuntimePermission");
5658
5659        enforceCrossUserPermission(callingUid, userId,
5660                true /* requireFullPermission */, true /* checkShell */,
5661                "grantRuntimePermission");
5662
5663        final int uid;
5664        final PackageSetting ps;
5665
5666        synchronized (mPackages) {
5667            final PackageParser.Package pkg = mPackages.get(packageName);
5668            if (pkg == null) {
5669                throw new IllegalArgumentException("Unknown package: " + packageName);
5670            }
5671            final BasePermission bp = mSettings.mPermissions.get(name);
5672            if (bp == null) {
5673                throw new IllegalArgumentException("Unknown permission: " + name);
5674            }
5675            ps = (PackageSetting) pkg.mExtras;
5676            if (ps == null
5677                    || filterAppAccessLPr(ps, callingUid, userId)) {
5678                throw new IllegalArgumentException("Unknown package: " + packageName);
5679            }
5680
5681            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5682
5683            // If a permission review is required for legacy apps we represent
5684            // their permissions as always granted runtime ones since we need
5685            // to keep the review required permission flag per user while an
5686            // install permission's state is shared across all users.
5687            if (mPermissionReviewRequired
5688                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5689                    && bp.isRuntime()) {
5690                return;
5691            }
5692
5693            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5694
5695            final PermissionsState permissionsState = ps.getPermissionsState();
5696
5697            final int flags = permissionsState.getPermissionFlags(name, userId);
5698            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5699                throw new SecurityException("Cannot grant system fixed permission "
5700                        + name + " for package " + packageName);
5701            }
5702            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5703                throw new SecurityException("Cannot grant policy fixed permission "
5704                        + name + " for package " + packageName);
5705            }
5706
5707            if (bp.isDevelopment()) {
5708                // Development permissions must be handled specially, since they are not
5709                // normal runtime permissions.  For now they apply to all users.
5710                if (permissionsState.grantInstallPermission(bp) !=
5711                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5712                    scheduleWriteSettingsLocked();
5713                }
5714                return;
5715            }
5716
5717            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5718                throw new SecurityException("Cannot grant non-ephemeral permission"
5719                        + name + " for package " + packageName);
5720            }
5721
5722            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5723                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5724                return;
5725            }
5726
5727            final int result = permissionsState.grantRuntimePermission(bp, userId);
5728            switch (result) {
5729                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5730                    return;
5731                }
5732
5733                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5734                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5735                    mHandler.post(new Runnable() {
5736                        @Override
5737                        public void run() {
5738                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5739                        }
5740                    });
5741                }
5742                break;
5743            }
5744
5745            if (bp.isRuntime()) {
5746                logPermissionGranted(mContext, name, packageName);
5747            }
5748
5749            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5750
5751            // Not critical if that is lost - app has to request again.
5752            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5753        }
5754
5755        // Only need to do this if user is initialized. Otherwise it's a new user
5756        // and there are no processes running as the user yet and there's no need
5757        // to make an expensive call to remount processes for the changed permissions.
5758        if (READ_EXTERNAL_STORAGE.equals(name)
5759                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5760            final long token = Binder.clearCallingIdentity();
5761            try {
5762                if (sUserManager.isInitialized(userId)) {
5763                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5764                            StorageManagerInternal.class);
5765                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5766                }
5767            } finally {
5768                Binder.restoreCallingIdentity(token);
5769            }
5770        }
5771    }
5772
5773    @Override
5774    public void revokeRuntimePermission(String packageName, String name, int userId) {
5775        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5776    }
5777
5778    private void revokeRuntimePermission(String packageName, String name, int userId,
5779            boolean overridePolicy) {
5780        if (!sUserManager.exists(userId)) {
5781            Log.e(TAG, "No such user:" + userId);
5782            return;
5783        }
5784
5785        mContext.enforceCallingOrSelfPermission(
5786                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5787                "revokeRuntimePermission");
5788
5789        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5790                true /* requireFullPermission */, true /* checkShell */,
5791                "revokeRuntimePermission");
5792
5793        final int appId;
5794
5795        synchronized (mPackages) {
5796            final PackageParser.Package pkg = mPackages.get(packageName);
5797            if (pkg == null) {
5798                throw new IllegalArgumentException("Unknown package: " + packageName);
5799            }
5800            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5801            if (ps == null
5802                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5803                throw new IllegalArgumentException("Unknown package: " + packageName);
5804            }
5805            final BasePermission bp = mSettings.mPermissions.get(name);
5806            if (bp == null) {
5807                throw new IllegalArgumentException("Unknown permission: " + name);
5808            }
5809
5810            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5811
5812            // If a permission review is required for legacy apps we represent
5813            // their permissions as always granted runtime ones since we need
5814            // to keep the review required permission flag per user while an
5815            // install permission's state is shared across all users.
5816            if (mPermissionReviewRequired
5817                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5818                    && bp.isRuntime()) {
5819                return;
5820            }
5821
5822            final PermissionsState permissionsState = ps.getPermissionsState();
5823
5824            final int flags = permissionsState.getPermissionFlags(name, userId);
5825            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5826                throw new SecurityException("Cannot revoke system fixed permission "
5827                        + name + " for package " + packageName);
5828            }
5829            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5830                throw new SecurityException("Cannot revoke policy fixed permission "
5831                        + name + " for package " + packageName);
5832            }
5833
5834            if (bp.isDevelopment()) {
5835                // Development permissions must be handled specially, since they are not
5836                // normal runtime permissions.  For now they apply to all users.
5837                if (permissionsState.revokeInstallPermission(bp) !=
5838                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5839                    scheduleWriteSettingsLocked();
5840                }
5841                return;
5842            }
5843
5844            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5845                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5846                return;
5847            }
5848
5849            if (bp.isRuntime()) {
5850                logPermissionRevoked(mContext, name, packageName);
5851            }
5852
5853            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5854
5855            // Critical, after this call app should never have the permission.
5856            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5857
5858            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5859        }
5860
5861        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5862    }
5863
5864    /**
5865     * Get the first event id for the permission.
5866     *
5867     * <p>There are four events for each permission: <ul>
5868     *     <li>Request permission: first id + 0</li>
5869     *     <li>Grant permission: first id + 1</li>
5870     *     <li>Request for permission denied: first id + 2</li>
5871     *     <li>Revoke permission: first id + 3</li>
5872     * </ul></p>
5873     *
5874     * @param name name of the permission
5875     *
5876     * @return The first event id for the permission
5877     */
5878    private static int getBaseEventId(@NonNull String name) {
5879        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5880
5881        if (eventIdIndex == -1) {
5882            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5883                    || Build.IS_USER) {
5884                Log.i(TAG, "Unknown permission " + name);
5885
5886                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5887            } else {
5888                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5889                //
5890                // Also update
5891                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5892                // - metrics_constants.proto
5893                throw new IllegalStateException("Unknown permission " + name);
5894            }
5895        }
5896
5897        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5898    }
5899
5900    /**
5901     * Log that a permission was revoked.
5902     *
5903     * @param context Context of the caller
5904     * @param name name of the permission
5905     * @param packageName package permission if for
5906     */
5907    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5908            @NonNull String packageName) {
5909        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5910    }
5911
5912    /**
5913     * Log that a permission request was granted.
5914     *
5915     * @param context Context of the caller
5916     * @param name name of the permission
5917     * @param packageName package permission if for
5918     */
5919    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5920            @NonNull String packageName) {
5921        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5922    }
5923
5924    @Override
5925    public void resetRuntimePermissions() {
5926        mContext.enforceCallingOrSelfPermission(
5927                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5928                "revokeRuntimePermission");
5929
5930        int callingUid = Binder.getCallingUid();
5931        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5932            mContext.enforceCallingOrSelfPermission(
5933                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5934                    "resetRuntimePermissions");
5935        }
5936
5937        synchronized (mPackages) {
5938            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5939            for (int userId : UserManagerService.getInstance().getUserIds()) {
5940                final int packageCount = mPackages.size();
5941                for (int i = 0; i < packageCount; i++) {
5942                    PackageParser.Package pkg = mPackages.valueAt(i);
5943                    if (!(pkg.mExtras instanceof PackageSetting)) {
5944                        continue;
5945                    }
5946                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5947                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5948                }
5949            }
5950        }
5951    }
5952
5953    @Override
5954    public int getPermissionFlags(String name, String packageName, int userId) {
5955        if (!sUserManager.exists(userId)) {
5956            return 0;
5957        }
5958
5959        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5960
5961        final int callingUid = Binder.getCallingUid();
5962        enforceCrossUserPermission(callingUid, userId,
5963                true /* requireFullPermission */, false /* checkShell */,
5964                "getPermissionFlags");
5965
5966        synchronized (mPackages) {
5967            final PackageParser.Package pkg = mPackages.get(packageName);
5968            if (pkg == null) {
5969                return 0;
5970            }
5971            final BasePermission bp = mSettings.mPermissions.get(name);
5972            if (bp == null) {
5973                return 0;
5974            }
5975            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5976            if (ps == null
5977                    || filterAppAccessLPr(ps, callingUid, userId)) {
5978                return 0;
5979            }
5980            PermissionsState permissionsState = ps.getPermissionsState();
5981            return permissionsState.getPermissionFlags(name, userId);
5982        }
5983    }
5984
5985    @Override
5986    public void updatePermissionFlags(String name, String packageName, int flagMask,
5987            int flagValues, int userId) {
5988        if (!sUserManager.exists(userId)) {
5989            return;
5990        }
5991
5992        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5993
5994        final int callingUid = Binder.getCallingUid();
5995        enforceCrossUserPermission(callingUid, userId,
5996                true /* requireFullPermission */, true /* checkShell */,
5997                "updatePermissionFlags");
5998
5999        // Only the system can change these flags and nothing else.
6000        if (getCallingUid() != Process.SYSTEM_UID) {
6001            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6002            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6003            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6004            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6005            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
6006        }
6007
6008        synchronized (mPackages) {
6009            final PackageParser.Package pkg = mPackages.get(packageName);
6010            if (pkg == null) {
6011                throw new IllegalArgumentException("Unknown package: " + packageName);
6012            }
6013            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6014            if (ps == null
6015                    || filterAppAccessLPr(ps, callingUid, userId)) {
6016                throw new IllegalArgumentException("Unknown package: " + packageName);
6017            }
6018
6019            final BasePermission bp = mSettings.mPermissions.get(name);
6020            if (bp == null) {
6021                throw new IllegalArgumentException("Unknown permission: " + name);
6022            }
6023
6024            PermissionsState permissionsState = ps.getPermissionsState();
6025
6026            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6027
6028            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6029                // Install and runtime permissions are stored in different places,
6030                // so figure out what permission changed and persist the change.
6031                if (permissionsState.getInstallPermissionState(name) != null) {
6032                    scheduleWriteSettingsLocked();
6033                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6034                        || hadState) {
6035                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6036                }
6037            }
6038        }
6039    }
6040
6041    /**
6042     * Update the permission flags for all packages and runtime permissions of a user in order
6043     * to allow device or profile owner to remove POLICY_FIXED.
6044     */
6045    @Override
6046    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6047        if (!sUserManager.exists(userId)) {
6048            return;
6049        }
6050
6051        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6052
6053        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6054                true /* requireFullPermission */, true /* checkShell */,
6055                "updatePermissionFlagsForAllApps");
6056
6057        // Only the system can change system fixed flags.
6058        if (getCallingUid() != Process.SYSTEM_UID) {
6059            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6060            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6061        }
6062
6063        synchronized (mPackages) {
6064            boolean changed = false;
6065            final int packageCount = mPackages.size();
6066            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6067                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6068                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6069                if (ps == null) {
6070                    continue;
6071                }
6072                PermissionsState permissionsState = ps.getPermissionsState();
6073                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6074                        userId, flagMask, flagValues);
6075            }
6076            if (changed) {
6077                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6078            }
6079        }
6080    }
6081
6082    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6083        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6084                != PackageManager.PERMISSION_GRANTED
6085            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6086                != PackageManager.PERMISSION_GRANTED) {
6087            throw new SecurityException(message + " requires "
6088                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6089                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6090        }
6091    }
6092
6093    @Override
6094    public boolean shouldShowRequestPermissionRationale(String permissionName,
6095            String packageName, int userId) {
6096        if (UserHandle.getCallingUserId() != userId) {
6097            mContext.enforceCallingPermission(
6098                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6099                    "canShowRequestPermissionRationale for user " + userId);
6100        }
6101
6102        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6103        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6104            return false;
6105        }
6106
6107        if (checkPermission(permissionName, packageName, userId)
6108                == PackageManager.PERMISSION_GRANTED) {
6109            return false;
6110        }
6111
6112        final int flags;
6113
6114        final long identity = Binder.clearCallingIdentity();
6115        try {
6116            flags = getPermissionFlags(permissionName,
6117                    packageName, userId);
6118        } finally {
6119            Binder.restoreCallingIdentity(identity);
6120        }
6121
6122        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6123                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6124                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6125
6126        if ((flags & fixedFlags) != 0) {
6127            return false;
6128        }
6129
6130        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6131    }
6132
6133    @Override
6134    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6135        mContext.enforceCallingOrSelfPermission(
6136                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6137                "addOnPermissionsChangeListener");
6138
6139        synchronized (mPackages) {
6140            mOnPermissionChangeListeners.addListenerLocked(listener);
6141        }
6142    }
6143
6144    @Override
6145    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6146        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6147            throw new SecurityException("Instant applications don't have access to this method");
6148        }
6149        synchronized (mPackages) {
6150            mOnPermissionChangeListeners.removeListenerLocked(listener);
6151        }
6152    }
6153
6154    @Override
6155    public boolean isProtectedBroadcast(String actionName) {
6156        // allow instant applications
6157        synchronized (mProtectedBroadcasts) {
6158            if (mProtectedBroadcasts.contains(actionName)) {
6159                return true;
6160            } else if (actionName != null) {
6161                // TODO: remove these terrible hacks
6162                if (actionName.startsWith("android.net.netmon.lingerExpired")
6163                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6164                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6165                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6166                    return true;
6167                }
6168            }
6169        }
6170        return false;
6171    }
6172
6173    @Override
6174    public int checkSignatures(String pkg1, String pkg2) {
6175        synchronized (mPackages) {
6176            final PackageParser.Package p1 = mPackages.get(pkg1);
6177            final PackageParser.Package p2 = mPackages.get(pkg2);
6178            if (p1 == null || p1.mExtras == null
6179                    || p2 == null || p2.mExtras == null) {
6180                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6181            }
6182            final int callingUid = Binder.getCallingUid();
6183            final int callingUserId = UserHandle.getUserId(callingUid);
6184            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6185            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6186            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6187                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6188                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6189            }
6190            return compareSignatures(p1.mSignatures, p2.mSignatures);
6191        }
6192    }
6193
6194    @Override
6195    public int checkUidSignatures(int uid1, int uid2) {
6196        final int callingUid = Binder.getCallingUid();
6197        final int callingUserId = UserHandle.getUserId(callingUid);
6198        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6199        // Map to base uids.
6200        uid1 = UserHandle.getAppId(uid1);
6201        uid2 = UserHandle.getAppId(uid2);
6202        // reader
6203        synchronized (mPackages) {
6204            Signature[] s1;
6205            Signature[] s2;
6206            Object obj = mSettings.getUserIdLPr(uid1);
6207            if (obj != null) {
6208                if (obj instanceof SharedUserSetting) {
6209                    if (isCallerInstantApp) {
6210                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6211                    }
6212                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6213                } else if (obj instanceof PackageSetting) {
6214                    final PackageSetting ps = (PackageSetting) obj;
6215                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6216                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6217                    }
6218                    s1 = ps.signatures.mSignatures;
6219                } else {
6220                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6221                }
6222            } else {
6223                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6224            }
6225            obj = mSettings.getUserIdLPr(uid2);
6226            if (obj != null) {
6227                if (obj instanceof SharedUserSetting) {
6228                    if (isCallerInstantApp) {
6229                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6230                    }
6231                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6232                } else if (obj instanceof PackageSetting) {
6233                    final PackageSetting ps = (PackageSetting) obj;
6234                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6235                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6236                    }
6237                    s2 = ps.signatures.mSignatures;
6238                } else {
6239                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6240                }
6241            } else {
6242                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6243            }
6244            return compareSignatures(s1, s2);
6245        }
6246    }
6247
6248    /**
6249     * This method should typically only be used when granting or revoking
6250     * permissions, since the app may immediately restart after this call.
6251     * <p>
6252     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6253     * guard your work against the app being relaunched.
6254     */
6255    private void killUid(int appId, int userId, String reason) {
6256        final long identity = Binder.clearCallingIdentity();
6257        try {
6258            IActivityManager am = ActivityManager.getService();
6259            if (am != null) {
6260                try {
6261                    am.killUid(appId, userId, reason);
6262                } catch (RemoteException e) {
6263                    /* ignore - same process */
6264                }
6265            }
6266        } finally {
6267            Binder.restoreCallingIdentity(identity);
6268        }
6269    }
6270
6271    /**
6272     * Compares two sets of signatures. Returns:
6273     * <br />
6274     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6275     * <br />
6276     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6277     * <br />
6278     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6279     * <br />
6280     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6281     * <br />
6282     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6283     */
6284    static int compareSignatures(Signature[] s1, Signature[] s2) {
6285        if (s1 == null) {
6286            return s2 == null
6287                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6288                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6289        }
6290
6291        if (s2 == null) {
6292            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6293        }
6294
6295        if (s1.length != s2.length) {
6296            return PackageManager.SIGNATURE_NO_MATCH;
6297        }
6298
6299        // Since both signature sets are of size 1, we can compare without HashSets.
6300        if (s1.length == 1) {
6301            return s1[0].equals(s2[0]) ?
6302                    PackageManager.SIGNATURE_MATCH :
6303                    PackageManager.SIGNATURE_NO_MATCH;
6304        }
6305
6306        ArraySet<Signature> set1 = new ArraySet<Signature>();
6307        for (Signature sig : s1) {
6308            set1.add(sig);
6309        }
6310        ArraySet<Signature> set2 = new ArraySet<Signature>();
6311        for (Signature sig : s2) {
6312            set2.add(sig);
6313        }
6314        // Make sure s2 contains all signatures in s1.
6315        if (set1.equals(set2)) {
6316            return PackageManager.SIGNATURE_MATCH;
6317        }
6318        return PackageManager.SIGNATURE_NO_MATCH;
6319    }
6320
6321    /**
6322     * If the database version for this type of package (internal storage or
6323     * external storage) is less than the version where package signatures
6324     * were updated, return true.
6325     */
6326    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6327        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6328        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6329    }
6330
6331    /**
6332     * Used for backward compatibility to make sure any packages with
6333     * certificate chains get upgraded to the new style. {@code existingSigs}
6334     * will be in the old format (since they were stored on disk from before the
6335     * system upgrade) and {@code scannedSigs} will be in the newer format.
6336     */
6337    private int compareSignaturesCompat(PackageSignatures existingSigs,
6338            PackageParser.Package scannedPkg) {
6339        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6340            return PackageManager.SIGNATURE_NO_MATCH;
6341        }
6342
6343        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6344        for (Signature sig : existingSigs.mSignatures) {
6345            existingSet.add(sig);
6346        }
6347        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6348        for (Signature sig : scannedPkg.mSignatures) {
6349            try {
6350                Signature[] chainSignatures = sig.getChainSignatures();
6351                for (Signature chainSig : chainSignatures) {
6352                    scannedCompatSet.add(chainSig);
6353                }
6354            } catch (CertificateEncodingException e) {
6355                scannedCompatSet.add(sig);
6356            }
6357        }
6358        /*
6359         * Make sure the expanded scanned set contains all signatures in the
6360         * existing one.
6361         */
6362        if (scannedCompatSet.equals(existingSet)) {
6363            // Migrate the old signatures to the new scheme.
6364            existingSigs.assignSignatures(scannedPkg.mSignatures);
6365            // The new KeySets will be re-added later in the scanning process.
6366            synchronized (mPackages) {
6367                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6368            }
6369            return PackageManager.SIGNATURE_MATCH;
6370        }
6371        return PackageManager.SIGNATURE_NO_MATCH;
6372    }
6373
6374    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6375        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6376        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6377    }
6378
6379    private int compareSignaturesRecover(PackageSignatures existingSigs,
6380            PackageParser.Package scannedPkg) {
6381        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6382            return PackageManager.SIGNATURE_NO_MATCH;
6383        }
6384
6385        String msg = null;
6386        try {
6387            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6388                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6389                        + scannedPkg.packageName);
6390                return PackageManager.SIGNATURE_MATCH;
6391            }
6392        } catch (CertificateException e) {
6393            msg = e.getMessage();
6394        }
6395
6396        logCriticalInfo(Log.INFO,
6397                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6398        return PackageManager.SIGNATURE_NO_MATCH;
6399    }
6400
6401    @Override
6402    public List<String> getAllPackages() {
6403        final int callingUid = Binder.getCallingUid();
6404        final int callingUserId = UserHandle.getUserId(callingUid);
6405        synchronized (mPackages) {
6406            if (canViewInstantApps(callingUid, callingUserId)) {
6407                return new ArrayList<String>(mPackages.keySet());
6408            }
6409            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6410            final List<String> result = new ArrayList<>();
6411            if (instantAppPkgName != null) {
6412                // caller is an instant application; filter unexposed applications
6413                for (PackageParser.Package pkg : mPackages.values()) {
6414                    if (!pkg.visibleToInstantApps) {
6415                        continue;
6416                    }
6417                    result.add(pkg.packageName);
6418                }
6419            } else {
6420                // caller is a normal application; filter instant applications
6421                for (PackageParser.Package pkg : mPackages.values()) {
6422                    final PackageSetting ps =
6423                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6424                    if (ps != null
6425                            && ps.getInstantApp(callingUserId)
6426                            && !mInstantAppRegistry.isInstantAccessGranted(
6427                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6428                        continue;
6429                    }
6430                    result.add(pkg.packageName);
6431                }
6432            }
6433            return result;
6434        }
6435    }
6436
6437    @Override
6438    public String[] getPackagesForUid(int uid) {
6439        final int callingUid = Binder.getCallingUid();
6440        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6441        final int userId = UserHandle.getUserId(uid);
6442        uid = UserHandle.getAppId(uid);
6443        // reader
6444        synchronized (mPackages) {
6445            Object obj = mSettings.getUserIdLPr(uid);
6446            if (obj instanceof SharedUserSetting) {
6447                if (isCallerInstantApp) {
6448                    return null;
6449                }
6450                final SharedUserSetting sus = (SharedUserSetting) obj;
6451                final int N = sus.packages.size();
6452                String[] res = new String[N];
6453                final Iterator<PackageSetting> it = sus.packages.iterator();
6454                int i = 0;
6455                while (it.hasNext()) {
6456                    PackageSetting ps = it.next();
6457                    if (ps.getInstalled(userId)) {
6458                        res[i++] = ps.name;
6459                    } else {
6460                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6461                    }
6462                }
6463                return res;
6464            } else if (obj instanceof PackageSetting) {
6465                final PackageSetting ps = (PackageSetting) obj;
6466                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6467                    return new String[]{ps.name};
6468                }
6469            }
6470        }
6471        return null;
6472    }
6473
6474    @Override
6475    public String getNameForUid(int uid) {
6476        final int callingUid = Binder.getCallingUid();
6477        if (getInstantAppPackageName(callingUid) != null) {
6478            return null;
6479        }
6480        synchronized (mPackages) {
6481            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6482            if (obj instanceof SharedUserSetting) {
6483                final SharedUserSetting sus = (SharedUserSetting) obj;
6484                return sus.name + ":" + sus.userId;
6485            } else if (obj instanceof PackageSetting) {
6486                final PackageSetting ps = (PackageSetting) obj;
6487                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6488                    return null;
6489                }
6490                return ps.name;
6491            }
6492            return null;
6493        }
6494    }
6495
6496    @Override
6497    public String[] getNamesForUids(int[] uids) {
6498        if (uids == null || uids.length == 0) {
6499            return null;
6500        }
6501        final int callingUid = Binder.getCallingUid();
6502        if (getInstantAppPackageName(callingUid) != null) {
6503            return null;
6504        }
6505        final String[] names = new String[uids.length];
6506        synchronized (mPackages) {
6507            for (int i = uids.length - 1; i >= 0; i--) {
6508                final int uid = uids[i];
6509                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6510                if (obj instanceof SharedUserSetting) {
6511                    final SharedUserSetting sus = (SharedUserSetting) obj;
6512                    names[i] = "shared:" + sus.name;
6513                } else if (obj instanceof PackageSetting) {
6514                    final PackageSetting ps = (PackageSetting) obj;
6515                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6516                        names[i] = null;
6517                    } else {
6518                        names[i] = ps.name;
6519                    }
6520                } else {
6521                    names[i] = null;
6522                }
6523            }
6524        }
6525        return names;
6526    }
6527
6528    @Override
6529    public int getUidForSharedUser(String sharedUserName) {
6530        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6531            return -1;
6532        }
6533        if (sharedUserName == null) {
6534            return -1;
6535        }
6536        // reader
6537        synchronized (mPackages) {
6538            SharedUserSetting suid;
6539            try {
6540                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6541                if (suid != null) {
6542                    return suid.userId;
6543                }
6544            } catch (PackageManagerException ignore) {
6545                // can't happen, but, still need to catch it
6546            }
6547            return -1;
6548        }
6549    }
6550
6551    @Override
6552    public int getFlagsForUid(int uid) {
6553        final int callingUid = Binder.getCallingUid();
6554        if (getInstantAppPackageName(callingUid) != null) {
6555            return 0;
6556        }
6557        synchronized (mPackages) {
6558            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6559            if (obj instanceof SharedUserSetting) {
6560                final SharedUserSetting sus = (SharedUserSetting) obj;
6561                return sus.pkgFlags;
6562            } else if (obj instanceof PackageSetting) {
6563                final PackageSetting ps = (PackageSetting) obj;
6564                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6565                    return 0;
6566                }
6567                return ps.pkgFlags;
6568            }
6569        }
6570        return 0;
6571    }
6572
6573    @Override
6574    public int getPrivateFlagsForUid(int uid) {
6575        final int callingUid = Binder.getCallingUid();
6576        if (getInstantAppPackageName(callingUid) != null) {
6577            return 0;
6578        }
6579        synchronized (mPackages) {
6580            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6581            if (obj instanceof SharedUserSetting) {
6582                final SharedUserSetting sus = (SharedUserSetting) obj;
6583                return sus.pkgPrivateFlags;
6584            } else if (obj instanceof PackageSetting) {
6585                final PackageSetting ps = (PackageSetting) obj;
6586                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6587                    return 0;
6588                }
6589                return ps.pkgPrivateFlags;
6590            }
6591        }
6592        return 0;
6593    }
6594
6595    @Override
6596    public boolean isUidPrivileged(int uid) {
6597        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6598            return false;
6599        }
6600        uid = UserHandle.getAppId(uid);
6601        // reader
6602        synchronized (mPackages) {
6603            Object obj = mSettings.getUserIdLPr(uid);
6604            if (obj instanceof SharedUserSetting) {
6605                final SharedUserSetting sus = (SharedUserSetting) obj;
6606                final Iterator<PackageSetting> it = sus.packages.iterator();
6607                while (it.hasNext()) {
6608                    if (it.next().isPrivileged()) {
6609                        return true;
6610                    }
6611                }
6612            } else if (obj instanceof PackageSetting) {
6613                final PackageSetting ps = (PackageSetting) obj;
6614                return ps.isPrivileged();
6615            }
6616        }
6617        return false;
6618    }
6619
6620    @Override
6621    public String[] getAppOpPermissionPackages(String permissionName) {
6622        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6623            return null;
6624        }
6625        synchronized (mPackages) {
6626            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6627            if (pkgs == null) {
6628                return null;
6629            }
6630            return pkgs.toArray(new String[pkgs.size()]);
6631        }
6632    }
6633
6634    @Override
6635    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6636            int flags, int userId) {
6637        return resolveIntentInternal(
6638                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6639    }
6640
6641    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6642            int flags, int userId, boolean resolveForStart) {
6643        try {
6644            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6645
6646            if (!sUserManager.exists(userId)) return null;
6647            final int callingUid = Binder.getCallingUid();
6648            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6649            enforceCrossUserPermission(callingUid, userId,
6650                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6651
6652            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6653            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6654                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6655            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6656
6657            final ResolveInfo bestChoice =
6658                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6659            return bestChoice;
6660        } finally {
6661            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6662        }
6663    }
6664
6665    @Override
6666    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6667        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6668            throw new SecurityException(
6669                    "findPersistentPreferredActivity can only be run by the system");
6670        }
6671        if (!sUserManager.exists(userId)) {
6672            return null;
6673        }
6674        final int callingUid = Binder.getCallingUid();
6675        intent = updateIntentForResolve(intent);
6676        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6677        final int flags = updateFlagsForResolve(
6678                0, userId, intent, callingUid, false /*includeInstantApps*/);
6679        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6680                userId);
6681        synchronized (mPackages) {
6682            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6683                    userId);
6684        }
6685    }
6686
6687    @Override
6688    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6689            IntentFilter filter, int match, ComponentName activity) {
6690        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6691            return;
6692        }
6693        final int userId = UserHandle.getCallingUserId();
6694        if (DEBUG_PREFERRED) {
6695            Log.v(TAG, "setLastChosenActivity intent=" + intent
6696                + " resolvedType=" + resolvedType
6697                + " flags=" + flags
6698                + " filter=" + filter
6699                + " match=" + match
6700                + " activity=" + activity);
6701            filter.dump(new PrintStreamPrinter(System.out), "    ");
6702        }
6703        intent.setComponent(null);
6704        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6705                userId);
6706        // Find any earlier preferred or last chosen entries and nuke them
6707        findPreferredActivity(intent, resolvedType,
6708                flags, query, 0, false, true, false, userId);
6709        // Add the new activity as the last chosen for this filter
6710        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6711                "Setting last chosen");
6712    }
6713
6714    @Override
6715    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6716        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6717            return null;
6718        }
6719        final int userId = UserHandle.getCallingUserId();
6720        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6721        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6722                userId);
6723        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6724                false, false, false, userId);
6725    }
6726
6727    /**
6728     * Returns whether or not instant apps have been disabled remotely.
6729     */
6730    private boolean isEphemeralDisabled() {
6731        return mEphemeralAppsDisabled;
6732    }
6733
6734    private boolean isInstantAppAllowed(
6735            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6736            boolean skipPackageCheck) {
6737        if (mInstantAppResolverConnection == null) {
6738            return false;
6739        }
6740        if (mInstantAppInstallerActivity == null) {
6741            return false;
6742        }
6743        if (intent.getComponent() != null) {
6744            return false;
6745        }
6746        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6747            return false;
6748        }
6749        if (!skipPackageCheck && intent.getPackage() != null) {
6750            return false;
6751        }
6752        final boolean isWebUri = hasWebURI(intent);
6753        if (!isWebUri || intent.getData().getHost() == null) {
6754            return false;
6755        }
6756        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6757        // Or if there's already an ephemeral app installed that handles the action
6758        synchronized (mPackages) {
6759            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6760            for (int n = 0; n < count; n++) {
6761                final ResolveInfo info = resolvedActivities.get(n);
6762                final String packageName = info.activityInfo.packageName;
6763                final PackageSetting ps = mSettings.mPackages.get(packageName);
6764                if (ps != null) {
6765                    // only check domain verification status if the app is not a browser
6766                    if (!info.handleAllWebDataURI) {
6767                        // Try to get the status from User settings first
6768                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6769                        final int status = (int) (packedStatus >> 32);
6770                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6771                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6772                            if (DEBUG_EPHEMERAL) {
6773                                Slog.v(TAG, "DENY instant app;"
6774                                    + " pkg: " + packageName + ", status: " + status);
6775                            }
6776                            return false;
6777                        }
6778                    }
6779                    if (ps.getInstantApp(userId)) {
6780                        if (DEBUG_EPHEMERAL) {
6781                            Slog.v(TAG, "DENY instant app installed;"
6782                                    + " pkg: " + packageName);
6783                        }
6784                        return false;
6785                    }
6786                }
6787            }
6788        }
6789        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6790        return true;
6791    }
6792
6793    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6794            Intent origIntent, String resolvedType, String callingPackage,
6795            Bundle verificationBundle, int userId) {
6796        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6797                new InstantAppRequest(responseObj, origIntent, resolvedType,
6798                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6799        mHandler.sendMessage(msg);
6800    }
6801
6802    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6803            int flags, List<ResolveInfo> query, int userId) {
6804        if (query != null) {
6805            final int N = query.size();
6806            if (N == 1) {
6807                return query.get(0);
6808            } else if (N > 1) {
6809                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6810                // If there is more than one activity with the same priority,
6811                // then let the user decide between them.
6812                ResolveInfo r0 = query.get(0);
6813                ResolveInfo r1 = query.get(1);
6814                if (DEBUG_INTENT_MATCHING || debug) {
6815                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6816                            + r1.activityInfo.name + "=" + r1.priority);
6817                }
6818                // If the first activity has a higher priority, or a different
6819                // default, then it is always desirable to pick it.
6820                if (r0.priority != r1.priority
6821                        || r0.preferredOrder != r1.preferredOrder
6822                        || r0.isDefault != r1.isDefault) {
6823                    return query.get(0);
6824                }
6825                // If we have saved a preference for a preferred activity for
6826                // this Intent, use that.
6827                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6828                        flags, query, r0.priority, true, false, debug, userId);
6829                if (ri != null) {
6830                    return ri;
6831                }
6832                // If we have an ephemeral app, use it
6833                for (int i = 0; i < N; i++) {
6834                    ri = query.get(i);
6835                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6836                        final String packageName = ri.activityInfo.packageName;
6837                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6838                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6839                        final int status = (int)(packedStatus >> 32);
6840                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6841                            return ri;
6842                        }
6843                    }
6844                }
6845                ri = new ResolveInfo(mResolveInfo);
6846                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6847                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6848                // If all of the options come from the same package, show the application's
6849                // label and icon instead of the generic resolver's.
6850                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6851                // and then throw away the ResolveInfo itself, meaning that the caller loses
6852                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6853                // a fallback for this case; we only set the target package's resources on
6854                // the ResolveInfo, not the ActivityInfo.
6855                final String intentPackage = intent.getPackage();
6856                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6857                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6858                    ri.resolvePackageName = intentPackage;
6859                    if (userNeedsBadging(userId)) {
6860                        ri.noResourceId = true;
6861                    } else {
6862                        ri.icon = appi.icon;
6863                    }
6864                    ri.iconResourceId = appi.icon;
6865                    ri.labelRes = appi.labelRes;
6866                }
6867                ri.activityInfo.applicationInfo = new ApplicationInfo(
6868                        ri.activityInfo.applicationInfo);
6869                if (userId != 0) {
6870                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6871                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6872                }
6873                // Make sure that the resolver is displayable in car mode
6874                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6875                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6876                return ri;
6877            }
6878        }
6879        return null;
6880    }
6881
6882    /**
6883     * Return true if the given list is not empty and all of its contents have
6884     * an activityInfo with the given package name.
6885     */
6886    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6887        if (ArrayUtils.isEmpty(list)) {
6888            return false;
6889        }
6890        for (int i = 0, N = list.size(); i < N; i++) {
6891            final ResolveInfo ri = list.get(i);
6892            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6893            if (ai == null || !packageName.equals(ai.packageName)) {
6894                return false;
6895            }
6896        }
6897        return true;
6898    }
6899
6900    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6901            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6902        final int N = query.size();
6903        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6904                .get(userId);
6905        // Get the list of persistent preferred activities that handle the intent
6906        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6907        List<PersistentPreferredActivity> pprefs = ppir != null
6908                ? ppir.queryIntent(intent, resolvedType,
6909                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6910                        userId)
6911                : null;
6912        if (pprefs != null && pprefs.size() > 0) {
6913            final int M = pprefs.size();
6914            for (int i=0; i<M; i++) {
6915                final PersistentPreferredActivity ppa = pprefs.get(i);
6916                if (DEBUG_PREFERRED || debug) {
6917                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6918                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6919                            + "\n  component=" + ppa.mComponent);
6920                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6921                }
6922                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6923                        flags | MATCH_DISABLED_COMPONENTS, userId);
6924                if (DEBUG_PREFERRED || debug) {
6925                    Slog.v(TAG, "Found persistent preferred activity:");
6926                    if (ai != null) {
6927                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6928                    } else {
6929                        Slog.v(TAG, "  null");
6930                    }
6931                }
6932                if (ai == null) {
6933                    // This previously registered persistent preferred activity
6934                    // component is no longer known. Ignore it and do NOT remove it.
6935                    continue;
6936                }
6937                for (int j=0; j<N; j++) {
6938                    final ResolveInfo ri = query.get(j);
6939                    if (!ri.activityInfo.applicationInfo.packageName
6940                            .equals(ai.applicationInfo.packageName)) {
6941                        continue;
6942                    }
6943                    if (!ri.activityInfo.name.equals(ai.name)) {
6944                        continue;
6945                    }
6946                    //  Found a persistent preference that can handle the intent.
6947                    if (DEBUG_PREFERRED || debug) {
6948                        Slog.v(TAG, "Returning persistent preferred activity: " +
6949                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6950                    }
6951                    return ri;
6952                }
6953            }
6954        }
6955        return null;
6956    }
6957
6958    // TODO: handle preferred activities missing while user has amnesia
6959    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6960            List<ResolveInfo> query, int priority, boolean always,
6961            boolean removeMatches, boolean debug, int userId) {
6962        if (!sUserManager.exists(userId)) return null;
6963        final int callingUid = Binder.getCallingUid();
6964        flags = updateFlagsForResolve(
6965                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6966        intent = updateIntentForResolve(intent);
6967        // writer
6968        synchronized (mPackages) {
6969            // Try to find a matching persistent preferred activity.
6970            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6971                    debug, userId);
6972
6973            // If a persistent preferred activity matched, use it.
6974            if (pri != null) {
6975                return pri;
6976            }
6977
6978            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6979            // Get the list of preferred activities that handle the intent
6980            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6981            List<PreferredActivity> prefs = pir != null
6982                    ? pir.queryIntent(intent, resolvedType,
6983                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6984                            userId)
6985                    : null;
6986            if (prefs != null && prefs.size() > 0) {
6987                boolean changed = false;
6988                try {
6989                    // First figure out how good the original match set is.
6990                    // We will only allow preferred activities that came
6991                    // from the same match quality.
6992                    int match = 0;
6993
6994                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6995
6996                    final int N = query.size();
6997                    for (int j=0; j<N; j++) {
6998                        final ResolveInfo ri = query.get(j);
6999                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
7000                                + ": 0x" + Integer.toHexString(match));
7001                        if (ri.match > match) {
7002                            match = ri.match;
7003                        }
7004                    }
7005
7006                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
7007                            + Integer.toHexString(match));
7008
7009                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7010                    final int M = prefs.size();
7011                    for (int i=0; i<M; i++) {
7012                        final PreferredActivity pa = prefs.get(i);
7013                        if (DEBUG_PREFERRED || debug) {
7014                            Slog.v(TAG, "Checking PreferredActivity ds="
7015                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7016                                    + "\n  component=" + pa.mPref.mComponent);
7017                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7018                        }
7019                        if (pa.mPref.mMatch != match) {
7020                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7021                                    + Integer.toHexString(pa.mPref.mMatch));
7022                            continue;
7023                        }
7024                        // If it's not an "always" type preferred activity and that's what we're
7025                        // looking for, skip it.
7026                        if (always && !pa.mPref.mAlways) {
7027                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7028                            continue;
7029                        }
7030                        final ActivityInfo ai = getActivityInfo(
7031                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7032                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7033                                userId);
7034                        if (DEBUG_PREFERRED || debug) {
7035                            Slog.v(TAG, "Found preferred activity:");
7036                            if (ai != null) {
7037                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7038                            } else {
7039                                Slog.v(TAG, "  null");
7040                            }
7041                        }
7042                        if (ai == null) {
7043                            // This previously registered preferred activity
7044                            // component is no longer known.  Most likely an update
7045                            // to the app was installed and in the new version this
7046                            // component no longer exists.  Clean it up by removing
7047                            // it from the preferred activities list, and skip it.
7048                            Slog.w(TAG, "Removing dangling preferred activity: "
7049                                    + pa.mPref.mComponent);
7050                            pir.removeFilter(pa);
7051                            changed = true;
7052                            continue;
7053                        }
7054                        for (int j=0; j<N; j++) {
7055                            final ResolveInfo ri = query.get(j);
7056                            if (!ri.activityInfo.applicationInfo.packageName
7057                                    .equals(ai.applicationInfo.packageName)) {
7058                                continue;
7059                            }
7060                            if (!ri.activityInfo.name.equals(ai.name)) {
7061                                continue;
7062                            }
7063
7064                            if (removeMatches) {
7065                                pir.removeFilter(pa);
7066                                changed = true;
7067                                if (DEBUG_PREFERRED) {
7068                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7069                                }
7070                                break;
7071                            }
7072
7073                            // Okay we found a previously set preferred or last chosen app.
7074                            // If the result set is different from when this
7075                            // was created, and is not a subset of the preferred set, we need to
7076                            // clear it and re-ask the user their preference, if we're looking for
7077                            // an "always" type entry.
7078                            if (always && !pa.mPref.sameSet(query)) {
7079                                if (pa.mPref.isSuperset(query)) {
7080                                    // some components of the set are no longer present in
7081                                    // the query, but the preferred activity can still be reused
7082                                    if (DEBUG_PREFERRED) {
7083                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7084                                                + " still valid as only non-preferred components"
7085                                                + " were removed for " + intent + " type "
7086                                                + resolvedType);
7087                                    }
7088                                    // remove obsolete components and re-add the up-to-date filter
7089                                    PreferredActivity freshPa = new PreferredActivity(pa,
7090                                            pa.mPref.mMatch,
7091                                            pa.mPref.discardObsoleteComponents(query),
7092                                            pa.mPref.mComponent,
7093                                            pa.mPref.mAlways);
7094                                    pir.removeFilter(pa);
7095                                    pir.addFilter(freshPa);
7096                                    changed = true;
7097                                } else {
7098                                    Slog.i(TAG,
7099                                            "Result set changed, dropping preferred activity for "
7100                                                    + intent + " type " + resolvedType);
7101                                    if (DEBUG_PREFERRED) {
7102                                        Slog.v(TAG, "Removing preferred activity since set changed "
7103                                                + pa.mPref.mComponent);
7104                                    }
7105                                    pir.removeFilter(pa);
7106                                    // Re-add the filter as a "last chosen" entry (!always)
7107                                    PreferredActivity lastChosen = new PreferredActivity(
7108                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7109                                    pir.addFilter(lastChosen);
7110                                    changed = true;
7111                                    return null;
7112                                }
7113                            }
7114
7115                            // Yay! Either the set matched or we're looking for the last chosen
7116                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7117                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7118                            return ri;
7119                        }
7120                    }
7121                } finally {
7122                    if (changed) {
7123                        if (DEBUG_PREFERRED) {
7124                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7125                        }
7126                        scheduleWritePackageRestrictionsLocked(userId);
7127                    }
7128                }
7129            }
7130        }
7131        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7132        return null;
7133    }
7134
7135    /*
7136     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7137     */
7138    @Override
7139    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7140            int targetUserId) {
7141        mContext.enforceCallingOrSelfPermission(
7142                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7143        List<CrossProfileIntentFilter> matches =
7144                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7145        if (matches != null) {
7146            int size = matches.size();
7147            for (int i = 0; i < size; i++) {
7148                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7149            }
7150        }
7151        if (hasWebURI(intent)) {
7152            // cross-profile app linking works only towards the parent.
7153            final int callingUid = Binder.getCallingUid();
7154            final UserInfo parent = getProfileParent(sourceUserId);
7155            synchronized(mPackages) {
7156                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7157                        false /*includeInstantApps*/);
7158                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7159                        intent, resolvedType, flags, sourceUserId, parent.id);
7160                return xpDomainInfo != null;
7161            }
7162        }
7163        return false;
7164    }
7165
7166    private UserInfo getProfileParent(int userId) {
7167        final long identity = Binder.clearCallingIdentity();
7168        try {
7169            return sUserManager.getProfileParent(userId);
7170        } finally {
7171            Binder.restoreCallingIdentity(identity);
7172        }
7173    }
7174
7175    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7176            String resolvedType, int userId) {
7177        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7178        if (resolver != null) {
7179            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7180        }
7181        return null;
7182    }
7183
7184    @Override
7185    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7186            String resolvedType, int flags, int userId) {
7187        try {
7188            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7189
7190            return new ParceledListSlice<>(
7191                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7192        } finally {
7193            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7194        }
7195    }
7196
7197    /**
7198     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7199     * instant, returns {@code null}.
7200     */
7201    private String getInstantAppPackageName(int callingUid) {
7202        synchronized (mPackages) {
7203            // If the caller is an isolated app use the owner's uid for the lookup.
7204            if (Process.isIsolated(callingUid)) {
7205                callingUid = mIsolatedOwners.get(callingUid);
7206            }
7207            final int appId = UserHandle.getAppId(callingUid);
7208            final Object obj = mSettings.getUserIdLPr(appId);
7209            if (obj instanceof PackageSetting) {
7210                final PackageSetting ps = (PackageSetting) obj;
7211                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7212                return isInstantApp ? ps.pkg.packageName : null;
7213            }
7214        }
7215        return null;
7216    }
7217
7218    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7219            String resolvedType, int flags, int userId) {
7220        return queryIntentActivitiesInternal(
7221                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7222                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7223    }
7224
7225    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7226            String resolvedType, int flags, int filterCallingUid, int userId,
7227            boolean resolveForStart, boolean allowDynamicSplits) {
7228        if (!sUserManager.exists(userId)) return Collections.emptyList();
7229        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7230        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7231                false /* requireFullPermission */, false /* checkShell */,
7232                "query intent activities");
7233        final String pkgName = intent.getPackage();
7234        ComponentName comp = intent.getComponent();
7235        if (comp == null) {
7236            if (intent.getSelector() != null) {
7237                intent = intent.getSelector();
7238                comp = intent.getComponent();
7239            }
7240        }
7241
7242        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7243                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7244        if (comp != null) {
7245            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7246            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7247            if (ai != null) {
7248                // When specifying an explicit component, we prevent the activity from being
7249                // used when either 1) the calling package is normal and the activity is within
7250                // an ephemeral application or 2) the calling package is ephemeral and the
7251                // activity is not visible to ephemeral applications.
7252                final boolean matchInstantApp =
7253                        (flags & PackageManager.MATCH_INSTANT) != 0;
7254                final boolean matchVisibleToInstantAppOnly =
7255                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7256                final boolean matchExplicitlyVisibleOnly =
7257                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7258                final boolean isCallerInstantApp =
7259                        instantAppPkgName != null;
7260                final boolean isTargetSameInstantApp =
7261                        comp.getPackageName().equals(instantAppPkgName);
7262                final boolean isTargetInstantApp =
7263                        (ai.applicationInfo.privateFlags
7264                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7265                final boolean isTargetVisibleToInstantApp =
7266                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7267                final boolean isTargetExplicitlyVisibleToInstantApp =
7268                        isTargetVisibleToInstantApp
7269                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7270                final boolean isTargetHiddenFromInstantApp =
7271                        !isTargetVisibleToInstantApp
7272                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7273                final boolean blockResolution =
7274                        !isTargetSameInstantApp
7275                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7276                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7277                                        && isTargetHiddenFromInstantApp));
7278                if (!blockResolution) {
7279                    final ResolveInfo ri = new ResolveInfo();
7280                    ri.activityInfo = ai;
7281                    list.add(ri);
7282                }
7283            }
7284            return applyPostResolutionFilter(
7285                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7286        }
7287
7288        // reader
7289        boolean sortResult = false;
7290        boolean addEphemeral = false;
7291        List<ResolveInfo> result;
7292        final boolean ephemeralDisabled = isEphemeralDisabled();
7293        synchronized (mPackages) {
7294            if (pkgName == null) {
7295                List<CrossProfileIntentFilter> matchingFilters =
7296                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7297                // Check for results that need to skip the current profile.
7298                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7299                        resolvedType, flags, userId);
7300                if (xpResolveInfo != null) {
7301                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7302                    xpResult.add(xpResolveInfo);
7303                    return applyPostResolutionFilter(
7304                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7305                            allowDynamicSplits, filterCallingUid, userId);
7306                }
7307
7308                // Check for results in the current profile.
7309                result = filterIfNotSystemUser(mActivities.queryIntent(
7310                        intent, resolvedType, flags, userId), userId);
7311                addEphemeral = !ephemeralDisabled
7312                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7313                // Check for cross profile results.
7314                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7315                xpResolveInfo = queryCrossProfileIntents(
7316                        matchingFilters, intent, resolvedType, flags, userId,
7317                        hasNonNegativePriorityResult);
7318                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7319                    boolean isVisibleToUser = filterIfNotSystemUser(
7320                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7321                    if (isVisibleToUser) {
7322                        result.add(xpResolveInfo);
7323                        sortResult = true;
7324                    }
7325                }
7326                if (hasWebURI(intent)) {
7327                    CrossProfileDomainInfo xpDomainInfo = null;
7328                    final UserInfo parent = getProfileParent(userId);
7329                    if (parent != null) {
7330                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7331                                flags, userId, parent.id);
7332                    }
7333                    if (xpDomainInfo != null) {
7334                        if (xpResolveInfo != null) {
7335                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7336                            // in the result.
7337                            result.remove(xpResolveInfo);
7338                        }
7339                        if (result.size() == 0 && !addEphemeral) {
7340                            // No result in current profile, but found candidate in parent user.
7341                            // And we are not going to add emphemeral app, so we can return the
7342                            // result straight away.
7343                            result.add(xpDomainInfo.resolveInfo);
7344                            return applyPostResolutionFilter(result, instantAppPkgName,
7345                                    allowDynamicSplits, filterCallingUid, userId);
7346                        }
7347                    } else if (result.size() <= 1 && !addEphemeral) {
7348                        // No result in parent user and <= 1 result in current profile, and we
7349                        // are not going to add emphemeral app, so we can return the result without
7350                        // further processing.
7351                        return applyPostResolutionFilter(result, instantAppPkgName,
7352                                allowDynamicSplits, filterCallingUid, userId);
7353                    }
7354                    // We have more than one candidate (combining results from current and parent
7355                    // profile), so we need filtering and sorting.
7356                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7357                            intent, flags, result, xpDomainInfo, userId);
7358                    sortResult = true;
7359                }
7360            } else {
7361                final PackageParser.Package pkg = mPackages.get(pkgName);
7362                result = null;
7363                if (pkg != null) {
7364                    result = filterIfNotSystemUser(
7365                            mActivities.queryIntentForPackage(
7366                                    intent, resolvedType, flags, pkg.activities, userId),
7367                            userId);
7368                }
7369                if (result == null || result.size() == 0) {
7370                    // the caller wants to resolve for a particular package; however, there
7371                    // were no installed results, so, try to find an ephemeral result
7372                    addEphemeral = !ephemeralDisabled
7373                            && isInstantAppAllowed(
7374                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7375                    if (result == null) {
7376                        result = new ArrayList<>();
7377                    }
7378                }
7379            }
7380        }
7381        if (addEphemeral) {
7382            result = maybeAddInstantAppInstaller(
7383                    result, intent, resolvedType, flags, userId, resolveForStart);
7384        }
7385        if (sortResult) {
7386            Collections.sort(result, mResolvePrioritySorter);
7387        }
7388        return applyPostResolutionFilter(
7389                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7390    }
7391
7392    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7393            String resolvedType, int flags, int userId, boolean resolveForStart) {
7394        // first, check to see if we've got an instant app already installed
7395        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7396        ResolveInfo localInstantApp = null;
7397        boolean blockResolution = false;
7398        if (!alreadyResolvedLocally) {
7399            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7400                    flags
7401                        | PackageManager.GET_RESOLVED_FILTER
7402                        | PackageManager.MATCH_INSTANT
7403                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7404                    userId);
7405            for (int i = instantApps.size() - 1; i >= 0; --i) {
7406                final ResolveInfo info = instantApps.get(i);
7407                final String packageName = info.activityInfo.packageName;
7408                final PackageSetting ps = mSettings.mPackages.get(packageName);
7409                if (ps.getInstantApp(userId)) {
7410                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7411                    final int status = (int)(packedStatus >> 32);
7412                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7413                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7414                        // there's a local instant application installed, but, the user has
7415                        // chosen to never use it; skip resolution and don't acknowledge
7416                        // an instant application is even available
7417                        if (DEBUG_EPHEMERAL) {
7418                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7419                        }
7420                        blockResolution = true;
7421                        break;
7422                    } else {
7423                        // we have a locally installed instant application; skip resolution
7424                        // but acknowledge there's an instant application available
7425                        if (DEBUG_EPHEMERAL) {
7426                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7427                        }
7428                        localInstantApp = info;
7429                        break;
7430                    }
7431                }
7432            }
7433        }
7434        // no app installed, let's see if one's available
7435        AuxiliaryResolveInfo auxiliaryResponse = null;
7436        if (!blockResolution) {
7437            if (localInstantApp == null) {
7438                // we don't have an instant app locally, resolve externally
7439                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7440                final InstantAppRequest requestObject = new InstantAppRequest(
7441                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7442                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7443                        resolveForStart);
7444                auxiliaryResponse =
7445                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7446                                mContext, mInstantAppResolverConnection, requestObject);
7447                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7448            } else {
7449                // we have an instant application locally, but, we can't admit that since
7450                // callers shouldn't be able to determine prior browsing. create a dummy
7451                // auxiliary response so the downstream code behaves as if there's an
7452                // instant application available externally. when it comes time to start
7453                // the instant application, we'll do the right thing.
7454                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7455                auxiliaryResponse = new AuxiliaryResolveInfo(
7456                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7457                        ai.versionCode, null /*failureIntent*/);
7458            }
7459        }
7460        if (auxiliaryResponse != null) {
7461            if (DEBUG_EPHEMERAL) {
7462                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7463            }
7464            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7465            final PackageSetting ps =
7466                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7467            if (ps != null) {
7468                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7469                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7470                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7471                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7472                // make sure this resolver is the default
7473                ephemeralInstaller.isDefault = true;
7474                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7475                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7476                // add a non-generic filter
7477                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7478                ephemeralInstaller.filter.addDataPath(
7479                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7480                ephemeralInstaller.isInstantAppAvailable = true;
7481                result.add(ephemeralInstaller);
7482            }
7483        }
7484        return result;
7485    }
7486
7487    private static class CrossProfileDomainInfo {
7488        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7489        ResolveInfo resolveInfo;
7490        /* Best domain verification status of the activities found in the other profile */
7491        int bestDomainVerificationStatus;
7492    }
7493
7494    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7495            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7496        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7497                sourceUserId)) {
7498            return null;
7499        }
7500        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7501                resolvedType, flags, parentUserId);
7502
7503        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7504            return null;
7505        }
7506        CrossProfileDomainInfo result = null;
7507        int size = resultTargetUser.size();
7508        for (int i = 0; i < size; i++) {
7509            ResolveInfo riTargetUser = resultTargetUser.get(i);
7510            // Intent filter verification is only for filters that specify a host. So don't return
7511            // those that handle all web uris.
7512            if (riTargetUser.handleAllWebDataURI) {
7513                continue;
7514            }
7515            String packageName = riTargetUser.activityInfo.packageName;
7516            PackageSetting ps = mSettings.mPackages.get(packageName);
7517            if (ps == null) {
7518                continue;
7519            }
7520            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7521            int status = (int)(verificationState >> 32);
7522            if (result == null) {
7523                result = new CrossProfileDomainInfo();
7524                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7525                        sourceUserId, parentUserId);
7526                result.bestDomainVerificationStatus = status;
7527            } else {
7528                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7529                        result.bestDomainVerificationStatus);
7530            }
7531        }
7532        // Don't consider matches with status NEVER across profiles.
7533        if (result != null && result.bestDomainVerificationStatus
7534                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7535            return null;
7536        }
7537        return result;
7538    }
7539
7540    /**
7541     * Verification statuses are ordered from the worse to the best, except for
7542     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7543     */
7544    private int bestDomainVerificationStatus(int status1, int status2) {
7545        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7546            return status2;
7547        }
7548        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7549            return status1;
7550        }
7551        return (int) MathUtils.max(status1, status2);
7552    }
7553
7554    private boolean isUserEnabled(int userId) {
7555        long callingId = Binder.clearCallingIdentity();
7556        try {
7557            UserInfo userInfo = sUserManager.getUserInfo(userId);
7558            return userInfo != null && userInfo.isEnabled();
7559        } finally {
7560            Binder.restoreCallingIdentity(callingId);
7561        }
7562    }
7563
7564    /**
7565     * Filter out activities with systemUserOnly flag set, when current user is not System.
7566     *
7567     * @return filtered list
7568     */
7569    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7570        if (userId == UserHandle.USER_SYSTEM) {
7571            return resolveInfos;
7572        }
7573        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7574            ResolveInfo info = resolveInfos.get(i);
7575            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7576                resolveInfos.remove(i);
7577            }
7578        }
7579        return resolveInfos;
7580    }
7581
7582    /**
7583     * Filters out ephemeral activities.
7584     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7585     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7586     *
7587     * @param resolveInfos The pre-filtered list of resolved activities
7588     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7589     *          is performed.
7590     * @return A filtered list of resolved activities.
7591     */
7592    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7593            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7594        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7595            final ResolveInfo info = resolveInfos.get(i);
7596            // allow activities that are defined in the provided package
7597            if (allowDynamicSplits
7598                    && info.activityInfo.splitName != null
7599                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7600                            info.activityInfo.splitName)) {
7601                // requested activity is defined in a split that hasn't been installed yet.
7602                // add the installer to the resolve list
7603                if (DEBUG_INSTALL) {
7604                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7605                }
7606                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7607                final ComponentName installFailureActivity = findInstallFailureActivity(
7608                        info.activityInfo.packageName,  filterCallingUid, userId);
7609                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7610                        info.activityInfo.packageName, info.activityInfo.splitName,
7611                        installFailureActivity,
7612                        info.activityInfo.applicationInfo.versionCode,
7613                        null /*failureIntent*/);
7614                // make sure this resolver is the default
7615                installerInfo.isDefault = true;
7616                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7617                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7618                // add a non-generic filter
7619                installerInfo.filter = new IntentFilter();
7620                // load resources from the correct package
7621                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7622                resolveInfos.set(i, installerInfo);
7623                continue;
7624            }
7625            // caller is a full app, don't need to apply any other filtering
7626            if (ephemeralPkgName == null) {
7627                continue;
7628            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7629                // caller is same app; don't need to apply any other filtering
7630                continue;
7631            }
7632            // allow activities that have been explicitly exposed to ephemeral apps
7633            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7634            if (!isEphemeralApp
7635                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7636                continue;
7637            }
7638            resolveInfos.remove(i);
7639        }
7640        return resolveInfos;
7641    }
7642
7643    /**
7644     * Returns the activity component that can handle install failures.
7645     * <p>By default, the instant application installer handles failures. However, an
7646     * application may want to handle failures on its own. Applications do this by
7647     * creating an activity with an intent filter that handles the action
7648     * {@link Intent#ACTION_INSTALL_FAILURE}.
7649     */
7650    private @Nullable ComponentName findInstallFailureActivity(
7651            String packageName, int filterCallingUid, int userId) {
7652        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7653        failureActivityIntent.setPackage(packageName);
7654        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7655        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7656                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7657                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7658        final int NR = result.size();
7659        if (NR > 0) {
7660            for (int i = 0; i < NR; i++) {
7661                final ResolveInfo info = result.get(i);
7662                if (info.activityInfo.splitName != null) {
7663                    continue;
7664                }
7665                return new ComponentName(packageName, info.activityInfo.name);
7666            }
7667        }
7668        return null;
7669    }
7670
7671    /**
7672     * @param resolveInfos list of resolve infos in descending priority order
7673     * @return if the list contains a resolve info with non-negative priority
7674     */
7675    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7676        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7677    }
7678
7679    private static boolean hasWebURI(Intent intent) {
7680        if (intent.getData() == null) {
7681            return false;
7682        }
7683        final String scheme = intent.getScheme();
7684        if (TextUtils.isEmpty(scheme)) {
7685            return false;
7686        }
7687        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7688    }
7689
7690    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7691            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7692            int userId) {
7693        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7694
7695        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7696            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7697                    candidates.size());
7698        }
7699
7700        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7701        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7702        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7703        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7704        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7705        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7706
7707        synchronized (mPackages) {
7708            final int count = candidates.size();
7709            // First, try to use linked apps. Partition the candidates into four lists:
7710            // one for the final results, one for the "do not use ever", one for "undefined status"
7711            // and finally one for "browser app type".
7712            for (int n=0; n<count; n++) {
7713                ResolveInfo info = candidates.get(n);
7714                String packageName = info.activityInfo.packageName;
7715                PackageSetting ps = mSettings.mPackages.get(packageName);
7716                if (ps != null) {
7717                    // Add to the special match all list (Browser use case)
7718                    if (info.handleAllWebDataURI) {
7719                        matchAllList.add(info);
7720                        continue;
7721                    }
7722                    // Try to get the status from User settings first
7723                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7724                    int status = (int)(packedStatus >> 32);
7725                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7726                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7727                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7728                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7729                                    + " : linkgen=" + linkGeneration);
7730                        }
7731                        // Use link-enabled generation as preferredOrder, i.e.
7732                        // prefer newly-enabled over earlier-enabled.
7733                        info.preferredOrder = linkGeneration;
7734                        alwaysList.add(info);
7735                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7736                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7737                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7738                        }
7739                        neverList.add(info);
7740                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7741                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7742                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7743                        }
7744                        alwaysAskList.add(info);
7745                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7746                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7747                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7748                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7749                        }
7750                        undefinedList.add(info);
7751                    }
7752                }
7753            }
7754
7755            // We'll want to include browser possibilities in a few cases
7756            boolean includeBrowser = false;
7757
7758            // First try to add the "always" resolution(s) for the current user, if any
7759            if (alwaysList.size() > 0) {
7760                result.addAll(alwaysList);
7761            } else {
7762                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7763                result.addAll(undefinedList);
7764                // Maybe add one for the other profile.
7765                if (xpDomainInfo != null && (
7766                        xpDomainInfo.bestDomainVerificationStatus
7767                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7768                    result.add(xpDomainInfo.resolveInfo);
7769                }
7770                includeBrowser = true;
7771            }
7772
7773            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7774            // If there were 'always' entries their preferred order has been set, so we also
7775            // back that off to make the alternatives equivalent
7776            if (alwaysAskList.size() > 0) {
7777                for (ResolveInfo i : result) {
7778                    i.preferredOrder = 0;
7779                }
7780                result.addAll(alwaysAskList);
7781                includeBrowser = true;
7782            }
7783
7784            if (includeBrowser) {
7785                // Also add browsers (all of them or only the default one)
7786                if (DEBUG_DOMAIN_VERIFICATION) {
7787                    Slog.v(TAG, "   ...including browsers in candidate set");
7788                }
7789                if ((matchFlags & MATCH_ALL) != 0) {
7790                    result.addAll(matchAllList);
7791                } else {
7792                    // Browser/generic handling case.  If there's a default browser, go straight
7793                    // to that (but only if there is no other higher-priority match).
7794                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7795                    int maxMatchPrio = 0;
7796                    ResolveInfo defaultBrowserMatch = null;
7797                    final int numCandidates = matchAllList.size();
7798                    for (int n = 0; n < numCandidates; n++) {
7799                        ResolveInfo info = matchAllList.get(n);
7800                        // track the highest overall match priority...
7801                        if (info.priority > maxMatchPrio) {
7802                            maxMatchPrio = info.priority;
7803                        }
7804                        // ...and the highest-priority default browser match
7805                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7806                            if (defaultBrowserMatch == null
7807                                    || (defaultBrowserMatch.priority < info.priority)) {
7808                                if (debug) {
7809                                    Slog.v(TAG, "Considering default browser match " + info);
7810                                }
7811                                defaultBrowserMatch = info;
7812                            }
7813                        }
7814                    }
7815                    if (defaultBrowserMatch != null
7816                            && defaultBrowserMatch.priority >= maxMatchPrio
7817                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7818                    {
7819                        if (debug) {
7820                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7821                        }
7822                        result.add(defaultBrowserMatch);
7823                    } else {
7824                        result.addAll(matchAllList);
7825                    }
7826                }
7827
7828                // If there is nothing selected, add all candidates and remove the ones that the user
7829                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7830                if (result.size() == 0) {
7831                    result.addAll(candidates);
7832                    result.removeAll(neverList);
7833                }
7834            }
7835        }
7836        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7837            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7838                    result.size());
7839            for (ResolveInfo info : result) {
7840                Slog.v(TAG, "  + " + info.activityInfo);
7841            }
7842        }
7843        return result;
7844    }
7845
7846    // Returns a packed value as a long:
7847    //
7848    // high 'int'-sized word: link status: undefined/ask/never/always.
7849    // low 'int'-sized word: relative priority among 'always' results.
7850    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7851        long result = ps.getDomainVerificationStatusForUser(userId);
7852        // if none available, get the master status
7853        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7854            if (ps.getIntentFilterVerificationInfo() != null) {
7855                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7856            }
7857        }
7858        return result;
7859    }
7860
7861    private ResolveInfo querySkipCurrentProfileIntents(
7862            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7863            int flags, int sourceUserId) {
7864        if (matchingFilters != null) {
7865            int size = matchingFilters.size();
7866            for (int i = 0; i < size; i ++) {
7867                CrossProfileIntentFilter filter = matchingFilters.get(i);
7868                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7869                    // Checking if there are activities in the target user that can handle the
7870                    // intent.
7871                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7872                            resolvedType, flags, sourceUserId);
7873                    if (resolveInfo != null) {
7874                        return resolveInfo;
7875                    }
7876                }
7877            }
7878        }
7879        return null;
7880    }
7881
7882    // Return matching ResolveInfo in target user if any.
7883    private ResolveInfo queryCrossProfileIntents(
7884            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7885            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7886        if (matchingFilters != null) {
7887            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7888            // match the same intent. For performance reasons, it is better not to
7889            // run queryIntent twice for the same userId
7890            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7891            int size = matchingFilters.size();
7892            for (int i = 0; i < size; i++) {
7893                CrossProfileIntentFilter filter = matchingFilters.get(i);
7894                int targetUserId = filter.getTargetUserId();
7895                boolean skipCurrentProfile =
7896                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7897                boolean skipCurrentProfileIfNoMatchFound =
7898                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7899                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7900                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7901                    // Checking if there are activities in the target user that can handle the
7902                    // intent.
7903                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7904                            resolvedType, flags, sourceUserId);
7905                    if (resolveInfo != null) return resolveInfo;
7906                    alreadyTriedUserIds.put(targetUserId, true);
7907                }
7908            }
7909        }
7910        return null;
7911    }
7912
7913    /**
7914     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7915     * will forward the intent to the filter's target user.
7916     * Otherwise, returns null.
7917     */
7918    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7919            String resolvedType, int flags, int sourceUserId) {
7920        int targetUserId = filter.getTargetUserId();
7921        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7922                resolvedType, flags, targetUserId);
7923        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7924            // If all the matches in the target profile are suspended, return null.
7925            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7926                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7927                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7928                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7929                            targetUserId);
7930                }
7931            }
7932        }
7933        return null;
7934    }
7935
7936    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7937            int sourceUserId, int targetUserId) {
7938        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7939        long ident = Binder.clearCallingIdentity();
7940        boolean targetIsProfile;
7941        try {
7942            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7943        } finally {
7944            Binder.restoreCallingIdentity(ident);
7945        }
7946        String className;
7947        if (targetIsProfile) {
7948            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7949        } else {
7950            className = FORWARD_INTENT_TO_PARENT;
7951        }
7952        ComponentName forwardingActivityComponentName = new ComponentName(
7953                mAndroidApplication.packageName, className);
7954        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7955                sourceUserId);
7956        if (!targetIsProfile) {
7957            forwardingActivityInfo.showUserIcon = targetUserId;
7958            forwardingResolveInfo.noResourceId = true;
7959        }
7960        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7961        forwardingResolveInfo.priority = 0;
7962        forwardingResolveInfo.preferredOrder = 0;
7963        forwardingResolveInfo.match = 0;
7964        forwardingResolveInfo.isDefault = true;
7965        forwardingResolveInfo.filter = filter;
7966        forwardingResolveInfo.targetUserId = targetUserId;
7967        return forwardingResolveInfo;
7968    }
7969
7970    @Override
7971    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7972            Intent[] specifics, String[] specificTypes, Intent intent,
7973            String resolvedType, int flags, int userId) {
7974        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7975                specificTypes, intent, resolvedType, flags, userId));
7976    }
7977
7978    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7979            Intent[] specifics, String[] specificTypes, Intent intent,
7980            String resolvedType, int flags, int userId) {
7981        if (!sUserManager.exists(userId)) return Collections.emptyList();
7982        final int callingUid = Binder.getCallingUid();
7983        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7984                false /*includeInstantApps*/);
7985        enforceCrossUserPermission(callingUid, userId,
7986                false /*requireFullPermission*/, false /*checkShell*/,
7987                "query intent activity options");
7988        final String resultsAction = intent.getAction();
7989
7990        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7991                | PackageManager.GET_RESOLVED_FILTER, userId);
7992
7993        if (DEBUG_INTENT_MATCHING) {
7994            Log.v(TAG, "Query " + intent + ": " + results);
7995        }
7996
7997        int specificsPos = 0;
7998        int N;
7999
8000        // todo: note that the algorithm used here is O(N^2).  This
8001        // isn't a problem in our current environment, but if we start running
8002        // into situations where we have more than 5 or 10 matches then this
8003        // should probably be changed to something smarter...
8004
8005        // First we go through and resolve each of the specific items
8006        // that were supplied, taking care of removing any corresponding
8007        // duplicate items in the generic resolve list.
8008        if (specifics != null) {
8009            for (int i=0; i<specifics.length; i++) {
8010                final Intent sintent = specifics[i];
8011                if (sintent == null) {
8012                    continue;
8013                }
8014
8015                if (DEBUG_INTENT_MATCHING) {
8016                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8017                }
8018
8019                String action = sintent.getAction();
8020                if (resultsAction != null && resultsAction.equals(action)) {
8021                    // If this action was explicitly requested, then don't
8022                    // remove things that have it.
8023                    action = null;
8024                }
8025
8026                ResolveInfo ri = null;
8027                ActivityInfo ai = null;
8028
8029                ComponentName comp = sintent.getComponent();
8030                if (comp == null) {
8031                    ri = resolveIntent(
8032                        sintent,
8033                        specificTypes != null ? specificTypes[i] : null,
8034                            flags, userId);
8035                    if (ri == null) {
8036                        continue;
8037                    }
8038                    if (ri == mResolveInfo) {
8039                        // ACK!  Must do something better with this.
8040                    }
8041                    ai = ri.activityInfo;
8042                    comp = new ComponentName(ai.applicationInfo.packageName,
8043                            ai.name);
8044                } else {
8045                    ai = getActivityInfo(comp, flags, userId);
8046                    if (ai == null) {
8047                        continue;
8048                    }
8049                }
8050
8051                // Look for any generic query activities that are duplicates
8052                // of this specific one, and remove them from the results.
8053                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8054                N = results.size();
8055                int j;
8056                for (j=specificsPos; j<N; j++) {
8057                    ResolveInfo sri = results.get(j);
8058                    if ((sri.activityInfo.name.equals(comp.getClassName())
8059                            && sri.activityInfo.applicationInfo.packageName.equals(
8060                                    comp.getPackageName()))
8061                        || (action != null && sri.filter.matchAction(action))) {
8062                        results.remove(j);
8063                        if (DEBUG_INTENT_MATCHING) Log.v(
8064                            TAG, "Removing duplicate item from " + j
8065                            + " due to specific " + specificsPos);
8066                        if (ri == null) {
8067                            ri = sri;
8068                        }
8069                        j--;
8070                        N--;
8071                    }
8072                }
8073
8074                // Add this specific item to its proper place.
8075                if (ri == null) {
8076                    ri = new ResolveInfo();
8077                    ri.activityInfo = ai;
8078                }
8079                results.add(specificsPos, ri);
8080                ri.specificIndex = i;
8081                specificsPos++;
8082            }
8083        }
8084
8085        // Now we go through the remaining generic results and remove any
8086        // duplicate actions that are found here.
8087        N = results.size();
8088        for (int i=specificsPos; i<N-1; i++) {
8089            final ResolveInfo rii = results.get(i);
8090            if (rii.filter == null) {
8091                continue;
8092            }
8093
8094            // Iterate over all of the actions of this result's intent
8095            // filter...  typically this should be just one.
8096            final Iterator<String> it = rii.filter.actionsIterator();
8097            if (it == null) {
8098                continue;
8099            }
8100            while (it.hasNext()) {
8101                final String action = it.next();
8102                if (resultsAction != null && resultsAction.equals(action)) {
8103                    // If this action was explicitly requested, then don't
8104                    // remove things that have it.
8105                    continue;
8106                }
8107                for (int j=i+1; j<N; j++) {
8108                    final ResolveInfo rij = results.get(j);
8109                    if (rij.filter != null && rij.filter.hasAction(action)) {
8110                        results.remove(j);
8111                        if (DEBUG_INTENT_MATCHING) Log.v(
8112                            TAG, "Removing duplicate item from " + j
8113                            + " due to action " + action + " at " + i);
8114                        j--;
8115                        N--;
8116                    }
8117                }
8118            }
8119
8120            // If the caller didn't request filter information, drop it now
8121            // so we don't have to marshall/unmarshall it.
8122            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8123                rii.filter = null;
8124            }
8125        }
8126
8127        // Filter out the caller activity if so requested.
8128        if (caller != null) {
8129            N = results.size();
8130            for (int i=0; i<N; i++) {
8131                ActivityInfo ainfo = results.get(i).activityInfo;
8132                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8133                        && caller.getClassName().equals(ainfo.name)) {
8134                    results.remove(i);
8135                    break;
8136                }
8137            }
8138        }
8139
8140        // If the caller didn't request filter information,
8141        // drop them now so we don't have to
8142        // marshall/unmarshall it.
8143        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8144            N = results.size();
8145            for (int i=0; i<N; i++) {
8146                results.get(i).filter = null;
8147            }
8148        }
8149
8150        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8151        return results;
8152    }
8153
8154    @Override
8155    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8156            String resolvedType, int flags, int userId) {
8157        return new ParceledListSlice<>(
8158                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8159                        false /*allowDynamicSplits*/));
8160    }
8161
8162    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8163            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8164        if (!sUserManager.exists(userId)) return Collections.emptyList();
8165        final int callingUid = Binder.getCallingUid();
8166        enforceCrossUserPermission(callingUid, userId,
8167                false /*requireFullPermission*/, false /*checkShell*/,
8168                "query intent receivers");
8169        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8170        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8171                false /*includeInstantApps*/);
8172        ComponentName comp = intent.getComponent();
8173        if (comp == null) {
8174            if (intent.getSelector() != null) {
8175                intent = intent.getSelector();
8176                comp = intent.getComponent();
8177            }
8178        }
8179        if (comp != null) {
8180            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8181            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8182            if (ai != null) {
8183                // When specifying an explicit component, we prevent the activity from being
8184                // used when either 1) the calling package is normal and the activity is within
8185                // an instant application or 2) the calling package is ephemeral and the
8186                // activity is not visible to instant applications.
8187                final boolean matchInstantApp =
8188                        (flags & PackageManager.MATCH_INSTANT) != 0;
8189                final boolean matchVisibleToInstantAppOnly =
8190                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8191                final boolean matchExplicitlyVisibleOnly =
8192                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8193                final boolean isCallerInstantApp =
8194                        instantAppPkgName != null;
8195                final boolean isTargetSameInstantApp =
8196                        comp.getPackageName().equals(instantAppPkgName);
8197                final boolean isTargetInstantApp =
8198                        (ai.applicationInfo.privateFlags
8199                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8200                final boolean isTargetVisibleToInstantApp =
8201                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8202                final boolean isTargetExplicitlyVisibleToInstantApp =
8203                        isTargetVisibleToInstantApp
8204                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8205                final boolean isTargetHiddenFromInstantApp =
8206                        !isTargetVisibleToInstantApp
8207                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8208                final boolean blockResolution =
8209                        !isTargetSameInstantApp
8210                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8211                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8212                                        && isTargetHiddenFromInstantApp));
8213                if (!blockResolution) {
8214                    ResolveInfo ri = new ResolveInfo();
8215                    ri.activityInfo = ai;
8216                    list.add(ri);
8217                }
8218            }
8219            return applyPostResolutionFilter(
8220                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8221        }
8222
8223        // reader
8224        synchronized (mPackages) {
8225            String pkgName = intent.getPackage();
8226            if (pkgName == null) {
8227                final List<ResolveInfo> result =
8228                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8229                return applyPostResolutionFilter(
8230                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8231            }
8232            final PackageParser.Package pkg = mPackages.get(pkgName);
8233            if (pkg != null) {
8234                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8235                        intent, resolvedType, flags, pkg.receivers, userId);
8236                return applyPostResolutionFilter(
8237                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8238            }
8239            return Collections.emptyList();
8240        }
8241    }
8242
8243    @Override
8244    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8245        final int callingUid = Binder.getCallingUid();
8246        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8247    }
8248
8249    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8250            int userId, int callingUid) {
8251        if (!sUserManager.exists(userId)) return null;
8252        flags = updateFlagsForResolve(
8253                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8254        List<ResolveInfo> query = queryIntentServicesInternal(
8255                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8256        if (query != null) {
8257            if (query.size() >= 1) {
8258                // If there is more than one service with the same priority,
8259                // just arbitrarily pick the first one.
8260                return query.get(0);
8261            }
8262        }
8263        return null;
8264    }
8265
8266    @Override
8267    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8268            String resolvedType, int flags, int userId) {
8269        final int callingUid = Binder.getCallingUid();
8270        return new ParceledListSlice<>(queryIntentServicesInternal(
8271                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8272    }
8273
8274    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8275            String resolvedType, int flags, int userId, int callingUid,
8276            boolean includeInstantApps) {
8277        if (!sUserManager.exists(userId)) return Collections.emptyList();
8278        enforceCrossUserPermission(callingUid, userId,
8279                false /*requireFullPermission*/, false /*checkShell*/,
8280                "query intent receivers");
8281        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8282        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8283        ComponentName comp = intent.getComponent();
8284        if (comp == null) {
8285            if (intent.getSelector() != null) {
8286                intent = intent.getSelector();
8287                comp = intent.getComponent();
8288            }
8289        }
8290        if (comp != null) {
8291            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8292            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8293            if (si != null) {
8294                // When specifying an explicit component, we prevent the service from being
8295                // used when either 1) the service is in an instant application and the
8296                // caller is not the same instant application or 2) the calling package is
8297                // ephemeral and the activity is not visible to ephemeral applications.
8298                final boolean matchInstantApp =
8299                        (flags & PackageManager.MATCH_INSTANT) != 0;
8300                final boolean matchVisibleToInstantAppOnly =
8301                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8302                final boolean isCallerInstantApp =
8303                        instantAppPkgName != null;
8304                final boolean isTargetSameInstantApp =
8305                        comp.getPackageName().equals(instantAppPkgName);
8306                final boolean isTargetInstantApp =
8307                        (si.applicationInfo.privateFlags
8308                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8309                final boolean isTargetHiddenFromInstantApp =
8310                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8311                final boolean blockResolution =
8312                        !isTargetSameInstantApp
8313                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8314                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8315                                        && isTargetHiddenFromInstantApp));
8316                if (!blockResolution) {
8317                    final ResolveInfo ri = new ResolveInfo();
8318                    ri.serviceInfo = si;
8319                    list.add(ri);
8320                }
8321            }
8322            return list;
8323        }
8324
8325        // reader
8326        synchronized (mPackages) {
8327            String pkgName = intent.getPackage();
8328            if (pkgName == null) {
8329                return applyPostServiceResolutionFilter(
8330                        mServices.queryIntent(intent, resolvedType, flags, userId),
8331                        instantAppPkgName);
8332            }
8333            final PackageParser.Package pkg = mPackages.get(pkgName);
8334            if (pkg != null) {
8335                return applyPostServiceResolutionFilter(
8336                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8337                                userId),
8338                        instantAppPkgName);
8339            }
8340            return Collections.emptyList();
8341        }
8342    }
8343
8344    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8345            String instantAppPkgName) {
8346        if (instantAppPkgName == null) {
8347            return resolveInfos;
8348        }
8349        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8350            final ResolveInfo info = resolveInfos.get(i);
8351            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8352            // allow services that are defined in the provided package
8353            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8354                if (info.serviceInfo.splitName != null
8355                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8356                                info.serviceInfo.splitName)) {
8357                    // requested service is defined in a split that hasn't been installed yet.
8358                    // add the installer to the resolve list
8359                    if (DEBUG_EPHEMERAL) {
8360                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8361                    }
8362                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8363                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8364                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8365                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8366                            null /*failureIntent*/);
8367                    // make sure this resolver is the default
8368                    installerInfo.isDefault = true;
8369                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8370                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8371                    // add a non-generic filter
8372                    installerInfo.filter = new IntentFilter();
8373                    // load resources from the correct package
8374                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8375                    resolveInfos.set(i, installerInfo);
8376                }
8377                continue;
8378            }
8379            // allow services that have been explicitly exposed to ephemeral apps
8380            if (!isEphemeralApp
8381                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8382                continue;
8383            }
8384            resolveInfos.remove(i);
8385        }
8386        return resolveInfos;
8387    }
8388
8389    @Override
8390    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8391            String resolvedType, int flags, int userId) {
8392        return new ParceledListSlice<>(
8393                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8394    }
8395
8396    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8397            Intent intent, String resolvedType, int flags, int userId) {
8398        if (!sUserManager.exists(userId)) return Collections.emptyList();
8399        final int callingUid = Binder.getCallingUid();
8400        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8401        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8402                false /*includeInstantApps*/);
8403        ComponentName comp = intent.getComponent();
8404        if (comp == null) {
8405            if (intent.getSelector() != null) {
8406                intent = intent.getSelector();
8407                comp = intent.getComponent();
8408            }
8409        }
8410        if (comp != null) {
8411            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8412            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8413            if (pi != null) {
8414                // When specifying an explicit component, we prevent the provider from being
8415                // used when either 1) the provider is in an instant application and the
8416                // caller is not the same instant application or 2) the calling package is an
8417                // instant application and the provider is not visible to instant applications.
8418                final boolean matchInstantApp =
8419                        (flags & PackageManager.MATCH_INSTANT) != 0;
8420                final boolean matchVisibleToInstantAppOnly =
8421                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8422                final boolean isCallerInstantApp =
8423                        instantAppPkgName != null;
8424                final boolean isTargetSameInstantApp =
8425                        comp.getPackageName().equals(instantAppPkgName);
8426                final boolean isTargetInstantApp =
8427                        (pi.applicationInfo.privateFlags
8428                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8429                final boolean isTargetHiddenFromInstantApp =
8430                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8431                final boolean blockResolution =
8432                        !isTargetSameInstantApp
8433                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8434                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8435                                        && isTargetHiddenFromInstantApp));
8436                if (!blockResolution) {
8437                    final ResolveInfo ri = new ResolveInfo();
8438                    ri.providerInfo = pi;
8439                    list.add(ri);
8440                }
8441            }
8442            return list;
8443        }
8444
8445        // reader
8446        synchronized (mPackages) {
8447            String pkgName = intent.getPackage();
8448            if (pkgName == null) {
8449                return applyPostContentProviderResolutionFilter(
8450                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8451                        instantAppPkgName);
8452            }
8453            final PackageParser.Package pkg = mPackages.get(pkgName);
8454            if (pkg != null) {
8455                return applyPostContentProviderResolutionFilter(
8456                        mProviders.queryIntentForPackage(
8457                        intent, resolvedType, flags, pkg.providers, userId),
8458                        instantAppPkgName);
8459            }
8460            return Collections.emptyList();
8461        }
8462    }
8463
8464    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8465            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8466        if (instantAppPkgName == null) {
8467            return resolveInfos;
8468        }
8469        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8470            final ResolveInfo info = resolveInfos.get(i);
8471            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8472            // allow providers that are defined in the provided package
8473            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8474                if (info.providerInfo.splitName != null
8475                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8476                                info.providerInfo.splitName)) {
8477                    // requested provider is defined in a split that hasn't been installed yet.
8478                    // add the installer to the resolve list
8479                    if (DEBUG_EPHEMERAL) {
8480                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8481                    }
8482                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8483                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8484                            info.providerInfo.packageName, info.providerInfo.splitName,
8485                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8486                            null /*failureIntent*/);
8487                    // make sure this resolver is the default
8488                    installerInfo.isDefault = true;
8489                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8490                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8491                    // add a non-generic filter
8492                    installerInfo.filter = new IntentFilter();
8493                    // load resources from the correct package
8494                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8495                    resolveInfos.set(i, installerInfo);
8496                }
8497                continue;
8498            }
8499            // allow providers that have been explicitly exposed to instant applications
8500            if (!isEphemeralApp
8501                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8502                continue;
8503            }
8504            resolveInfos.remove(i);
8505        }
8506        return resolveInfos;
8507    }
8508
8509    @Override
8510    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8511        final int callingUid = Binder.getCallingUid();
8512        if (getInstantAppPackageName(callingUid) != null) {
8513            return ParceledListSlice.emptyList();
8514        }
8515        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8516        flags = updateFlagsForPackage(flags, userId, null);
8517        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8518        enforceCrossUserPermission(callingUid, userId,
8519                true /* requireFullPermission */, false /* checkShell */,
8520                "get installed packages");
8521
8522        // writer
8523        synchronized (mPackages) {
8524            ArrayList<PackageInfo> list;
8525            if (listUninstalled) {
8526                list = new ArrayList<>(mSettings.mPackages.size());
8527                for (PackageSetting ps : mSettings.mPackages.values()) {
8528                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8529                        continue;
8530                    }
8531                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8532                        continue;
8533                    }
8534                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8535                    if (pi != null) {
8536                        list.add(pi);
8537                    }
8538                }
8539            } else {
8540                list = new ArrayList<>(mPackages.size());
8541                for (PackageParser.Package p : mPackages.values()) {
8542                    final PackageSetting ps = (PackageSetting) p.mExtras;
8543                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8544                        continue;
8545                    }
8546                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8547                        continue;
8548                    }
8549                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8550                            p.mExtras, flags, userId);
8551                    if (pi != null) {
8552                        list.add(pi);
8553                    }
8554                }
8555            }
8556
8557            return new ParceledListSlice<>(list);
8558        }
8559    }
8560
8561    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8562            String[] permissions, boolean[] tmp, int flags, int userId) {
8563        int numMatch = 0;
8564        final PermissionsState permissionsState = ps.getPermissionsState();
8565        for (int i=0; i<permissions.length; i++) {
8566            final String permission = permissions[i];
8567            if (permissionsState.hasPermission(permission, userId)) {
8568                tmp[i] = true;
8569                numMatch++;
8570            } else {
8571                tmp[i] = false;
8572            }
8573        }
8574        if (numMatch == 0) {
8575            return;
8576        }
8577        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8578
8579        // The above might return null in cases of uninstalled apps or install-state
8580        // skew across users/profiles.
8581        if (pi != null) {
8582            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8583                if (numMatch == permissions.length) {
8584                    pi.requestedPermissions = permissions;
8585                } else {
8586                    pi.requestedPermissions = new String[numMatch];
8587                    numMatch = 0;
8588                    for (int i=0; i<permissions.length; i++) {
8589                        if (tmp[i]) {
8590                            pi.requestedPermissions[numMatch] = permissions[i];
8591                            numMatch++;
8592                        }
8593                    }
8594                }
8595            }
8596            list.add(pi);
8597        }
8598    }
8599
8600    @Override
8601    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8602            String[] permissions, int flags, int userId) {
8603        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8604        flags = updateFlagsForPackage(flags, userId, permissions);
8605        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8606                true /* requireFullPermission */, false /* checkShell */,
8607                "get packages holding permissions");
8608        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8609
8610        // writer
8611        synchronized (mPackages) {
8612            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8613            boolean[] tmpBools = new boolean[permissions.length];
8614            if (listUninstalled) {
8615                for (PackageSetting ps : mSettings.mPackages.values()) {
8616                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8617                            userId);
8618                }
8619            } else {
8620                for (PackageParser.Package pkg : mPackages.values()) {
8621                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8622                    if (ps != null) {
8623                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8624                                userId);
8625                    }
8626                }
8627            }
8628
8629            return new ParceledListSlice<PackageInfo>(list);
8630        }
8631    }
8632
8633    @Override
8634    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8635        final int callingUid = Binder.getCallingUid();
8636        if (getInstantAppPackageName(callingUid) != null) {
8637            return ParceledListSlice.emptyList();
8638        }
8639        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8640        flags = updateFlagsForApplication(flags, userId, null);
8641        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8642
8643        // writer
8644        synchronized (mPackages) {
8645            ArrayList<ApplicationInfo> list;
8646            if (listUninstalled) {
8647                list = new ArrayList<>(mSettings.mPackages.size());
8648                for (PackageSetting ps : mSettings.mPackages.values()) {
8649                    ApplicationInfo ai;
8650                    int effectiveFlags = flags;
8651                    if (ps.isSystem()) {
8652                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8653                    }
8654                    if (ps.pkg != null) {
8655                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8656                            continue;
8657                        }
8658                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8659                            continue;
8660                        }
8661                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8662                                ps.readUserState(userId), userId);
8663                        if (ai != null) {
8664                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8665                        }
8666                    } else {
8667                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8668                        // and already converts to externally visible package name
8669                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8670                                callingUid, effectiveFlags, userId);
8671                    }
8672                    if (ai != null) {
8673                        list.add(ai);
8674                    }
8675                }
8676            } else {
8677                list = new ArrayList<>(mPackages.size());
8678                for (PackageParser.Package p : mPackages.values()) {
8679                    if (p.mExtras != null) {
8680                        PackageSetting ps = (PackageSetting) p.mExtras;
8681                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8682                            continue;
8683                        }
8684                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8685                            continue;
8686                        }
8687                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8688                                ps.readUserState(userId), userId);
8689                        if (ai != null) {
8690                            ai.packageName = resolveExternalPackageNameLPr(p);
8691                            list.add(ai);
8692                        }
8693                    }
8694                }
8695            }
8696
8697            return new ParceledListSlice<>(list);
8698        }
8699    }
8700
8701    @Override
8702    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8703        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8704            return null;
8705        }
8706        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8707            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8708                    "getEphemeralApplications");
8709        }
8710        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8711                true /* requireFullPermission */, false /* checkShell */,
8712                "getEphemeralApplications");
8713        synchronized (mPackages) {
8714            List<InstantAppInfo> instantApps = mInstantAppRegistry
8715                    .getInstantAppsLPr(userId);
8716            if (instantApps != null) {
8717                return new ParceledListSlice<>(instantApps);
8718            }
8719        }
8720        return null;
8721    }
8722
8723    @Override
8724    public boolean isInstantApp(String packageName, int userId) {
8725        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8726                true /* requireFullPermission */, false /* checkShell */,
8727                "isInstantApp");
8728        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8729            return false;
8730        }
8731
8732        synchronized (mPackages) {
8733            int callingUid = Binder.getCallingUid();
8734            if (Process.isIsolated(callingUid)) {
8735                callingUid = mIsolatedOwners.get(callingUid);
8736            }
8737            final PackageSetting ps = mSettings.mPackages.get(packageName);
8738            PackageParser.Package pkg = mPackages.get(packageName);
8739            final boolean returnAllowed =
8740                    ps != null
8741                    && (isCallerSameApp(packageName, callingUid)
8742                            || canViewInstantApps(callingUid, userId)
8743                            || mInstantAppRegistry.isInstantAccessGranted(
8744                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8745            if (returnAllowed) {
8746                return ps.getInstantApp(userId);
8747            }
8748        }
8749        return false;
8750    }
8751
8752    @Override
8753    public byte[] getInstantAppCookie(String packageName, int userId) {
8754        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8755            return null;
8756        }
8757
8758        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8759                true /* requireFullPermission */, false /* checkShell */,
8760                "getInstantAppCookie");
8761        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8762            return null;
8763        }
8764        synchronized (mPackages) {
8765            return mInstantAppRegistry.getInstantAppCookieLPw(
8766                    packageName, userId);
8767        }
8768    }
8769
8770    @Override
8771    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8772        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8773            return true;
8774        }
8775
8776        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8777                true /* requireFullPermission */, true /* checkShell */,
8778                "setInstantAppCookie");
8779        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8780            return false;
8781        }
8782        synchronized (mPackages) {
8783            return mInstantAppRegistry.setInstantAppCookieLPw(
8784                    packageName, cookie, userId);
8785        }
8786    }
8787
8788    @Override
8789    public Bitmap getInstantAppIcon(String packageName, int userId) {
8790        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8791            return null;
8792        }
8793
8794        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8795            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8796                    "getInstantAppIcon");
8797        }
8798        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8799                true /* requireFullPermission */, false /* checkShell */,
8800                "getInstantAppIcon");
8801
8802        synchronized (mPackages) {
8803            return mInstantAppRegistry.getInstantAppIconLPw(
8804                    packageName, userId);
8805        }
8806    }
8807
8808    private boolean isCallerSameApp(String packageName, int uid) {
8809        PackageParser.Package pkg = mPackages.get(packageName);
8810        return pkg != null
8811                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8812    }
8813
8814    @Override
8815    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8816        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8817            return ParceledListSlice.emptyList();
8818        }
8819        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8820    }
8821
8822    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8823        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8824
8825        // reader
8826        synchronized (mPackages) {
8827            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8828            final int userId = UserHandle.getCallingUserId();
8829            while (i.hasNext()) {
8830                final PackageParser.Package p = i.next();
8831                if (p.applicationInfo == null) continue;
8832
8833                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8834                        && !p.applicationInfo.isDirectBootAware();
8835                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8836                        && p.applicationInfo.isDirectBootAware();
8837
8838                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8839                        && (!mSafeMode || isSystemApp(p))
8840                        && (matchesUnaware || matchesAware)) {
8841                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8842                    if (ps != null) {
8843                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8844                                ps.readUserState(userId), userId);
8845                        if (ai != null) {
8846                            finalList.add(ai);
8847                        }
8848                    }
8849                }
8850            }
8851        }
8852
8853        return finalList;
8854    }
8855
8856    @Override
8857    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8858        if (!sUserManager.exists(userId)) return null;
8859        flags = updateFlagsForComponent(flags, userId, name);
8860        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8861        // reader
8862        synchronized (mPackages) {
8863            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8864            PackageSetting ps = provider != null
8865                    ? mSettings.mPackages.get(provider.owner.packageName)
8866                    : null;
8867            if (ps != null) {
8868                final boolean isInstantApp = ps.getInstantApp(userId);
8869                // normal application; filter out instant application provider
8870                if (instantAppPkgName == null && isInstantApp) {
8871                    return null;
8872                }
8873                // instant application; filter out other instant applications
8874                if (instantAppPkgName != null
8875                        && isInstantApp
8876                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8877                    return null;
8878                }
8879                // instant application; filter out non-exposed provider
8880                if (instantAppPkgName != null
8881                        && !isInstantApp
8882                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8883                    return null;
8884                }
8885                // provider not enabled
8886                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8887                    return null;
8888                }
8889                return PackageParser.generateProviderInfo(
8890                        provider, flags, ps.readUserState(userId), userId);
8891            }
8892            return null;
8893        }
8894    }
8895
8896    /**
8897     * @deprecated
8898     */
8899    @Deprecated
8900    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8901        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8902            return;
8903        }
8904        // reader
8905        synchronized (mPackages) {
8906            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8907                    .entrySet().iterator();
8908            final int userId = UserHandle.getCallingUserId();
8909            while (i.hasNext()) {
8910                Map.Entry<String, PackageParser.Provider> entry = i.next();
8911                PackageParser.Provider p = entry.getValue();
8912                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8913
8914                if (ps != null && p.syncable
8915                        && (!mSafeMode || (p.info.applicationInfo.flags
8916                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8917                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8918                            ps.readUserState(userId), userId);
8919                    if (info != null) {
8920                        outNames.add(entry.getKey());
8921                        outInfo.add(info);
8922                    }
8923                }
8924            }
8925        }
8926    }
8927
8928    @Override
8929    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8930            int uid, int flags, String metaDataKey) {
8931        final int callingUid = Binder.getCallingUid();
8932        final int userId = processName != null ? UserHandle.getUserId(uid)
8933                : UserHandle.getCallingUserId();
8934        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8935        flags = updateFlagsForComponent(flags, userId, processName);
8936        ArrayList<ProviderInfo> finalList = null;
8937        // reader
8938        synchronized (mPackages) {
8939            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8940            while (i.hasNext()) {
8941                final PackageParser.Provider p = i.next();
8942                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8943                if (ps != null && p.info.authority != null
8944                        && (processName == null
8945                                || (p.info.processName.equals(processName)
8946                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8947                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8948
8949                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8950                    // parameter.
8951                    if (metaDataKey != null
8952                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8953                        continue;
8954                    }
8955                    final ComponentName component =
8956                            new ComponentName(p.info.packageName, p.info.name);
8957                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8958                        continue;
8959                    }
8960                    if (finalList == null) {
8961                        finalList = new ArrayList<ProviderInfo>(3);
8962                    }
8963                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8964                            ps.readUserState(userId), userId);
8965                    if (info != null) {
8966                        finalList.add(info);
8967                    }
8968                }
8969            }
8970        }
8971
8972        if (finalList != null) {
8973            Collections.sort(finalList, mProviderInitOrderSorter);
8974            return new ParceledListSlice<ProviderInfo>(finalList);
8975        }
8976
8977        return ParceledListSlice.emptyList();
8978    }
8979
8980    @Override
8981    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8982        // reader
8983        synchronized (mPackages) {
8984            final int callingUid = Binder.getCallingUid();
8985            final int callingUserId = UserHandle.getUserId(callingUid);
8986            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8987            if (ps == null) return null;
8988            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8989                return null;
8990            }
8991            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8992            return PackageParser.generateInstrumentationInfo(i, flags);
8993        }
8994    }
8995
8996    @Override
8997    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8998            String targetPackage, int flags) {
8999        final int callingUid = Binder.getCallingUid();
9000        final int callingUserId = UserHandle.getUserId(callingUid);
9001        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
9002        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
9003            return ParceledListSlice.emptyList();
9004        }
9005        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
9006    }
9007
9008    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9009            int flags) {
9010        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9011
9012        // reader
9013        synchronized (mPackages) {
9014            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9015            while (i.hasNext()) {
9016                final PackageParser.Instrumentation p = i.next();
9017                if (targetPackage == null
9018                        || targetPackage.equals(p.info.targetPackage)) {
9019                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9020                            flags);
9021                    if (ii != null) {
9022                        finalList.add(ii);
9023                    }
9024                }
9025            }
9026        }
9027
9028        return finalList;
9029    }
9030
9031    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9032        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9033        try {
9034            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9035        } finally {
9036            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9037        }
9038    }
9039
9040    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9041        final File[] files = dir.listFiles();
9042        if (ArrayUtils.isEmpty(files)) {
9043            Log.d(TAG, "No files in app dir " + dir);
9044            return;
9045        }
9046
9047        if (DEBUG_PACKAGE_SCANNING) {
9048            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9049                    + " flags=0x" + Integer.toHexString(parseFlags));
9050        }
9051        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9052                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9053                mParallelPackageParserCallback);
9054
9055        // Submit files for parsing in parallel
9056        int fileCount = 0;
9057        for (File file : files) {
9058            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9059                    && !PackageInstallerService.isStageName(file.getName());
9060            if (!isPackage) {
9061                // Ignore entries which are not packages
9062                continue;
9063            }
9064            parallelPackageParser.submit(file, parseFlags);
9065            fileCount++;
9066        }
9067
9068        // Process results one by one
9069        for (; fileCount > 0; fileCount--) {
9070            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9071            Throwable throwable = parseResult.throwable;
9072            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9073
9074            if (throwable == null) {
9075                // Static shared libraries have synthetic package names
9076                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9077                    renameStaticSharedLibraryPackage(parseResult.pkg);
9078                }
9079                try {
9080                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9081                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9082                                currentTime, null);
9083                    }
9084                } catch (PackageManagerException e) {
9085                    errorCode = e.error;
9086                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9087                }
9088            } else if (throwable instanceof PackageParser.PackageParserException) {
9089                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9090                        throwable;
9091                errorCode = e.error;
9092                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9093            } else {
9094                throw new IllegalStateException("Unexpected exception occurred while parsing "
9095                        + parseResult.scanFile, throwable);
9096            }
9097
9098            // Delete invalid userdata apps
9099            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9100                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9101                logCriticalInfo(Log.WARN,
9102                        "Deleting invalid package at " + parseResult.scanFile);
9103                removeCodePathLI(parseResult.scanFile);
9104            }
9105        }
9106        parallelPackageParser.close();
9107    }
9108
9109    private static File getSettingsProblemFile() {
9110        File dataDir = Environment.getDataDirectory();
9111        File systemDir = new File(dataDir, "system");
9112        File fname = new File(systemDir, "uiderrors.txt");
9113        return fname;
9114    }
9115
9116    static void reportSettingsProblem(int priority, String msg) {
9117        logCriticalInfo(priority, msg);
9118    }
9119
9120    public static void logCriticalInfo(int priority, String msg) {
9121        Slog.println(priority, TAG, msg);
9122        EventLogTags.writePmCriticalInfo(msg);
9123        try {
9124            File fname = getSettingsProblemFile();
9125            FileOutputStream out = new FileOutputStream(fname, true);
9126            PrintWriter pw = new FastPrintWriter(out);
9127            SimpleDateFormat formatter = new SimpleDateFormat();
9128            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9129            pw.println(dateString + ": " + msg);
9130            pw.close();
9131            FileUtils.setPermissions(
9132                    fname.toString(),
9133                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9134                    -1, -1);
9135        } catch (java.io.IOException e) {
9136        }
9137    }
9138
9139    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9140        if (srcFile.isDirectory()) {
9141            final File baseFile = new File(pkg.baseCodePath);
9142            long maxModifiedTime = baseFile.lastModified();
9143            if (pkg.splitCodePaths != null) {
9144                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9145                    final File splitFile = new File(pkg.splitCodePaths[i]);
9146                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9147                }
9148            }
9149            return maxModifiedTime;
9150        }
9151        return srcFile.lastModified();
9152    }
9153
9154    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9155            final int policyFlags) throws PackageManagerException {
9156        // When upgrading from pre-N MR1, verify the package time stamp using the package
9157        // directory and not the APK file.
9158        final long lastModifiedTime = mIsPreNMR1Upgrade
9159                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9160        if (ps != null
9161                && ps.codePath.equals(srcFile)
9162                && ps.timeStamp == lastModifiedTime
9163                && !isCompatSignatureUpdateNeeded(pkg)
9164                && !isRecoverSignatureUpdateNeeded(pkg)) {
9165            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9166            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9167            ArraySet<PublicKey> signingKs;
9168            synchronized (mPackages) {
9169                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9170            }
9171            if (ps.signatures.mSignatures != null
9172                    && ps.signatures.mSignatures.length != 0
9173                    && signingKs != null) {
9174                // Optimization: reuse the existing cached certificates
9175                // if the package appears to be unchanged.
9176                pkg.mSignatures = ps.signatures.mSignatures;
9177                pkg.mSigningKeys = signingKs;
9178                return;
9179            }
9180
9181            Slog.w(TAG, "PackageSetting for " + ps.name
9182                    + " is missing signatures.  Collecting certs again to recover them.");
9183        } else {
9184            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9185        }
9186
9187        try {
9188            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9189            PackageParser.collectCertificates(pkg, policyFlags);
9190        } catch (PackageParserException e) {
9191            throw PackageManagerException.from(e);
9192        } finally {
9193            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9194        }
9195    }
9196
9197    /**
9198     *  Traces a package scan.
9199     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9200     */
9201    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9202            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9203        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9204        try {
9205            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9206        } finally {
9207            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9208        }
9209    }
9210
9211    /**
9212     *  Scans a package and returns the newly parsed package.
9213     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9214     */
9215    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9216            long currentTime, UserHandle user) throws PackageManagerException {
9217        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9218        PackageParser pp = new PackageParser();
9219        pp.setSeparateProcesses(mSeparateProcesses);
9220        pp.setOnlyCoreApps(mOnlyCore);
9221        pp.setDisplayMetrics(mMetrics);
9222        pp.setCallback(mPackageParserCallback);
9223
9224        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9225            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9226        }
9227
9228        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9229        final PackageParser.Package pkg;
9230        try {
9231            pkg = pp.parsePackage(scanFile, parseFlags);
9232        } catch (PackageParserException e) {
9233            throw PackageManagerException.from(e);
9234        } finally {
9235            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9236        }
9237
9238        // Static shared libraries have synthetic package names
9239        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9240            renameStaticSharedLibraryPackage(pkg);
9241        }
9242
9243        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9244    }
9245
9246    /**
9247     *  Scans a package and returns the newly parsed package.
9248     *  @throws PackageManagerException on a parse error.
9249     */
9250    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9251            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9252            throws PackageManagerException {
9253        // If the package has children and this is the first dive in the function
9254        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9255        // packages (parent and children) would be successfully scanned before the
9256        // actual scan since scanning mutates internal state and we want to atomically
9257        // install the package and its children.
9258        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9259            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9260                scanFlags |= SCAN_CHECK_ONLY;
9261            }
9262        } else {
9263            scanFlags &= ~SCAN_CHECK_ONLY;
9264        }
9265
9266        // Scan the parent
9267        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9268                scanFlags, currentTime, user);
9269
9270        // Scan the children
9271        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9272        for (int i = 0; i < childCount; i++) {
9273            PackageParser.Package childPackage = pkg.childPackages.get(i);
9274            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9275                    currentTime, user);
9276        }
9277
9278
9279        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9280            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9281        }
9282
9283        return scannedPkg;
9284    }
9285
9286    /**
9287     *  Scans a package and returns the newly parsed package.
9288     *  @throws PackageManagerException on a parse error.
9289     */
9290    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9291            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9292            throws PackageManagerException {
9293        PackageSetting ps = null;
9294        PackageSetting updatedPkg;
9295        // reader
9296        synchronized (mPackages) {
9297            // Look to see if we already know about this package.
9298            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9299            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9300                // This package has been renamed to its original name.  Let's
9301                // use that.
9302                ps = mSettings.getPackageLPr(oldName);
9303            }
9304            // If there was no original package, see one for the real package name.
9305            if (ps == null) {
9306                ps = mSettings.getPackageLPr(pkg.packageName);
9307            }
9308            // Check to see if this package could be hiding/updating a system
9309            // package.  Must look for it either under the original or real
9310            // package name depending on our state.
9311            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9312            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9313
9314            // If this is a package we don't know about on the system partition, we
9315            // may need to remove disabled child packages on the system partition
9316            // or may need to not add child packages if the parent apk is updated
9317            // on the data partition and no longer defines this child package.
9318            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9319                // If this is a parent package for an updated system app and this system
9320                // app got an OTA update which no longer defines some of the child packages
9321                // we have to prune them from the disabled system packages.
9322                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9323                if (disabledPs != null) {
9324                    final int scannedChildCount = (pkg.childPackages != null)
9325                            ? pkg.childPackages.size() : 0;
9326                    final int disabledChildCount = disabledPs.childPackageNames != null
9327                            ? disabledPs.childPackageNames.size() : 0;
9328                    for (int i = 0; i < disabledChildCount; i++) {
9329                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9330                        boolean disabledPackageAvailable = false;
9331                        for (int j = 0; j < scannedChildCount; j++) {
9332                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9333                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9334                                disabledPackageAvailable = true;
9335                                break;
9336                            }
9337                         }
9338                         if (!disabledPackageAvailable) {
9339                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9340                         }
9341                    }
9342                }
9343            }
9344        }
9345
9346        final boolean isUpdatedPkg = updatedPkg != null;
9347        final boolean isUpdatedSystemPkg = isUpdatedPkg
9348                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9349        boolean isUpdatedPkgBetter = false;
9350        // First check if this is a system package that may involve an update
9351        if (isUpdatedSystemPkg) {
9352            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9353            // it needs to drop FLAG_PRIVILEGED.
9354            if (locationIsPrivileged(scanFile)) {
9355                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9356            } else {
9357                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9358            }
9359
9360            if (ps != null && !ps.codePath.equals(scanFile)) {
9361                // The path has changed from what was last scanned...  check the
9362                // version of the new path against what we have stored to determine
9363                // what to do.
9364                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9365                if (pkg.mVersionCode <= ps.versionCode) {
9366                    // The system package has been updated and the code path does not match
9367                    // Ignore entry. Skip it.
9368                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9369                            + " ignored: updated version " + ps.versionCode
9370                            + " better than this " + pkg.mVersionCode);
9371                    if (!updatedPkg.codePath.equals(scanFile)) {
9372                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9373                                + ps.name + " changing from " + updatedPkg.codePathString
9374                                + " to " + scanFile);
9375                        updatedPkg.codePath = scanFile;
9376                        updatedPkg.codePathString = scanFile.toString();
9377                        updatedPkg.resourcePath = scanFile;
9378                        updatedPkg.resourcePathString = scanFile.toString();
9379                    }
9380                    updatedPkg.pkg = pkg;
9381                    updatedPkg.versionCode = pkg.mVersionCode;
9382
9383                    // Update the disabled system child packages to point to the package too.
9384                    final int childCount = updatedPkg.childPackageNames != null
9385                            ? updatedPkg.childPackageNames.size() : 0;
9386                    for (int i = 0; i < childCount; i++) {
9387                        String childPackageName = updatedPkg.childPackageNames.get(i);
9388                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9389                                childPackageName);
9390                        if (updatedChildPkg != null) {
9391                            updatedChildPkg.pkg = pkg;
9392                            updatedChildPkg.versionCode = pkg.mVersionCode;
9393                        }
9394                    }
9395                } else {
9396                    // The current app on the system partition is better than
9397                    // what we have updated to on the data partition; switch
9398                    // back to the system partition version.
9399                    // At this point, its safely assumed that package installation for
9400                    // apps in system partition will go through. If not there won't be a working
9401                    // version of the app
9402                    // writer
9403                    synchronized (mPackages) {
9404                        // Just remove the loaded entries from package lists.
9405                        mPackages.remove(ps.name);
9406                    }
9407
9408                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9409                            + " reverting from " + ps.codePathString
9410                            + ": new version " + pkg.mVersionCode
9411                            + " better than installed " + ps.versionCode);
9412
9413                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9414                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9415                    synchronized (mInstallLock) {
9416                        args.cleanUpResourcesLI();
9417                    }
9418                    synchronized (mPackages) {
9419                        mSettings.enableSystemPackageLPw(ps.name);
9420                    }
9421                    isUpdatedPkgBetter = true;
9422                }
9423            }
9424        }
9425
9426        String resourcePath = null;
9427        String baseResourcePath = null;
9428        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9429            if (ps != null && ps.resourcePathString != null) {
9430                resourcePath = ps.resourcePathString;
9431                baseResourcePath = ps.resourcePathString;
9432            } else {
9433                // Should not happen at all. Just log an error.
9434                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9435            }
9436        } else {
9437            resourcePath = pkg.codePath;
9438            baseResourcePath = pkg.baseCodePath;
9439        }
9440
9441        // Set application objects path explicitly.
9442        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9443        pkg.setApplicationInfoCodePath(pkg.codePath);
9444        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9445        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9446        pkg.setApplicationInfoResourcePath(resourcePath);
9447        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9448        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9449
9450        // throw an exception if we have an update to a system application, but, it's not more
9451        // recent than the package we've already scanned
9452        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9453            // Set CPU Abis to application info.
9454            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9455                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9456                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9457            } else {
9458                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9459                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9460            }
9461
9462            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9463                    + scanFile + " ignored: updated version " + ps.versionCode
9464                    + " better than this " + pkg.mVersionCode);
9465        }
9466
9467        if (isUpdatedPkg) {
9468            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9469            // initially
9470            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9471
9472            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9473            // flag set initially
9474            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9475                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9476            }
9477        }
9478
9479        // Verify certificates against what was last scanned
9480        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9481
9482        /*
9483         * A new system app appeared, but we already had a non-system one of the
9484         * same name installed earlier.
9485         */
9486        boolean shouldHideSystemApp = false;
9487        if (!isUpdatedPkg && ps != null
9488                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9489            /*
9490             * Check to make sure the signatures match first. If they don't,
9491             * wipe the installed application and its data.
9492             */
9493            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9494                    != PackageManager.SIGNATURE_MATCH) {
9495                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9496                        + " signatures don't match existing userdata copy; removing");
9497                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9498                        "scanPackageInternalLI")) {
9499                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9500                }
9501                ps = null;
9502            } else {
9503                /*
9504                 * If the newly-added system app is an older version than the
9505                 * already installed version, hide it. It will be scanned later
9506                 * and re-added like an update.
9507                 */
9508                if (pkg.mVersionCode <= ps.versionCode) {
9509                    shouldHideSystemApp = true;
9510                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9511                            + " but new version " + pkg.mVersionCode + " better than installed "
9512                            + ps.versionCode + "; hiding system");
9513                } else {
9514                    /*
9515                     * The newly found system app is a newer version that the
9516                     * one previously installed. Simply remove the
9517                     * already-installed application and replace it with our own
9518                     * while keeping the application data.
9519                     */
9520                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9521                            + " reverting from " + ps.codePathString + ": new version "
9522                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9523                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9524                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9525                    synchronized (mInstallLock) {
9526                        args.cleanUpResourcesLI();
9527                    }
9528                }
9529            }
9530        }
9531
9532        // The apk is forward locked (not public) if its code and resources
9533        // are kept in different files. (except for app in either system or
9534        // vendor path).
9535        // TODO grab this value from PackageSettings
9536        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9537            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9538                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9539            }
9540        }
9541
9542        final int userId = ((user == null) ? 0 : user.getIdentifier());
9543        if (ps != null && ps.getInstantApp(userId)) {
9544            scanFlags |= SCAN_AS_INSTANT_APP;
9545        }
9546        if (ps != null && ps.getVirtulalPreload(userId)) {
9547            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9548        }
9549
9550        // Note that we invoke the following method only if we are about to unpack an application
9551        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9552                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9553
9554        /*
9555         * If the system app should be overridden by a previously installed
9556         * data, hide the system app now and let the /data/app scan pick it up
9557         * again.
9558         */
9559        if (shouldHideSystemApp) {
9560            synchronized (mPackages) {
9561                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9562            }
9563        }
9564
9565        return scannedPkg;
9566    }
9567
9568    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9569        // Derive the new package synthetic package name
9570        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9571                + pkg.staticSharedLibVersion);
9572    }
9573
9574    private static String fixProcessName(String defProcessName,
9575            String processName) {
9576        if (processName == null) {
9577            return defProcessName;
9578        }
9579        return processName;
9580    }
9581
9582    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9583            throws PackageManagerException {
9584        if (pkgSetting.signatures.mSignatures != null) {
9585            // Already existing package. Make sure signatures match
9586            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9587                    == PackageManager.SIGNATURE_MATCH;
9588            if (!match) {
9589                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9590                        == PackageManager.SIGNATURE_MATCH;
9591            }
9592            if (!match) {
9593                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9594                        == PackageManager.SIGNATURE_MATCH;
9595            }
9596            if (!match) {
9597                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9598                        + pkg.packageName + " signatures do not match the "
9599                        + "previously installed version; ignoring!");
9600            }
9601        }
9602
9603        // Check for shared user signatures
9604        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9605            // Already existing package. Make sure signatures match
9606            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9607                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9608            if (!match) {
9609                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9610                        == PackageManager.SIGNATURE_MATCH;
9611            }
9612            if (!match) {
9613                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9614                        == PackageManager.SIGNATURE_MATCH;
9615            }
9616            if (!match) {
9617                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9618                        "Package " + pkg.packageName
9619                        + " has no signatures that match those in shared user "
9620                        + pkgSetting.sharedUser.name + "; ignoring!");
9621            }
9622        }
9623    }
9624
9625    /**
9626     * Enforces that only the system UID or root's UID can call a method exposed
9627     * via Binder.
9628     *
9629     * @param message used as message if SecurityException is thrown
9630     * @throws SecurityException if the caller is not system or root
9631     */
9632    private static final void enforceSystemOrRoot(String message) {
9633        final int uid = Binder.getCallingUid();
9634        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9635            throw new SecurityException(message);
9636        }
9637    }
9638
9639    @Override
9640    public void performFstrimIfNeeded() {
9641        enforceSystemOrRoot("Only the system can request fstrim");
9642
9643        // Before everything else, see whether we need to fstrim.
9644        try {
9645            IStorageManager sm = PackageHelper.getStorageManager();
9646            if (sm != null) {
9647                boolean doTrim = false;
9648                final long interval = android.provider.Settings.Global.getLong(
9649                        mContext.getContentResolver(),
9650                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9651                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9652                if (interval > 0) {
9653                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9654                    if (timeSinceLast > interval) {
9655                        doTrim = true;
9656                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9657                                + "; running immediately");
9658                    }
9659                }
9660                if (doTrim) {
9661                    final boolean dexOptDialogShown;
9662                    synchronized (mPackages) {
9663                        dexOptDialogShown = mDexOptDialogShown;
9664                    }
9665                    if (!isFirstBoot() && dexOptDialogShown) {
9666                        try {
9667                            ActivityManager.getService().showBootMessage(
9668                                    mContext.getResources().getString(
9669                                            R.string.android_upgrading_fstrim), true);
9670                        } catch (RemoteException e) {
9671                        }
9672                    }
9673                    sm.runMaintenance();
9674                }
9675            } else {
9676                Slog.e(TAG, "storageManager service unavailable!");
9677            }
9678        } catch (RemoteException e) {
9679            // Can't happen; StorageManagerService is local
9680        }
9681    }
9682
9683    @Override
9684    public void updatePackagesIfNeeded() {
9685        enforceSystemOrRoot("Only the system can request package update");
9686
9687        // We need to re-extract after an OTA.
9688        boolean causeUpgrade = isUpgrade();
9689
9690        // First boot or factory reset.
9691        // Note: we also handle devices that are upgrading to N right now as if it is their
9692        //       first boot, as they do not have profile data.
9693        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9694
9695        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9696        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9697
9698        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9699            return;
9700        }
9701
9702        List<PackageParser.Package> pkgs;
9703        synchronized (mPackages) {
9704            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9705        }
9706
9707        final long startTime = System.nanoTime();
9708        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9709                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9710                    false /* bootComplete */);
9711
9712        final int elapsedTimeSeconds =
9713                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9714
9715        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9716        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9717        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9718        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9719        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9720    }
9721
9722    /*
9723     * Return the prebuilt profile path given a package base code path.
9724     */
9725    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9726        return pkg.baseCodePath + ".prof";
9727    }
9728
9729    /**
9730     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9731     * containing statistics about the invocation. The array consists of three elements,
9732     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9733     * and {@code numberOfPackagesFailed}.
9734     */
9735    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9736            final String compilerFilter, boolean bootComplete) {
9737
9738        int numberOfPackagesVisited = 0;
9739        int numberOfPackagesOptimized = 0;
9740        int numberOfPackagesSkipped = 0;
9741        int numberOfPackagesFailed = 0;
9742        final int numberOfPackagesToDexopt = pkgs.size();
9743
9744        for (PackageParser.Package pkg : pkgs) {
9745            numberOfPackagesVisited++;
9746
9747            boolean useProfileForDexopt = false;
9748
9749            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9750                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9751                // that are already compiled.
9752                File profileFile = new File(getPrebuildProfilePath(pkg));
9753                // Copy profile if it exists.
9754                if (profileFile.exists()) {
9755                    try {
9756                        // We could also do this lazily before calling dexopt in
9757                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9758                        // is that we don't have a good way to say "do this only once".
9759                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9760                                pkg.applicationInfo.uid, pkg.packageName)) {
9761                            Log.e(TAG, "Installer failed to copy system profile!");
9762                        } else {
9763                            // Disabled as this causes speed-profile compilation during first boot
9764                            // even if things are already compiled.
9765                            // useProfileForDexopt = true;
9766                        }
9767                    } catch (Exception e) {
9768                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9769                                e);
9770                    }
9771                } else {
9772                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9773                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9774                    // minimize the number off apps being speed-profile compiled during first boot.
9775                    // The other paths will not change the filter.
9776                    if (disabledPs != null && disabledPs.pkg.isStub) {
9777                        // The package is the stub one, remove the stub suffix to get the normal
9778                        // package and APK names.
9779                        String systemProfilePath =
9780                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9781                        profileFile = new File(systemProfilePath);
9782                        // If we have a profile for a compressed APK, copy it to the reference
9783                        // location.
9784                        // Note that copying the profile here will cause it to override the
9785                        // reference profile every OTA even though the existing reference profile
9786                        // may have more data. We can't copy during decompression since the
9787                        // directories are not set up at that point.
9788                        if (profileFile.exists()) {
9789                            try {
9790                                // We could also do this lazily before calling dexopt in
9791                                // PackageDexOptimizer to prevent this happening on first boot. The
9792                                // issue is that we don't have a good way to say "do this only
9793                                // once".
9794                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9795                                        pkg.applicationInfo.uid, pkg.packageName)) {
9796                                    Log.e(TAG, "Failed to copy system profile for stub package!");
9797                                } else {
9798                                    useProfileForDexopt = true;
9799                                }
9800                            } catch (Exception e) {
9801                                Log.e(TAG, "Failed to copy profile " +
9802                                        profileFile.getAbsolutePath() + " ", e);
9803                            }
9804                        }
9805                    }
9806                }
9807            }
9808
9809            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9810                if (DEBUG_DEXOPT) {
9811                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9812                }
9813                numberOfPackagesSkipped++;
9814                continue;
9815            }
9816
9817            if (DEBUG_DEXOPT) {
9818                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9819                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9820            }
9821
9822            if (showDialog) {
9823                try {
9824                    ActivityManager.getService().showBootMessage(
9825                            mContext.getResources().getString(R.string.android_upgrading_apk,
9826                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9827                } catch (RemoteException e) {
9828                }
9829                synchronized (mPackages) {
9830                    mDexOptDialogShown = true;
9831                }
9832            }
9833
9834            String pkgCompilerFilter = compilerFilter;
9835            if (useProfileForDexopt) {
9836                // Use background dexopt mode to try and use the profile. Note that this does not
9837                // guarantee usage of the profile.
9838                pkgCompilerFilter =
9839                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9840                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9841            }
9842
9843            // checkProfiles is false to avoid merging profiles during boot which
9844            // might interfere with background compilation (b/28612421).
9845            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9846            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9847            // trade-off worth doing to save boot time work.
9848            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9849            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9850                    pkg.packageName,
9851                    pkgCompilerFilter,
9852                    dexoptFlags));
9853
9854            switch (primaryDexOptStaus) {
9855                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9856                    numberOfPackagesOptimized++;
9857                    break;
9858                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9859                    numberOfPackagesSkipped++;
9860                    break;
9861                case PackageDexOptimizer.DEX_OPT_FAILED:
9862                    numberOfPackagesFailed++;
9863                    break;
9864                default:
9865                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9866                    break;
9867            }
9868        }
9869
9870        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9871                numberOfPackagesFailed };
9872    }
9873
9874    @Override
9875    public void notifyPackageUse(String packageName, int reason) {
9876        synchronized (mPackages) {
9877            final int callingUid = Binder.getCallingUid();
9878            final int callingUserId = UserHandle.getUserId(callingUid);
9879            if (getInstantAppPackageName(callingUid) != null) {
9880                if (!isCallerSameApp(packageName, callingUid)) {
9881                    return;
9882                }
9883            } else {
9884                if (isInstantApp(packageName, callingUserId)) {
9885                    return;
9886                }
9887            }
9888            notifyPackageUseLocked(packageName, reason);
9889        }
9890    }
9891
9892    private void notifyPackageUseLocked(String packageName, int reason) {
9893        final PackageParser.Package p = mPackages.get(packageName);
9894        if (p == null) {
9895            return;
9896        }
9897        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9898    }
9899
9900    @Override
9901    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9902            List<String> classPaths, String loaderIsa) {
9903        int userId = UserHandle.getCallingUserId();
9904        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9905        if (ai == null) {
9906            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9907                + loadingPackageName + ", user=" + userId);
9908            return;
9909        }
9910        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9911    }
9912
9913    @Override
9914    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9915            IDexModuleRegisterCallback callback) {
9916        int userId = UserHandle.getCallingUserId();
9917        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9918        DexManager.RegisterDexModuleResult result;
9919        if (ai == null) {
9920            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9921                     " calling user. package=" + packageName + ", user=" + userId);
9922            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9923        } else {
9924            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9925        }
9926
9927        if (callback != null) {
9928            mHandler.post(() -> {
9929                try {
9930                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9931                } catch (RemoteException e) {
9932                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9933                }
9934            });
9935        }
9936    }
9937
9938    /**
9939     * Ask the package manager to perform a dex-opt with the given compiler filter.
9940     *
9941     * Note: exposed only for the shell command to allow moving packages explicitly to a
9942     *       definite state.
9943     */
9944    @Override
9945    public boolean performDexOptMode(String packageName,
9946            boolean checkProfiles, String targetCompilerFilter, boolean force,
9947            boolean bootComplete, String splitName) {
9948        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9949                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9950                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9951        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9952                splitName, flags));
9953    }
9954
9955    /**
9956     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9957     * secondary dex files belonging to the given package.
9958     *
9959     * Note: exposed only for the shell command to allow moving packages explicitly to a
9960     *       definite state.
9961     */
9962    @Override
9963    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9964            boolean force) {
9965        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9966                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9967                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9968                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9969        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9970    }
9971
9972    /*package*/ boolean performDexOpt(DexoptOptions options) {
9973        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9974            return false;
9975        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9976            return false;
9977        }
9978
9979        if (options.isDexoptOnlySecondaryDex()) {
9980            return mDexManager.dexoptSecondaryDex(options);
9981        } else {
9982            int dexoptStatus = performDexOptWithStatus(options);
9983            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9984        }
9985    }
9986
9987    /**
9988     * Perform dexopt on the given package and return one of following result:
9989     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9990     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9991     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9992     */
9993    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9994        return performDexOptTraced(options);
9995    }
9996
9997    private int performDexOptTraced(DexoptOptions options) {
9998        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9999        try {
10000            return performDexOptInternal(options);
10001        } finally {
10002            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10003        }
10004    }
10005
10006    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
10007    // if the package can now be considered up to date for the given filter.
10008    private int performDexOptInternal(DexoptOptions options) {
10009        PackageParser.Package p;
10010        synchronized (mPackages) {
10011            p = mPackages.get(options.getPackageName());
10012            if (p == null) {
10013                // Package could not be found. Report failure.
10014                return PackageDexOptimizer.DEX_OPT_FAILED;
10015            }
10016            mPackageUsage.maybeWriteAsync(mPackages);
10017            mCompilerStats.maybeWriteAsync();
10018        }
10019        long callingId = Binder.clearCallingIdentity();
10020        try {
10021            synchronized (mInstallLock) {
10022                return performDexOptInternalWithDependenciesLI(p, options);
10023            }
10024        } finally {
10025            Binder.restoreCallingIdentity(callingId);
10026        }
10027    }
10028
10029    public ArraySet<String> getOptimizablePackages() {
10030        ArraySet<String> pkgs = new ArraySet<String>();
10031        synchronized (mPackages) {
10032            for (PackageParser.Package p : mPackages.values()) {
10033                if (PackageDexOptimizer.canOptimizePackage(p)) {
10034                    pkgs.add(p.packageName);
10035                }
10036            }
10037        }
10038        return pkgs;
10039    }
10040
10041    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10042            DexoptOptions options) {
10043        // Select the dex optimizer based on the force parameter.
10044        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10045        //       allocate an object here.
10046        PackageDexOptimizer pdo = options.isForce()
10047                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10048                : mPackageDexOptimizer;
10049
10050        // Dexopt all dependencies first. Note: we ignore the return value and march on
10051        // on errors.
10052        // Note that we are going to call performDexOpt on those libraries as many times as
10053        // they are referenced in packages. When we do a batch of performDexOpt (for example
10054        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10055        // and the first package that uses the library will dexopt it. The
10056        // others will see that the compiled code for the library is up to date.
10057        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10058        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10059        if (!deps.isEmpty()) {
10060            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10061                    options.getCompilerFilter(), options.getSplitName(),
10062                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10063            for (PackageParser.Package depPackage : deps) {
10064                // TODO: Analyze and investigate if we (should) profile libraries.
10065                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10066                        getOrCreateCompilerPackageStats(depPackage),
10067                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10068            }
10069        }
10070        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10071                getOrCreateCompilerPackageStats(p),
10072                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10073    }
10074
10075    /**
10076     * Reconcile the information we have about the secondary dex files belonging to
10077     * {@code packagName} and the actual dex files. For all dex files that were
10078     * deleted, update the internal records and delete the generated oat files.
10079     */
10080    @Override
10081    public void reconcileSecondaryDexFiles(String packageName) {
10082        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10083            return;
10084        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10085            return;
10086        }
10087        mDexManager.reconcileSecondaryDexFiles(packageName);
10088    }
10089
10090    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10091    // a reference there.
10092    /*package*/ DexManager getDexManager() {
10093        return mDexManager;
10094    }
10095
10096    /**
10097     * Execute the background dexopt job immediately.
10098     */
10099    @Override
10100    public boolean runBackgroundDexoptJob() {
10101        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10102            return false;
10103        }
10104        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10105    }
10106
10107    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10108        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10109                || p.usesStaticLibraries != null) {
10110            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10111            Set<String> collectedNames = new HashSet<>();
10112            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10113
10114            retValue.remove(p);
10115
10116            return retValue;
10117        } else {
10118            return Collections.emptyList();
10119        }
10120    }
10121
10122    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10123            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10124        if (!collectedNames.contains(p.packageName)) {
10125            collectedNames.add(p.packageName);
10126            collected.add(p);
10127
10128            if (p.usesLibraries != null) {
10129                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10130                        null, collected, collectedNames);
10131            }
10132            if (p.usesOptionalLibraries != null) {
10133                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10134                        null, collected, collectedNames);
10135            }
10136            if (p.usesStaticLibraries != null) {
10137                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10138                        p.usesStaticLibrariesVersions, collected, collectedNames);
10139            }
10140        }
10141    }
10142
10143    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10144            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10145        final int libNameCount = libs.size();
10146        for (int i = 0; i < libNameCount; i++) {
10147            String libName = libs.get(i);
10148            int version = (versions != null && versions.length == libNameCount)
10149                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10150            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10151            if (libPkg != null) {
10152                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10153            }
10154        }
10155    }
10156
10157    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10158        synchronized (mPackages) {
10159            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10160            if (libEntry != null) {
10161                return mPackages.get(libEntry.apk);
10162            }
10163            return null;
10164        }
10165    }
10166
10167    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10168        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10169        if (versionedLib == null) {
10170            return null;
10171        }
10172        return versionedLib.get(version);
10173    }
10174
10175    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10176        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10177                pkg.staticSharedLibName);
10178        if (versionedLib == null) {
10179            return null;
10180        }
10181        int previousLibVersion = -1;
10182        final int versionCount = versionedLib.size();
10183        for (int i = 0; i < versionCount; i++) {
10184            final int libVersion = versionedLib.keyAt(i);
10185            if (libVersion < pkg.staticSharedLibVersion) {
10186                previousLibVersion = Math.max(previousLibVersion, libVersion);
10187            }
10188        }
10189        if (previousLibVersion >= 0) {
10190            return versionedLib.get(previousLibVersion);
10191        }
10192        return null;
10193    }
10194
10195    public void shutdown() {
10196        mPackageUsage.writeNow(mPackages);
10197        mCompilerStats.writeNow();
10198        mDexManager.writePackageDexUsageNow();
10199    }
10200
10201    @Override
10202    public void dumpProfiles(String packageName) {
10203        PackageParser.Package pkg;
10204        synchronized (mPackages) {
10205            pkg = mPackages.get(packageName);
10206            if (pkg == null) {
10207                throw new IllegalArgumentException("Unknown package: " + packageName);
10208            }
10209        }
10210        /* Only the shell, root, or the app user should be able to dump profiles. */
10211        int callingUid = Binder.getCallingUid();
10212        if (callingUid != Process.SHELL_UID &&
10213            callingUid != Process.ROOT_UID &&
10214            callingUid != pkg.applicationInfo.uid) {
10215            throw new SecurityException("dumpProfiles");
10216        }
10217
10218        synchronized (mInstallLock) {
10219            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10220            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10221            try {
10222                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10223                String codePaths = TextUtils.join(";", allCodePaths);
10224                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10225            } catch (InstallerException e) {
10226                Slog.w(TAG, "Failed to dump profiles", e);
10227            }
10228            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10229        }
10230    }
10231
10232    @Override
10233    public void forceDexOpt(String packageName) {
10234        enforceSystemOrRoot("forceDexOpt");
10235
10236        PackageParser.Package pkg;
10237        synchronized (mPackages) {
10238            pkg = mPackages.get(packageName);
10239            if (pkg == null) {
10240                throw new IllegalArgumentException("Unknown package: " + packageName);
10241            }
10242        }
10243
10244        synchronized (mInstallLock) {
10245            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10246
10247            // Whoever is calling forceDexOpt wants a compiled package.
10248            // Don't use profiles since that may cause compilation to be skipped.
10249            final int res = performDexOptInternalWithDependenciesLI(
10250                    pkg,
10251                    new DexoptOptions(packageName,
10252                            getDefaultCompilerFilter(),
10253                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10254
10255            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10256            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10257                throw new IllegalStateException("Failed to dexopt: " + res);
10258            }
10259        }
10260    }
10261
10262    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10263        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10264            Slog.w(TAG, "Unable to update from " + oldPkg.name
10265                    + " to " + newPkg.packageName
10266                    + ": old package not in system partition");
10267            return false;
10268        } else if (mPackages.get(oldPkg.name) != null) {
10269            Slog.w(TAG, "Unable to update from " + oldPkg.name
10270                    + " to " + newPkg.packageName
10271                    + ": old package still exists");
10272            return false;
10273        }
10274        return true;
10275    }
10276
10277    void removeCodePathLI(File codePath) {
10278        if (codePath.isDirectory()) {
10279            try {
10280                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10281            } catch (InstallerException e) {
10282                Slog.w(TAG, "Failed to remove code path", e);
10283            }
10284        } else {
10285            codePath.delete();
10286        }
10287    }
10288
10289    private int[] resolveUserIds(int userId) {
10290        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10291    }
10292
10293    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10294        if (pkg == null) {
10295            Slog.wtf(TAG, "Package was null!", new Throwable());
10296            return;
10297        }
10298        clearAppDataLeafLIF(pkg, userId, flags);
10299        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10300        for (int i = 0; i < childCount; i++) {
10301            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10302        }
10303    }
10304
10305    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10306        final PackageSetting ps;
10307        synchronized (mPackages) {
10308            ps = mSettings.mPackages.get(pkg.packageName);
10309        }
10310        for (int realUserId : resolveUserIds(userId)) {
10311            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10312            try {
10313                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10314                        ceDataInode);
10315            } catch (InstallerException e) {
10316                Slog.w(TAG, String.valueOf(e));
10317            }
10318        }
10319    }
10320
10321    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10322        if (pkg == null) {
10323            Slog.wtf(TAG, "Package was null!", new Throwable());
10324            return;
10325        }
10326        destroyAppDataLeafLIF(pkg, userId, flags);
10327        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10328        for (int i = 0; i < childCount; i++) {
10329            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10330        }
10331    }
10332
10333    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10334        final PackageSetting ps;
10335        synchronized (mPackages) {
10336            ps = mSettings.mPackages.get(pkg.packageName);
10337        }
10338        for (int realUserId : resolveUserIds(userId)) {
10339            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10340            try {
10341                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10342                        ceDataInode);
10343            } catch (InstallerException e) {
10344                Slog.w(TAG, String.valueOf(e));
10345            }
10346            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10347        }
10348    }
10349
10350    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10351        if (pkg == null) {
10352            Slog.wtf(TAG, "Package was null!", new Throwable());
10353            return;
10354        }
10355        destroyAppProfilesLeafLIF(pkg);
10356        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10357        for (int i = 0; i < childCount; i++) {
10358            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10359        }
10360    }
10361
10362    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10363        try {
10364            mInstaller.destroyAppProfiles(pkg.packageName);
10365        } catch (InstallerException e) {
10366            Slog.w(TAG, String.valueOf(e));
10367        }
10368    }
10369
10370    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10371        if (pkg == null) {
10372            Slog.wtf(TAG, "Package was null!", new Throwable());
10373            return;
10374        }
10375        clearAppProfilesLeafLIF(pkg);
10376        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10377        for (int i = 0; i < childCount; i++) {
10378            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10379        }
10380    }
10381
10382    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10383        try {
10384            mInstaller.clearAppProfiles(pkg.packageName);
10385        } catch (InstallerException e) {
10386            Slog.w(TAG, String.valueOf(e));
10387        }
10388    }
10389
10390    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10391            long lastUpdateTime) {
10392        // Set parent install/update time
10393        PackageSetting ps = (PackageSetting) pkg.mExtras;
10394        if (ps != null) {
10395            ps.firstInstallTime = firstInstallTime;
10396            ps.lastUpdateTime = lastUpdateTime;
10397        }
10398        // Set children install/update time
10399        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10400        for (int i = 0; i < childCount; i++) {
10401            PackageParser.Package childPkg = pkg.childPackages.get(i);
10402            ps = (PackageSetting) childPkg.mExtras;
10403            if (ps != null) {
10404                ps.firstInstallTime = firstInstallTime;
10405                ps.lastUpdateTime = lastUpdateTime;
10406            }
10407        }
10408    }
10409
10410    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
10411            SharedLibraryEntry file,
10412            PackageParser.Package changingLib) {
10413        if (file.path != null) {
10414            usesLibraryFiles.add(file.path);
10415            return;
10416        }
10417        PackageParser.Package p = mPackages.get(file.apk);
10418        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10419            // If we are doing this while in the middle of updating a library apk,
10420            // then we need to make sure to use that new apk for determining the
10421            // dependencies here.  (We haven't yet finished committing the new apk
10422            // to the package manager state.)
10423            if (p == null || p.packageName.equals(changingLib.packageName)) {
10424                p = changingLib;
10425            }
10426        }
10427        if (p != null) {
10428            usesLibraryFiles.addAll(p.getAllCodePaths());
10429            if (p.usesLibraryFiles != null) {
10430                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10431            }
10432        }
10433    }
10434
10435    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10436            PackageParser.Package changingLib) throws PackageManagerException {
10437        if (pkg == null) {
10438            return;
10439        }
10440        // The collection used here must maintain the order of addition (so
10441        // that libraries are searched in the correct order) and must have no
10442        // duplicates.
10443        Set<String> usesLibraryFiles = null;
10444        if (pkg.usesLibraries != null) {
10445            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10446                    null, null, pkg.packageName, changingLib, true,
10447                    pkg.applicationInfo.targetSdkVersion, null);
10448        }
10449        if (pkg.usesStaticLibraries != null) {
10450            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10451                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10452                    pkg.packageName, changingLib, true,
10453                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10454        }
10455        if (pkg.usesOptionalLibraries != null) {
10456            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10457                    null, null, pkg.packageName, changingLib, false,
10458                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10459        }
10460        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10461            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10462        } else {
10463            pkg.usesLibraryFiles = null;
10464        }
10465    }
10466
10467    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10468            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10469            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10470            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
10471            throws PackageManagerException {
10472        final int libCount = requestedLibraries.size();
10473        for (int i = 0; i < libCount; i++) {
10474            final String libName = requestedLibraries.get(i);
10475            final int libVersion = requiredVersions != null ? requiredVersions[i]
10476                    : SharedLibraryInfo.VERSION_UNDEFINED;
10477            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10478            if (libEntry == null) {
10479                if (required) {
10480                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10481                            "Package " + packageName + " requires unavailable shared library "
10482                                    + libName + "; failing!");
10483                } else if (DEBUG_SHARED_LIBRARIES) {
10484                    Slog.i(TAG, "Package " + packageName
10485                            + " desires unavailable shared library "
10486                            + libName + "; ignoring!");
10487                }
10488            } else {
10489                if (requiredVersions != null && requiredCertDigests != null) {
10490                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10491                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10492                            "Package " + packageName + " requires unavailable static shared"
10493                                    + " library " + libName + " version "
10494                                    + libEntry.info.getVersion() + "; failing!");
10495                    }
10496
10497                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10498                    if (libPkg == null) {
10499                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10500                                "Package " + packageName + " requires unavailable static shared"
10501                                        + " library; failing!");
10502                    }
10503
10504                    final String[] expectedCertDigests = requiredCertDigests[i];
10505                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10506                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10507                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10508                            : PackageUtils.computeSignaturesSha256Digests(
10509                                    new Signature[]{libPkg.mSignatures[0]});
10510
10511                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10512                    // target O we don't parse the "additional-certificate" tags similarly
10513                    // how we only consider all certs only for apps targeting O (see above).
10514                    // Therefore, the size check is safe to make.
10515                    if (expectedCertDigests.length != libCertDigests.length) {
10516                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10517                                "Package " + packageName + " requires differently signed" +
10518                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10519                    }
10520
10521                    // Use a predictable order as signature order may vary
10522                    Arrays.sort(libCertDigests);
10523                    Arrays.sort(expectedCertDigests);
10524
10525                    final int certCount = libCertDigests.length;
10526                    for (int j = 0; j < certCount; j++) {
10527                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10528                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10529                                    "Package " + packageName + " requires differently signed" +
10530                                            " static shared library; failing!");
10531                        }
10532                    }
10533                }
10534
10535                if (outUsedLibraries == null) {
10536                    // Use LinkedHashSet to preserve the order of files added to
10537                    // usesLibraryFiles while eliminating duplicates.
10538                    outUsedLibraries = new LinkedHashSet<>();
10539                }
10540                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10541            }
10542        }
10543        return outUsedLibraries;
10544    }
10545
10546    private static boolean hasString(List<String> list, List<String> which) {
10547        if (list == null) {
10548            return false;
10549        }
10550        for (int i=list.size()-1; i>=0; i--) {
10551            for (int j=which.size()-1; j>=0; j--) {
10552                if (which.get(j).equals(list.get(i))) {
10553                    return true;
10554                }
10555            }
10556        }
10557        return false;
10558    }
10559
10560    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10561            PackageParser.Package changingPkg) {
10562        ArrayList<PackageParser.Package> res = null;
10563        for (PackageParser.Package pkg : mPackages.values()) {
10564            if (changingPkg != null
10565                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10566                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10567                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10568                            changingPkg.staticSharedLibName)) {
10569                return null;
10570            }
10571            if (res == null) {
10572                res = new ArrayList<>();
10573            }
10574            res.add(pkg);
10575            try {
10576                updateSharedLibrariesLPr(pkg, changingPkg);
10577            } catch (PackageManagerException e) {
10578                // If a system app update or an app and a required lib missing we
10579                // delete the package and for updated system apps keep the data as
10580                // it is better for the user to reinstall than to be in an limbo
10581                // state. Also libs disappearing under an app should never happen
10582                // - just in case.
10583                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10584                    final int flags = pkg.isUpdatedSystemApp()
10585                            ? PackageManager.DELETE_KEEP_DATA : 0;
10586                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10587                            flags , null, true, null);
10588                }
10589                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10590            }
10591        }
10592        return res;
10593    }
10594
10595    /**
10596     * Derive the value of the {@code cpuAbiOverride} based on the provided
10597     * value and an optional stored value from the package settings.
10598     */
10599    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10600        String cpuAbiOverride = null;
10601
10602        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10603            cpuAbiOverride = null;
10604        } else if (abiOverride != null) {
10605            cpuAbiOverride = abiOverride;
10606        } else if (settings != null) {
10607            cpuAbiOverride = settings.cpuAbiOverrideString;
10608        }
10609
10610        return cpuAbiOverride;
10611    }
10612
10613    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10614            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10615                    throws PackageManagerException {
10616        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10617        // If the package has children and this is the first dive in the function
10618        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10619        // whether all packages (parent and children) would be successfully scanned
10620        // before the actual scan since scanning mutates internal state and we want
10621        // to atomically install the package and its children.
10622        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10623            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10624                scanFlags |= SCAN_CHECK_ONLY;
10625            }
10626        } else {
10627            scanFlags &= ~SCAN_CHECK_ONLY;
10628        }
10629
10630        final PackageParser.Package scannedPkg;
10631        try {
10632            // Scan the parent
10633            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10634            // Scan the children
10635            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10636            for (int i = 0; i < childCount; i++) {
10637                PackageParser.Package childPkg = pkg.childPackages.get(i);
10638                scanPackageLI(childPkg, policyFlags,
10639                        scanFlags, currentTime, user);
10640            }
10641        } finally {
10642            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10643        }
10644
10645        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10646            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10647        }
10648
10649        return scannedPkg;
10650    }
10651
10652    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10653            int scanFlags, long currentTime, @Nullable UserHandle user)
10654                    throws PackageManagerException {
10655        boolean success = false;
10656        try {
10657            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10658                    currentTime, user);
10659            success = true;
10660            return res;
10661        } finally {
10662            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10663                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10664                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10665                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10666                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10667            }
10668        }
10669    }
10670
10671    /**
10672     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10673     */
10674    private static boolean apkHasCode(String fileName) {
10675        StrictJarFile jarFile = null;
10676        try {
10677            jarFile = new StrictJarFile(fileName,
10678                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10679            return jarFile.findEntry("classes.dex") != null;
10680        } catch (IOException ignore) {
10681        } finally {
10682            try {
10683                if (jarFile != null) {
10684                    jarFile.close();
10685                }
10686            } catch (IOException ignore) {}
10687        }
10688        return false;
10689    }
10690
10691    /**
10692     * Enforces code policy for the package. This ensures that if an APK has
10693     * declared hasCode="true" in its manifest that the APK actually contains
10694     * code.
10695     *
10696     * @throws PackageManagerException If bytecode could not be found when it should exist
10697     */
10698    private static void assertCodePolicy(PackageParser.Package pkg)
10699            throws PackageManagerException {
10700        final boolean shouldHaveCode =
10701                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10702        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10703            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10704                    "Package " + pkg.baseCodePath + " code is missing");
10705        }
10706
10707        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10708            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10709                final boolean splitShouldHaveCode =
10710                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10711                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10712                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10713                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10714                }
10715            }
10716        }
10717    }
10718
10719    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10720            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10721                    throws PackageManagerException {
10722        if (DEBUG_PACKAGE_SCANNING) {
10723            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10724                Log.d(TAG, "Scanning package " + pkg.packageName);
10725        }
10726
10727        applyPolicy(pkg, policyFlags);
10728
10729        assertPackageIsValid(pkg, policyFlags, scanFlags);
10730
10731        if (Build.IS_DEBUGGABLE &&
10732                pkg.isPrivilegedApp() &&
10733                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10734            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10735        }
10736
10737        // Initialize package source and resource directories
10738        final File scanFile = new File(pkg.codePath);
10739        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10740        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10741
10742        SharedUserSetting suid = null;
10743        PackageSetting pkgSetting = null;
10744
10745        // Getting the package setting may have a side-effect, so if we
10746        // are only checking if scan would succeed, stash a copy of the
10747        // old setting to restore at the end.
10748        PackageSetting nonMutatedPs = null;
10749
10750        // We keep references to the derived CPU Abis from settings in oder to reuse
10751        // them in the case where we're not upgrading or booting for the first time.
10752        String primaryCpuAbiFromSettings = null;
10753        String secondaryCpuAbiFromSettings = null;
10754        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10755
10756        // writer
10757        synchronized (mPackages) {
10758            if (pkg.mSharedUserId != null) {
10759                // SIDE EFFECTS; may potentially allocate a new shared user
10760                suid = mSettings.getSharedUserLPw(
10761                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10762                if (DEBUG_PACKAGE_SCANNING) {
10763                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10764                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10765                                + "): packages=" + suid.packages);
10766                }
10767            }
10768
10769            // Check if we are renaming from an original package name.
10770            PackageSetting origPackage = null;
10771            String realName = null;
10772            if (pkg.mOriginalPackages != null) {
10773                // This package may need to be renamed to a previously
10774                // installed name.  Let's check on that...
10775                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10776                if (pkg.mOriginalPackages.contains(renamed)) {
10777                    // This package had originally been installed as the
10778                    // original name, and we have already taken care of
10779                    // transitioning to the new one.  Just update the new
10780                    // one to continue using the old name.
10781                    realName = pkg.mRealPackage;
10782                    if (!pkg.packageName.equals(renamed)) {
10783                        // Callers into this function may have already taken
10784                        // care of renaming the package; only do it here if
10785                        // it is not already done.
10786                        pkg.setPackageName(renamed);
10787                    }
10788                } else {
10789                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10790                        if ((origPackage = mSettings.getPackageLPr(
10791                                pkg.mOriginalPackages.get(i))) != null) {
10792                            // We do have the package already installed under its
10793                            // original name...  should we use it?
10794                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10795                                // New package is not compatible with original.
10796                                origPackage = null;
10797                                continue;
10798                            } else if (origPackage.sharedUser != null) {
10799                                // Make sure uid is compatible between packages.
10800                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10801                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10802                                            + " to " + pkg.packageName + ": old uid "
10803                                            + origPackage.sharedUser.name
10804                                            + " differs from " + pkg.mSharedUserId);
10805                                    origPackage = null;
10806                                    continue;
10807                                }
10808                                // TODO: Add case when shared user id is added [b/28144775]
10809                            } else {
10810                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10811                                        + pkg.packageName + " to old name " + origPackage.name);
10812                            }
10813                            break;
10814                        }
10815                    }
10816                }
10817            }
10818
10819            if (mTransferedPackages.contains(pkg.packageName)) {
10820                Slog.w(TAG, "Package " + pkg.packageName
10821                        + " was transferred to another, but its .apk remains");
10822            }
10823
10824            // See comments in nonMutatedPs declaration
10825            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10826                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10827                if (foundPs != null) {
10828                    nonMutatedPs = new PackageSetting(foundPs);
10829                }
10830            }
10831
10832            if (!needToDeriveAbi) {
10833                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10834                if (foundPs != null) {
10835                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10836                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10837                } else {
10838                    // when re-adding a system package failed after uninstalling updates.
10839                    needToDeriveAbi = true;
10840                }
10841            }
10842
10843            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10844            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10845                PackageManagerService.reportSettingsProblem(Log.WARN,
10846                        "Package " + pkg.packageName + " shared user changed from "
10847                                + (pkgSetting.sharedUser != null
10848                                        ? pkgSetting.sharedUser.name : "<nothing>")
10849                                + " to "
10850                                + (suid != null ? suid.name : "<nothing>")
10851                                + "; replacing with new");
10852                pkgSetting = null;
10853            }
10854            final PackageSetting oldPkgSetting =
10855                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10856            final PackageSetting disabledPkgSetting =
10857                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10858
10859            String[] usesStaticLibraries = null;
10860            if (pkg.usesStaticLibraries != null) {
10861                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10862                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10863            }
10864
10865            if (pkgSetting == null) {
10866                final String parentPackageName = (pkg.parentPackage != null)
10867                        ? pkg.parentPackage.packageName : null;
10868                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10869                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10870                // REMOVE SharedUserSetting from method; update in a separate call
10871                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10872                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10873                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10874                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10875                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10876                        true /*allowInstall*/, instantApp, virtualPreload,
10877                        parentPackageName, pkg.getChildPackageNames(),
10878                        UserManagerService.getInstance(), usesStaticLibraries,
10879                        pkg.usesStaticLibrariesVersions);
10880                // SIDE EFFECTS; updates system state; move elsewhere
10881                if (origPackage != null) {
10882                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10883                }
10884                mSettings.addUserToSettingLPw(pkgSetting);
10885            } else {
10886                // REMOVE SharedUserSetting from method; update in a separate call.
10887                //
10888                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10889                // secondaryCpuAbi are not known at this point so we always update them
10890                // to null here, only to reset them at a later point.
10891                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10892                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10893                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10894                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10895                        UserManagerService.getInstance(), usesStaticLibraries,
10896                        pkg.usesStaticLibrariesVersions);
10897            }
10898            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10899            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10900
10901            // SIDE EFFECTS; modifies system state; move elsewhere
10902            if (pkgSetting.origPackage != null) {
10903                // If we are first transitioning from an original package,
10904                // fix up the new package's name now.  We need to do this after
10905                // looking up the package under its new name, so getPackageLP
10906                // can take care of fiddling things correctly.
10907                pkg.setPackageName(origPackage.name);
10908
10909                // File a report about this.
10910                String msg = "New package " + pkgSetting.realName
10911                        + " renamed to replace old package " + pkgSetting.name;
10912                reportSettingsProblem(Log.WARN, msg);
10913
10914                // Make a note of it.
10915                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10916                    mTransferedPackages.add(origPackage.name);
10917                }
10918
10919                // No longer need to retain this.
10920                pkgSetting.origPackage = null;
10921            }
10922
10923            // SIDE EFFECTS; modifies system state; move elsewhere
10924            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10925                // Make a note of it.
10926                mTransferedPackages.add(pkg.packageName);
10927            }
10928
10929            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10930                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10931            }
10932
10933            if ((scanFlags & SCAN_BOOTING) == 0
10934                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10935                // Check all shared libraries and map to their actual file path.
10936                // We only do this here for apps not on a system dir, because those
10937                // are the only ones that can fail an install due to this.  We
10938                // will take care of the system apps by updating all of their
10939                // library paths after the scan is done. Also during the initial
10940                // scan don't update any libs as we do this wholesale after all
10941                // apps are scanned to avoid dependency based scanning.
10942                updateSharedLibrariesLPr(pkg, null);
10943            }
10944
10945            if (mFoundPolicyFile) {
10946                SELinuxMMAC.assignSeInfoValue(pkg);
10947            }
10948            pkg.applicationInfo.uid = pkgSetting.appId;
10949            pkg.mExtras = pkgSetting;
10950
10951
10952            // Static shared libs have same package with different versions where
10953            // we internally use a synthetic package name to allow multiple versions
10954            // of the same package, therefore we need to compare signatures against
10955            // the package setting for the latest library version.
10956            PackageSetting signatureCheckPs = pkgSetting;
10957            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10958                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10959                if (libraryEntry != null) {
10960                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10961                }
10962            }
10963
10964            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10965                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10966                    // We just determined the app is signed correctly, so bring
10967                    // over the latest parsed certs.
10968                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10969                } else {
10970                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10971                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10972                                "Package " + pkg.packageName + " upgrade keys do not match the "
10973                                + "previously installed version");
10974                    } else {
10975                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10976                        String msg = "System package " + pkg.packageName
10977                                + " signature changed; retaining data.";
10978                        reportSettingsProblem(Log.WARN, msg);
10979                    }
10980                }
10981            } else {
10982                try {
10983                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10984                    verifySignaturesLP(signatureCheckPs, pkg);
10985                    // We just determined the app is signed correctly, so bring
10986                    // over the latest parsed certs.
10987                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10988                } catch (PackageManagerException e) {
10989                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10990                        throw e;
10991                    }
10992                    // The signature has changed, but this package is in the system
10993                    // image...  let's recover!
10994                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10995                    // However...  if this package is part of a shared user, but it
10996                    // doesn't match the signature of the shared user, let's fail.
10997                    // What this means is that you can't change the signatures
10998                    // associated with an overall shared user, which doesn't seem all
10999                    // that unreasonable.
11000                    if (signatureCheckPs.sharedUser != null) {
11001                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
11002                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
11003                            throw new PackageManagerException(
11004                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
11005                                    "Signature mismatch for shared user: "
11006                                            + pkgSetting.sharedUser);
11007                        }
11008                    }
11009                    // File a report about this.
11010                    String msg = "System package " + pkg.packageName
11011                            + " signature changed; retaining data.";
11012                    reportSettingsProblem(Log.WARN, msg);
11013                }
11014            }
11015
11016            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
11017                // This package wants to adopt ownership of permissions from
11018                // another package.
11019                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
11020                    final String origName = pkg.mAdoptPermissions.get(i);
11021                    final PackageSetting orig = mSettings.getPackageLPr(origName);
11022                    if (orig != null) {
11023                        if (verifyPackageUpdateLPr(orig, pkg)) {
11024                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
11025                                    + pkg.packageName);
11026                            // SIDE EFFECTS; updates permissions system state; move elsewhere
11027                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
11028                        }
11029                    }
11030                }
11031            }
11032        }
11033
11034        pkg.applicationInfo.processName = fixProcessName(
11035                pkg.applicationInfo.packageName,
11036                pkg.applicationInfo.processName);
11037
11038        if (pkg != mPlatformPackage) {
11039            // Get all of our default paths setup
11040            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11041        }
11042
11043        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11044
11045        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11046            if (needToDeriveAbi) {
11047                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11048                final boolean extractNativeLibs = !pkg.isLibrary();
11049                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11050                        mAppLib32InstallDir);
11051                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11052
11053                // Some system apps still use directory structure for native libraries
11054                // in which case we might end up not detecting abi solely based on apk
11055                // structure. Try to detect abi based on directory structure.
11056                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11057                        pkg.applicationInfo.primaryCpuAbi == null) {
11058                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11059                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11060                }
11061            } else {
11062                // This is not a first boot or an upgrade, don't bother deriving the
11063                // ABI during the scan. Instead, trust the value that was stored in the
11064                // package setting.
11065                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11066                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11067
11068                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11069
11070                if (DEBUG_ABI_SELECTION) {
11071                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11072                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11073                        pkg.applicationInfo.secondaryCpuAbi);
11074                }
11075            }
11076        } else {
11077            if ((scanFlags & SCAN_MOVE) != 0) {
11078                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11079                // but we already have this packages package info in the PackageSetting. We just
11080                // use that and derive the native library path based on the new codepath.
11081                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11082                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11083            }
11084
11085            // Set native library paths again. For moves, the path will be updated based on the
11086            // ABIs we've determined above. For non-moves, the path will be updated based on the
11087            // ABIs we determined during compilation, but the path will depend on the final
11088            // package path (after the rename away from the stage path).
11089            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11090        }
11091
11092        // This is a special case for the "system" package, where the ABI is
11093        // dictated by the zygote configuration (and init.rc). We should keep track
11094        // of this ABI so that we can deal with "normal" applications that run under
11095        // the same UID correctly.
11096        if (mPlatformPackage == pkg) {
11097            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11098                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11099        }
11100
11101        // If there's a mismatch between the abi-override in the package setting
11102        // and the abiOverride specified for the install. Warn about this because we
11103        // would've already compiled the app without taking the package setting into
11104        // account.
11105        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11106            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11107                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11108                        " for package " + pkg.packageName);
11109            }
11110        }
11111
11112        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11113        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11114        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11115
11116        // Copy the derived override back to the parsed package, so that we can
11117        // update the package settings accordingly.
11118        pkg.cpuAbiOverride = cpuAbiOverride;
11119
11120        if (DEBUG_ABI_SELECTION) {
11121            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11122                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11123                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11124        }
11125
11126        // Push the derived path down into PackageSettings so we know what to
11127        // clean up at uninstall time.
11128        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11129
11130        if (DEBUG_ABI_SELECTION) {
11131            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11132                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11133                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11134        }
11135
11136        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11137        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11138            // We don't do this here during boot because we can do it all
11139            // at once after scanning all existing packages.
11140            //
11141            // We also do this *before* we perform dexopt on this package, so that
11142            // we can avoid redundant dexopts, and also to make sure we've got the
11143            // code and package path correct.
11144            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11145        }
11146
11147        if (mFactoryTest && pkg.requestedPermissions.contains(
11148                android.Manifest.permission.FACTORY_TEST)) {
11149            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11150        }
11151
11152        if (isSystemApp(pkg)) {
11153            pkgSetting.isOrphaned = true;
11154        }
11155
11156        // Take care of first install / last update times.
11157        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11158        if (currentTime != 0) {
11159            if (pkgSetting.firstInstallTime == 0) {
11160                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11161            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11162                pkgSetting.lastUpdateTime = currentTime;
11163            }
11164        } else if (pkgSetting.firstInstallTime == 0) {
11165            // We need *something*.  Take time time stamp of the file.
11166            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11167        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11168            if (scanFileTime != pkgSetting.timeStamp) {
11169                // A package on the system image has changed; consider this
11170                // to be an update.
11171                pkgSetting.lastUpdateTime = scanFileTime;
11172            }
11173        }
11174        pkgSetting.setTimeStamp(scanFileTime);
11175
11176        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11177            if (nonMutatedPs != null) {
11178                synchronized (mPackages) {
11179                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11180                }
11181            }
11182        } else {
11183            final int userId = user == null ? 0 : user.getIdentifier();
11184            // Modify state for the given package setting
11185            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11186                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11187            if (pkgSetting.getInstantApp(userId)) {
11188                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11189            }
11190        }
11191        return pkg;
11192    }
11193
11194    /**
11195     * Applies policy to the parsed package based upon the given policy flags.
11196     * Ensures the package is in a good state.
11197     * <p>
11198     * Implementation detail: This method must NOT have any side effect. It would
11199     * ideally be static, but, it requires locks to read system state.
11200     */
11201    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11202        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11203            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11204            if (pkg.applicationInfo.isDirectBootAware()) {
11205                // we're direct boot aware; set for all components
11206                for (PackageParser.Service s : pkg.services) {
11207                    s.info.encryptionAware = s.info.directBootAware = true;
11208                }
11209                for (PackageParser.Provider p : pkg.providers) {
11210                    p.info.encryptionAware = p.info.directBootAware = true;
11211                }
11212                for (PackageParser.Activity a : pkg.activities) {
11213                    a.info.encryptionAware = a.info.directBootAware = true;
11214                }
11215                for (PackageParser.Activity r : pkg.receivers) {
11216                    r.info.encryptionAware = r.info.directBootAware = true;
11217                }
11218            }
11219            if (compressedFileExists(pkg.codePath)) {
11220                pkg.isStub = true;
11221            }
11222        } else {
11223            // Only allow system apps to be flagged as core apps.
11224            pkg.coreApp = false;
11225            // clear flags not applicable to regular apps
11226            pkg.applicationInfo.privateFlags &=
11227                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11228            pkg.applicationInfo.privateFlags &=
11229                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11230        }
11231        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11232
11233        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11234            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11235        }
11236
11237        if (!isSystemApp(pkg)) {
11238            // Only system apps can use these features.
11239            pkg.mOriginalPackages = null;
11240            pkg.mRealPackage = null;
11241            pkg.mAdoptPermissions = null;
11242        }
11243    }
11244
11245    /**
11246     * Asserts the parsed package is valid according to the given policy. If the
11247     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11248     * <p>
11249     * Implementation detail: This method must NOT have any side effects. It would
11250     * ideally be static, but, it requires locks to read system state.
11251     *
11252     * @throws PackageManagerException If the package fails any of the validation checks
11253     */
11254    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11255            throws PackageManagerException {
11256        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11257            assertCodePolicy(pkg);
11258        }
11259
11260        if (pkg.applicationInfo.getCodePath() == null ||
11261                pkg.applicationInfo.getResourcePath() == null) {
11262            // Bail out. The resource and code paths haven't been set.
11263            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11264                    "Code and resource paths haven't been set correctly");
11265        }
11266
11267        // Make sure we're not adding any bogus keyset info
11268        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11269        ksms.assertScannedPackageValid(pkg);
11270
11271        synchronized (mPackages) {
11272            // The special "android" package can only be defined once
11273            if (pkg.packageName.equals("android")) {
11274                if (mAndroidApplication != null) {
11275                    Slog.w(TAG, "*************************************************");
11276                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11277                    Slog.w(TAG, " codePath=" + pkg.codePath);
11278                    Slog.w(TAG, "*************************************************");
11279                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11280                            "Core android package being redefined.  Skipping.");
11281                }
11282            }
11283
11284            // A package name must be unique; don't allow duplicates
11285            if (mPackages.containsKey(pkg.packageName)) {
11286                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11287                        "Application package " + pkg.packageName
11288                        + " already installed.  Skipping duplicate.");
11289            }
11290
11291            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11292                // Static libs have a synthetic package name containing the version
11293                // but we still want the base name to be unique.
11294                if (mPackages.containsKey(pkg.manifestPackageName)) {
11295                    throw new PackageManagerException(
11296                            "Duplicate static shared lib provider package");
11297                }
11298
11299                // Static shared libraries should have at least O target SDK
11300                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11301                    throw new PackageManagerException(
11302                            "Packages declaring static-shared libs must target O SDK or higher");
11303                }
11304
11305                // Package declaring static a shared lib cannot be instant apps
11306                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11307                    throw new PackageManagerException(
11308                            "Packages declaring static-shared libs cannot be instant apps");
11309                }
11310
11311                // Package declaring static a shared lib cannot be renamed since the package
11312                // name is synthetic and apps can't code around package manager internals.
11313                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11314                    throw new PackageManagerException(
11315                            "Packages declaring static-shared libs cannot be renamed");
11316                }
11317
11318                // Package declaring static a shared lib cannot declare child packages
11319                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11320                    throw new PackageManagerException(
11321                            "Packages declaring static-shared libs cannot have child packages");
11322                }
11323
11324                // Package declaring static a shared lib cannot declare dynamic libs
11325                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11326                    throw new PackageManagerException(
11327                            "Packages declaring static-shared libs cannot declare dynamic libs");
11328                }
11329
11330                // Package declaring static a shared lib cannot declare shared users
11331                if (pkg.mSharedUserId != null) {
11332                    throw new PackageManagerException(
11333                            "Packages declaring static-shared libs cannot declare shared users");
11334                }
11335
11336                // Static shared libs cannot declare activities
11337                if (!pkg.activities.isEmpty()) {
11338                    throw new PackageManagerException(
11339                            "Static shared libs cannot declare activities");
11340                }
11341
11342                // Static shared libs cannot declare services
11343                if (!pkg.services.isEmpty()) {
11344                    throw new PackageManagerException(
11345                            "Static shared libs cannot declare services");
11346                }
11347
11348                // Static shared libs cannot declare providers
11349                if (!pkg.providers.isEmpty()) {
11350                    throw new PackageManagerException(
11351                            "Static shared libs cannot declare content providers");
11352                }
11353
11354                // Static shared libs cannot declare receivers
11355                if (!pkg.receivers.isEmpty()) {
11356                    throw new PackageManagerException(
11357                            "Static shared libs cannot declare broadcast receivers");
11358                }
11359
11360                // Static shared libs cannot declare permission groups
11361                if (!pkg.permissionGroups.isEmpty()) {
11362                    throw new PackageManagerException(
11363                            "Static shared libs cannot declare permission groups");
11364                }
11365
11366                // Static shared libs cannot declare permissions
11367                if (!pkg.permissions.isEmpty()) {
11368                    throw new PackageManagerException(
11369                            "Static shared libs cannot declare permissions");
11370                }
11371
11372                // Static shared libs cannot declare protected broadcasts
11373                if (pkg.protectedBroadcasts != null) {
11374                    throw new PackageManagerException(
11375                            "Static shared libs cannot declare protected broadcasts");
11376                }
11377
11378                // Static shared libs cannot be overlay targets
11379                if (pkg.mOverlayTarget != null) {
11380                    throw new PackageManagerException(
11381                            "Static shared libs cannot be overlay targets");
11382                }
11383
11384                // The version codes must be ordered as lib versions
11385                int minVersionCode = Integer.MIN_VALUE;
11386                int maxVersionCode = Integer.MAX_VALUE;
11387
11388                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11389                        pkg.staticSharedLibName);
11390                if (versionedLib != null) {
11391                    final int versionCount = versionedLib.size();
11392                    for (int i = 0; i < versionCount; i++) {
11393                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11394                        final int libVersionCode = libInfo.getDeclaringPackage()
11395                                .getVersionCode();
11396                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11397                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11398                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11399                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11400                        } else {
11401                            minVersionCode = maxVersionCode = libVersionCode;
11402                            break;
11403                        }
11404                    }
11405                }
11406                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11407                    throw new PackageManagerException("Static shared"
11408                            + " lib version codes must be ordered as lib versions");
11409                }
11410            }
11411
11412            // Only privileged apps and updated privileged apps can add child packages.
11413            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11414                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11415                    throw new PackageManagerException("Only privileged apps can add child "
11416                            + "packages. Ignoring package " + pkg.packageName);
11417                }
11418                final int childCount = pkg.childPackages.size();
11419                for (int i = 0; i < childCount; i++) {
11420                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11421                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11422                            childPkg.packageName)) {
11423                        throw new PackageManagerException("Can't override child of "
11424                                + "another disabled app. Ignoring package " + pkg.packageName);
11425                    }
11426                }
11427            }
11428
11429            // If we're only installing presumed-existing packages, require that the
11430            // scanned APK is both already known and at the path previously established
11431            // for it.  Previously unknown packages we pick up normally, but if we have an
11432            // a priori expectation about this package's install presence, enforce it.
11433            // With a singular exception for new system packages. When an OTA contains
11434            // a new system package, we allow the codepath to change from a system location
11435            // to the user-installed location. If we don't allow this change, any newer,
11436            // user-installed version of the application will be ignored.
11437            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11438                if (mExpectingBetter.containsKey(pkg.packageName)) {
11439                    logCriticalInfo(Log.WARN,
11440                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11441                } else {
11442                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11443                    if (known != null) {
11444                        if (DEBUG_PACKAGE_SCANNING) {
11445                            Log.d(TAG, "Examining " + pkg.codePath
11446                                    + " and requiring known paths " + known.codePathString
11447                                    + " & " + known.resourcePathString);
11448                        }
11449                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11450                                || !pkg.applicationInfo.getResourcePath().equals(
11451                                        known.resourcePathString)) {
11452                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11453                                    "Application package " + pkg.packageName
11454                                    + " found at " + pkg.applicationInfo.getCodePath()
11455                                    + " but expected at " + known.codePathString
11456                                    + "; ignoring.");
11457                        }
11458                    } else {
11459                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11460                                "Application package " + pkg.packageName
11461                                + " not found; ignoring.");
11462                    }
11463                }
11464            }
11465
11466            // Verify that this new package doesn't have any content providers
11467            // that conflict with existing packages.  Only do this if the
11468            // package isn't already installed, since we don't want to break
11469            // things that are installed.
11470            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11471                final int N = pkg.providers.size();
11472                int i;
11473                for (i=0; i<N; i++) {
11474                    PackageParser.Provider p = pkg.providers.get(i);
11475                    if (p.info.authority != null) {
11476                        String names[] = p.info.authority.split(";");
11477                        for (int j = 0; j < names.length; j++) {
11478                            if (mProvidersByAuthority.containsKey(names[j])) {
11479                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11480                                final String otherPackageName =
11481                                        ((other != null && other.getComponentName() != null) ?
11482                                                other.getComponentName().getPackageName() : "?");
11483                                throw new PackageManagerException(
11484                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11485                                        "Can't install because provider name " + names[j]
11486                                                + " (in package " + pkg.applicationInfo.packageName
11487                                                + ") is already used by " + otherPackageName);
11488                            }
11489                        }
11490                    }
11491                }
11492            }
11493        }
11494    }
11495
11496    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11497            int type, String declaringPackageName, int declaringVersionCode) {
11498        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11499        if (versionedLib == null) {
11500            versionedLib = new SparseArray<>();
11501            mSharedLibraries.put(name, versionedLib);
11502            if (type == SharedLibraryInfo.TYPE_STATIC) {
11503                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11504            }
11505        } else if (versionedLib.indexOfKey(version) >= 0) {
11506            return false;
11507        }
11508        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11509                version, type, declaringPackageName, declaringVersionCode);
11510        versionedLib.put(version, libEntry);
11511        return true;
11512    }
11513
11514    private boolean removeSharedLibraryLPw(String name, int version) {
11515        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11516        if (versionedLib == null) {
11517            return false;
11518        }
11519        final int libIdx = versionedLib.indexOfKey(version);
11520        if (libIdx < 0) {
11521            return false;
11522        }
11523        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11524        versionedLib.remove(version);
11525        if (versionedLib.size() <= 0) {
11526            mSharedLibraries.remove(name);
11527            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11528                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11529                        .getPackageName());
11530            }
11531        }
11532        return true;
11533    }
11534
11535    /**
11536     * Adds a scanned package to the system. When this method is finished, the package will
11537     * be available for query, resolution, etc...
11538     */
11539    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11540            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11541        final String pkgName = pkg.packageName;
11542        if (mCustomResolverComponentName != null &&
11543                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11544            setUpCustomResolverActivity(pkg);
11545        }
11546
11547        if (pkg.packageName.equals("android")) {
11548            synchronized (mPackages) {
11549                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11550                    // Set up information for our fall-back user intent resolution activity.
11551                    mPlatformPackage = pkg;
11552                    pkg.mVersionCode = mSdkVersion;
11553                    mAndroidApplication = pkg.applicationInfo;
11554                    if (!mResolverReplaced) {
11555                        mResolveActivity.applicationInfo = mAndroidApplication;
11556                        mResolveActivity.name = ResolverActivity.class.getName();
11557                        mResolveActivity.packageName = mAndroidApplication.packageName;
11558                        mResolveActivity.processName = "system:ui";
11559                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11560                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11561                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11562                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11563                        mResolveActivity.exported = true;
11564                        mResolveActivity.enabled = true;
11565                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11566                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11567                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11568                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11569                                | ActivityInfo.CONFIG_ORIENTATION
11570                                | ActivityInfo.CONFIG_KEYBOARD
11571                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11572                        mResolveInfo.activityInfo = mResolveActivity;
11573                        mResolveInfo.priority = 0;
11574                        mResolveInfo.preferredOrder = 0;
11575                        mResolveInfo.match = 0;
11576                        mResolveComponentName = new ComponentName(
11577                                mAndroidApplication.packageName, mResolveActivity.name);
11578                    }
11579                }
11580            }
11581        }
11582
11583        ArrayList<PackageParser.Package> clientLibPkgs = null;
11584        // writer
11585        synchronized (mPackages) {
11586            boolean hasStaticSharedLibs = false;
11587
11588            // Any app can add new static shared libraries
11589            if (pkg.staticSharedLibName != null) {
11590                // Static shared libs don't allow renaming as they have synthetic package
11591                // names to allow install of multiple versions, so use name from manifest.
11592                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11593                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11594                        pkg.manifestPackageName, pkg.mVersionCode)) {
11595                    hasStaticSharedLibs = true;
11596                } else {
11597                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11598                                + pkg.staticSharedLibName + " already exists; skipping");
11599                }
11600                // Static shared libs cannot be updated once installed since they
11601                // use synthetic package name which includes the version code, so
11602                // not need to update other packages's shared lib dependencies.
11603            }
11604
11605            if (!hasStaticSharedLibs
11606                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11607                // Only system apps can add new dynamic shared libraries.
11608                if (pkg.libraryNames != null) {
11609                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11610                        String name = pkg.libraryNames.get(i);
11611                        boolean allowed = false;
11612                        if (pkg.isUpdatedSystemApp()) {
11613                            // New library entries can only be added through the
11614                            // system image.  This is important to get rid of a lot
11615                            // of nasty edge cases: for example if we allowed a non-
11616                            // system update of the app to add a library, then uninstalling
11617                            // the update would make the library go away, and assumptions
11618                            // we made such as through app install filtering would now
11619                            // have allowed apps on the device which aren't compatible
11620                            // with it.  Better to just have the restriction here, be
11621                            // conservative, and create many fewer cases that can negatively
11622                            // impact the user experience.
11623                            final PackageSetting sysPs = mSettings
11624                                    .getDisabledSystemPkgLPr(pkg.packageName);
11625                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11626                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11627                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11628                                        allowed = true;
11629                                        break;
11630                                    }
11631                                }
11632                            }
11633                        } else {
11634                            allowed = true;
11635                        }
11636                        if (allowed) {
11637                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11638                                    SharedLibraryInfo.VERSION_UNDEFINED,
11639                                    SharedLibraryInfo.TYPE_DYNAMIC,
11640                                    pkg.packageName, pkg.mVersionCode)) {
11641                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11642                                        + name + " already exists; skipping");
11643                            }
11644                        } else {
11645                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11646                                    + name + " that is not declared on system image; skipping");
11647                        }
11648                    }
11649
11650                    if ((scanFlags & SCAN_BOOTING) == 0) {
11651                        // If we are not booting, we need to update any applications
11652                        // that are clients of our shared library.  If we are booting,
11653                        // this will all be done once the scan is complete.
11654                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11655                    }
11656                }
11657            }
11658        }
11659
11660        if ((scanFlags & SCAN_BOOTING) != 0) {
11661            // No apps can run during boot scan, so they don't need to be frozen
11662        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11663            // Caller asked to not kill app, so it's probably not frozen
11664        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11665            // Caller asked us to ignore frozen check for some reason; they
11666            // probably didn't know the package name
11667        } else {
11668            // We're doing major surgery on this package, so it better be frozen
11669            // right now to keep it from launching
11670            checkPackageFrozen(pkgName);
11671        }
11672
11673        // Also need to kill any apps that are dependent on the library.
11674        if (clientLibPkgs != null) {
11675            for (int i=0; i<clientLibPkgs.size(); i++) {
11676                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11677                killApplication(clientPkg.applicationInfo.packageName,
11678                        clientPkg.applicationInfo.uid, "update lib");
11679            }
11680        }
11681
11682        // writer
11683        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11684
11685        synchronized (mPackages) {
11686            // We don't expect installation to fail beyond this point
11687
11688            // Add the new setting to mSettings
11689            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11690            // Add the new setting to mPackages
11691            mPackages.put(pkg.applicationInfo.packageName, pkg);
11692            // Make sure we don't accidentally delete its data.
11693            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11694            while (iter.hasNext()) {
11695                PackageCleanItem item = iter.next();
11696                if (pkgName.equals(item.packageName)) {
11697                    iter.remove();
11698                }
11699            }
11700
11701            // Add the package's KeySets to the global KeySetManagerService
11702            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11703            ksms.addScannedPackageLPw(pkg);
11704
11705            int N = pkg.providers.size();
11706            StringBuilder r = null;
11707            int i;
11708            for (i=0; i<N; i++) {
11709                PackageParser.Provider p = pkg.providers.get(i);
11710                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11711                        p.info.processName);
11712                mProviders.addProvider(p);
11713                p.syncable = p.info.isSyncable;
11714                if (p.info.authority != null) {
11715                    String names[] = p.info.authority.split(";");
11716                    p.info.authority = null;
11717                    for (int j = 0; j < names.length; j++) {
11718                        if (j == 1 && p.syncable) {
11719                            // We only want the first authority for a provider to possibly be
11720                            // syncable, so if we already added this provider using a different
11721                            // authority clear the syncable flag. We copy the provider before
11722                            // changing it because the mProviders object contains a reference
11723                            // to a provider that we don't want to change.
11724                            // Only do this for the second authority since the resulting provider
11725                            // object can be the same for all future authorities for this provider.
11726                            p = new PackageParser.Provider(p);
11727                            p.syncable = false;
11728                        }
11729                        if (!mProvidersByAuthority.containsKey(names[j])) {
11730                            mProvidersByAuthority.put(names[j], p);
11731                            if (p.info.authority == null) {
11732                                p.info.authority = names[j];
11733                            } else {
11734                                p.info.authority = p.info.authority + ";" + names[j];
11735                            }
11736                            if (DEBUG_PACKAGE_SCANNING) {
11737                                if (chatty)
11738                                    Log.d(TAG, "Registered content provider: " + names[j]
11739                                            + ", className = " + p.info.name + ", isSyncable = "
11740                                            + p.info.isSyncable);
11741                            }
11742                        } else {
11743                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11744                            Slog.w(TAG, "Skipping provider name " + names[j] +
11745                                    " (in package " + pkg.applicationInfo.packageName +
11746                                    "): name already used by "
11747                                    + ((other != null && other.getComponentName() != null)
11748                                            ? other.getComponentName().getPackageName() : "?"));
11749                        }
11750                    }
11751                }
11752                if (chatty) {
11753                    if (r == null) {
11754                        r = new StringBuilder(256);
11755                    } else {
11756                        r.append(' ');
11757                    }
11758                    r.append(p.info.name);
11759                }
11760            }
11761            if (r != null) {
11762                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11763            }
11764
11765            N = pkg.services.size();
11766            r = null;
11767            for (i=0; i<N; i++) {
11768                PackageParser.Service s = pkg.services.get(i);
11769                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11770                        s.info.processName);
11771                mServices.addService(s);
11772                if (chatty) {
11773                    if (r == null) {
11774                        r = new StringBuilder(256);
11775                    } else {
11776                        r.append(' ');
11777                    }
11778                    r.append(s.info.name);
11779                }
11780            }
11781            if (r != null) {
11782                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11783            }
11784
11785            N = pkg.receivers.size();
11786            r = null;
11787            for (i=0; i<N; i++) {
11788                PackageParser.Activity a = pkg.receivers.get(i);
11789                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11790                        a.info.processName);
11791                mReceivers.addActivity(a, "receiver");
11792                if (chatty) {
11793                    if (r == null) {
11794                        r = new StringBuilder(256);
11795                    } else {
11796                        r.append(' ');
11797                    }
11798                    r.append(a.info.name);
11799                }
11800            }
11801            if (r != null) {
11802                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11803            }
11804
11805            N = pkg.activities.size();
11806            r = null;
11807            for (i=0; i<N; i++) {
11808                PackageParser.Activity a = pkg.activities.get(i);
11809                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11810                        a.info.processName);
11811                mActivities.addActivity(a, "activity");
11812                if (chatty) {
11813                    if (r == null) {
11814                        r = new StringBuilder(256);
11815                    } else {
11816                        r.append(' ');
11817                    }
11818                    r.append(a.info.name);
11819                }
11820            }
11821            if (r != null) {
11822                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11823            }
11824
11825            N = pkg.permissionGroups.size();
11826            r = null;
11827            for (i=0; i<N; i++) {
11828                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11829                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11830                final String curPackageName = cur == null ? null : cur.info.packageName;
11831                // Dont allow ephemeral apps to define new permission groups.
11832                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11833                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11834                            + pg.info.packageName
11835                            + " ignored: instant apps cannot define new permission groups.");
11836                    continue;
11837                }
11838                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11839                if (cur == null || isPackageUpdate) {
11840                    mPermissionGroups.put(pg.info.name, pg);
11841                    if (chatty) {
11842                        if (r == null) {
11843                            r = new StringBuilder(256);
11844                        } else {
11845                            r.append(' ');
11846                        }
11847                        if (isPackageUpdate) {
11848                            r.append("UPD:");
11849                        }
11850                        r.append(pg.info.name);
11851                    }
11852                } else {
11853                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11854                            + pg.info.packageName + " ignored: original from "
11855                            + cur.info.packageName);
11856                    if (chatty) {
11857                        if (r == null) {
11858                            r = new StringBuilder(256);
11859                        } else {
11860                            r.append(' ');
11861                        }
11862                        r.append("DUP:");
11863                        r.append(pg.info.name);
11864                    }
11865                }
11866            }
11867            if (r != null) {
11868                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11869            }
11870
11871            N = pkg.permissions.size();
11872            r = null;
11873            for (i=0; i<N; i++) {
11874                PackageParser.Permission p = pkg.permissions.get(i);
11875
11876                // Dont allow ephemeral apps to define new permissions.
11877                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11878                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11879                            + p.info.packageName
11880                            + " ignored: instant apps cannot define new permissions.");
11881                    continue;
11882                }
11883
11884                // Assume by default that we did not install this permission into the system.
11885                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11886
11887                // Now that permission groups have a special meaning, we ignore permission
11888                // groups for legacy apps to prevent unexpected behavior. In particular,
11889                // permissions for one app being granted to someone just because they happen
11890                // to be in a group defined by another app (before this had no implications).
11891                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11892                    p.group = mPermissionGroups.get(p.info.group);
11893                    // Warn for a permission in an unknown group.
11894                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11895                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11896                                + p.info.packageName + " in an unknown group " + p.info.group);
11897                    }
11898                }
11899
11900                ArrayMap<String, BasePermission> permissionMap =
11901                        p.tree ? mSettings.mPermissionTrees
11902                                : mSettings.mPermissions;
11903                BasePermission bp = permissionMap.get(p.info.name);
11904
11905                // Allow system apps to redefine non-system permissions
11906                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11907                    final boolean currentOwnerIsSystem = (bp.perm != null
11908                            && isSystemApp(bp.perm.owner));
11909                    if (isSystemApp(p.owner)) {
11910                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11911                            // It's a built-in permission and no owner, take ownership now
11912                            bp.packageSetting = pkgSetting;
11913                            bp.perm = p;
11914                            bp.uid = pkg.applicationInfo.uid;
11915                            bp.sourcePackage = p.info.packageName;
11916                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11917                        } else if (!currentOwnerIsSystem) {
11918                            String msg = "New decl " + p.owner + " of permission  "
11919                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11920                            reportSettingsProblem(Log.WARN, msg);
11921                            bp = null;
11922                        }
11923                    }
11924                }
11925
11926                if (bp == null) {
11927                    bp = new BasePermission(p.info.name, p.info.packageName,
11928                            BasePermission.TYPE_NORMAL);
11929                    permissionMap.put(p.info.name, bp);
11930                }
11931
11932                if (bp.perm == null) {
11933                    if (bp.sourcePackage == null
11934                            || bp.sourcePackage.equals(p.info.packageName)) {
11935                        BasePermission tree = findPermissionTreeLP(p.info.name);
11936                        if (tree == null
11937                                || tree.sourcePackage.equals(p.info.packageName)) {
11938                            bp.packageSetting = pkgSetting;
11939                            bp.perm = p;
11940                            bp.uid = pkg.applicationInfo.uid;
11941                            bp.sourcePackage = p.info.packageName;
11942                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11943                            if (chatty) {
11944                                if (r == null) {
11945                                    r = new StringBuilder(256);
11946                                } else {
11947                                    r.append(' ');
11948                                }
11949                                r.append(p.info.name);
11950                            }
11951                        } else {
11952                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11953                                    + p.info.packageName + " ignored: base tree "
11954                                    + tree.name + " is from package "
11955                                    + tree.sourcePackage);
11956                        }
11957                    } else {
11958                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11959                                + p.info.packageName + " ignored: original from "
11960                                + bp.sourcePackage);
11961                    }
11962                } else if (chatty) {
11963                    if (r == null) {
11964                        r = new StringBuilder(256);
11965                    } else {
11966                        r.append(' ');
11967                    }
11968                    r.append("DUP:");
11969                    r.append(p.info.name);
11970                }
11971                if (bp.perm == p) {
11972                    bp.protectionLevel = p.info.protectionLevel;
11973                }
11974            }
11975
11976            if (r != null) {
11977                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11978            }
11979
11980            N = pkg.instrumentation.size();
11981            r = null;
11982            for (i=0; i<N; i++) {
11983                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11984                a.info.packageName = pkg.applicationInfo.packageName;
11985                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11986                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11987                a.info.splitNames = pkg.splitNames;
11988                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11989                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11990                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11991                a.info.dataDir = pkg.applicationInfo.dataDir;
11992                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11993                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11994                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11995                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11996                mInstrumentation.put(a.getComponentName(), a);
11997                if (chatty) {
11998                    if (r == null) {
11999                        r = new StringBuilder(256);
12000                    } else {
12001                        r.append(' ');
12002                    }
12003                    r.append(a.info.name);
12004                }
12005            }
12006            if (r != null) {
12007                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
12008            }
12009
12010            if (pkg.protectedBroadcasts != null) {
12011                N = pkg.protectedBroadcasts.size();
12012                synchronized (mProtectedBroadcasts) {
12013                    for (i = 0; i < N; i++) {
12014                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
12015                    }
12016                }
12017            }
12018        }
12019
12020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12021    }
12022
12023    /**
12024     * Derive the ABI of a non-system package located at {@code scanFile}. This information
12025     * is derived purely on the basis of the contents of {@code scanFile} and
12026     * {@code cpuAbiOverride}.
12027     *
12028     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12029     */
12030    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
12031                                 String cpuAbiOverride, boolean extractLibs,
12032                                 File appLib32InstallDir)
12033            throws PackageManagerException {
12034        // Give ourselves some initial paths; we'll come back for another
12035        // pass once we've determined ABI below.
12036        setNativeLibraryPaths(pkg, appLib32InstallDir);
12037
12038        // We would never need to extract libs for forward-locked and external packages,
12039        // since the container service will do it for us. We shouldn't attempt to
12040        // extract libs from system app when it was not updated.
12041        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12042                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12043            extractLibs = false;
12044        }
12045
12046        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12047        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12048
12049        NativeLibraryHelper.Handle handle = null;
12050        try {
12051            handle = NativeLibraryHelper.Handle.create(pkg);
12052            // TODO(multiArch): This can be null for apps that didn't go through the
12053            // usual installation process. We can calculate it again, like we
12054            // do during install time.
12055            //
12056            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12057            // unnecessary.
12058            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12059
12060            // Null out the abis so that they can be recalculated.
12061            pkg.applicationInfo.primaryCpuAbi = null;
12062            pkg.applicationInfo.secondaryCpuAbi = null;
12063            if (isMultiArch(pkg.applicationInfo)) {
12064                // Warn if we've set an abiOverride for multi-lib packages..
12065                // By definition, we need to copy both 32 and 64 bit libraries for
12066                // such packages.
12067                if (pkg.cpuAbiOverride != null
12068                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12069                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12070                }
12071
12072                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12073                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12074                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12075                    if (extractLibs) {
12076                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12077                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12078                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12079                                useIsaSpecificSubdirs);
12080                    } else {
12081                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12082                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12083                    }
12084                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12085                }
12086
12087                // Shared library native code should be in the APK zip aligned
12088                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12089                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12090                            "Shared library native lib extraction not supported");
12091                }
12092
12093                maybeThrowExceptionForMultiArchCopy(
12094                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12095
12096                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12097                    if (extractLibs) {
12098                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12099                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12100                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12101                                useIsaSpecificSubdirs);
12102                    } else {
12103                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12104                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12105                    }
12106                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12107                }
12108
12109                maybeThrowExceptionForMultiArchCopy(
12110                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12111
12112                if (abi64 >= 0) {
12113                    // Shared library native libs should be in the APK zip aligned
12114                    if (extractLibs && pkg.isLibrary()) {
12115                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12116                                "Shared library native lib extraction not supported");
12117                    }
12118                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12119                }
12120
12121                if (abi32 >= 0) {
12122                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12123                    if (abi64 >= 0) {
12124                        if (pkg.use32bitAbi) {
12125                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12126                            pkg.applicationInfo.primaryCpuAbi = abi;
12127                        } else {
12128                            pkg.applicationInfo.secondaryCpuAbi = abi;
12129                        }
12130                    } else {
12131                        pkg.applicationInfo.primaryCpuAbi = abi;
12132                    }
12133                }
12134            } else {
12135                String[] abiList = (cpuAbiOverride != null) ?
12136                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12137
12138                // Enable gross and lame hacks for apps that are built with old
12139                // SDK tools. We must scan their APKs for renderscript bitcode and
12140                // not launch them if it's present. Don't bother checking on devices
12141                // that don't have 64 bit support.
12142                boolean needsRenderScriptOverride = false;
12143                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12144                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12145                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12146                    needsRenderScriptOverride = true;
12147                }
12148
12149                final int copyRet;
12150                if (extractLibs) {
12151                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12152                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12153                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12154                } else {
12155                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12156                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12157                }
12158                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12159
12160                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12161                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12162                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12163                }
12164
12165                if (copyRet >= 0) {
12166                    // Shared libraries that have native libs must be multi-architecture
12167                    if (pkg.isLibrary()) {
12168                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12169                                "Shared library with native libs must be multiarch");
12170                    }
12171                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12172                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12173                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12174                } else if (needsRenderScriptOverride) {
12175                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12176                }
12177            }
12178        } catch (IOException ioe) {
12179            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12180        } finally {
12181            IoUtils.closeQuietly(handle);
12182        }
12183
12184        // Now that we've calculated the ABIs and determined if it's an internal app,
12185        // we will go ahead and populate the nativeLibraryPath.
12186        setNativeLibraryPaths(pkg, appLib32InstallDir);
12187    }
12188
12189    /**
12190     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12191     * i.e, so that all packages can be run inside a single process if required.
12192     *
12193     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12194     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12195     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12196     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12197     * updating a package that belongs to a shared user.
12198     *
12199     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12200     * adds unnecessary complexity.
12201     */
12202    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12203            PackageParser.Package scannedPackage) {
12204        String requiredInstructionSet = null;
12205        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12206            requiredInstructionSet = VMRuntime.getInstructionSet(
12207                     scannedPackage.applicationInfo.primaryCpuAbi);
12208        }
12209
12210        PackageSetting requirer = null;
12211        for (PackageSetting ps : packagesForUser) {
12212            // If packagesForUser contains scannedPackage, we skip it. This will happen
12213            // when scannedPackage is an update of an existing package. Without this check,
12214            // we will never be able to change the ABI of any package belonging to a shared
12215            // user, even if it's compatible with other packages.
12216            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12217                if (ps.primaryCpuAbiString == null) {
12218                    continue;
12219                }
12220
12221                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12222                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12223                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12224                    // this but there's not much we can do.
12225                    String errorMessage = "Instruction set mismatch, "
12226                            + ((requirer == null) ? "[caller]" : requirer)
12227                            + " requires " + requiredInstructionSet + " whereas " + ps
12228                            + " requires " + instructionSet;
12229                    Slog.w(TAG, errorMessage);
12230                }
12231
12232                if (requiredInstructionSet == null) {
12233                    requiredInstructionSet = instructionSet;
12234                    requirer = ps;
12235                }
12236            }
12237        }
12238
12239        if (requiredInstructionSet != null) {
12240            String adjustedAbi;
12241            if (requirer != null) {
12242                // requirer != null implies that either scannedPackage was null or that scannedPackage
12243                // did not require an ABI, in which case we have to adjust scannedPackage to match
12244                // the ABI of the set (which is the same as requirer's ABI)
12245                adjustedAbi = requirer.primaryCpuAbiString;
12246                if (scannedPackage != null) {
12247                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12248                }
12249            } else {
12250                // requirer == null implies that we're updating all ABIs in the set to
12251                // match scannedPackage.
12252                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12253            }
12254
12255            for (PackageSetting ps : packagesForUser) {
12256                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12257                    if (ps.primaryCpuAbiString != null) {
12258                        continue;
12259                    }
12260
12261                    ps.primaryCpuAbiString = adjustedAbi;
12262                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12263                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12264                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12265                        if (DEBUG_ABI_SELECTION) {
12266                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12267                                    + " (requirer="
12268                                    + (requirer != null ? requirer.pkg : "null")
12269                                    + ", scannedPackage="
12270                                    + (scannedPackage != null ? scannedPackage : "null")
12271                                    + ")");
12272                        }
12273                        try {
12274                            mInstaller.rmdex(ps.codePathString,
12275                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12276                        } catch (InstallerException ignored) {
12277                        }
12278                    }
12279                }
12280            }
12281        }
12282    }
12283
12284    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12285        synchronized (mPackages) {
12286            mResolverReplaced = true;
12287            // Set up information for custom user intent resolution activity.
12288            mResolveActivity.applicationInfo = pkg.applicationInfo;
12289            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12290            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12291            mResolveActivity.processName = pkg.applicationInfo.packageName;
12292            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12293            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12294                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12295            mResolveActivity.theme = 0;
12296            mResolveActivity.exported = true;
12297            mResolveActivity.enabled = true;
12298            mResolveInfo.activityInfo = mResolveActivity;
12299            mResolveInfo.priority = 0;
12300            mResolveInfo.preferredOrder = 0;
12301            mResolveInfo.match = 0;
12302            mResolveComponentName = mCustomResolverComponentName;
12303            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12304                    mResolveComponentName);
12305        }
12306    }
12307
12308    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12309        if (installerActivity == null) {
12310            if (DEBUG_EPHEMERAL) {
12311                Slog.d(TAG, "Clear ephemeral installer activity");
12312            }
12313            mInstantAppInstallerActivity = null;
12314            return;
12315        }
12316
12317        if (DEBUG_EPHEMERAL) {
12318            Slog.d(TAG, "Set ephemeral installer activity: "
12319                    + installerActivity.getComponentName());
12320        }
12321        // Set up information for ephemeral installer activity
12322        mInstantAppInstallerActivity = installerActivity;
12323        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12324                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12325        mInstantAppInstallerActivity.exported = true;
12326        mInstantAppInstallerActivity.enabled = true;
12327        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12328        mInstantAppInstallerInfo.priority = 0;
12329        mInstantAppInstallerInfo.preferredOrder = 1;
12330        mInstantAppInstallerInfo.isDefault = true;
12331        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12332                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12333    }
12334
12335    private static String calculateBundledApkRoot(final String codePathString) {
12336        final File codePath = new File(codePathString);
12337        final File codeRoot;
12338        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12339            codeRoot = Environment.getRootDirectory();
12340        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12341            codeRoot = Environment.getOemDirectory();
12342        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12343            codeRoot = Environment.getVendorDirectory();
12344        } else {
12345            // Unrecognized code path; take its top real segment as the apk root:
12346            // e.g. /something/app/blah.apk => /something
12347            try {
12348                File f = codePath.getCanonicalFile();
12349                File parent = f.getParentFile();    // non-null because codePath is a file
12350                File tmp;
12351                while ((tmp = parent.getParentFile()) != null) {
12352                    f = parent;
12353                    parent = tmp;
12354                }
12355                codeRoot = f;
12356                Slog.w(TAG, "Unrecognized code path "
12357                        + codePath + " - using " + codeRoot);
12358            } catch (IOException e) {
12359                // Can't canonicalize the code path -- shenanigans?
12360                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12361                return Environment.getRootDirectory().getPath();
12362            }
12363        }
12364        return codeRoot.getPath();
12365    }
12366
12367    /**
12368     * Derive and set the location of native libraries for the given package,
12369     * which varies depending on where and how the package was installed.
12370     */
12371    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12372        final ApplicationInfo info = pkg.applicationInfo;
12373        final String codePath = pkg.codePath;
12374        final File codeFile = new File(codePath);
12375        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12376        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12377
12378        info.nativeLibraryRootDir = null;
12379        info.nativeLibraryRootRequiresIsa = false;
12380        info.nativeLibraryDir = null;
12381        info.secondaryNativeLibraryDir = null;
12382
12383        if (isApkFile(codeFile)) {
12384            // Monolithic install
12385            if (bundledApp) {
12386                // If "/system/lib64/apkname" exists, assume that is the per-package
12387                // native library directory to use; otherwise use "/system/lib/apkname".
12388                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12389                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12390                        getPrimaryInstructionSet(info));
12391
12392                // This is a bundled system app so choose the path based on the ABI.
12393                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12394                // is just the default path.
12395                final String apkName = deriveCodePathName(codePath);
12396                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12397                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12398                        apkName).getAbsolutePath();
12399
12400                if (info.secondaryCpuAbi != null) {
12401                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12402                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12403                            secondaryLibDir, apkName).getAbsolutePath();
12404                }
12405            } else if (asecApp) {
12406                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12407                        .getAbsolutePath();
12408            } else {
12409                final String apkName = deriveCodePathName(codePath);
12410                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12411                        .getAbsolutePath();
12412            }
12413
12414            info.nativeLibraryRootRequiresIsa = false;
12415            info.nativeLibraryDir = info.nativeLibraryRootDir;
12416        } else {
12417            // Cluster install
12418            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12419            info.nativeLibraryRootRequiresIsa = true;
12420
12421            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12422                    getPrimaryInstructionSet(info)).getAbsolutePath();
12423
12424            if (info.secondaryCpuAbi != null) {
12425                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12426                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12427            }
12428        }
12429    }
12430
12431    /**
12432     * Calculate the abis and roots for a bundled app. These can uniquely
12433     * be determined from the contents of the system partition, i.e whether
12434     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12435     * of this information, and instead assume that the system was built
12436     * sensibly.
12437     */
12438    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12439                                           PackageSetting pkgSetting) {
12440        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12441
12442        // If "/system/lib64/apkname" exists, assume that is the per-package
12443        // native library directory to use; otherwise use "/system/lib/apkname".
12444        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12445        setBundledAppAbi(pkg, apkRoot, apkName);
12446        // pkgSetting might be null during rescan following uninstall of updates
12447        // to a bundled app, so accommodate that possibility.  The settings in
12448        // that case will be established later from the parsed package.
12449        //
12450        // If the settings aren't null, sync them up with what we've just derived.
12451        // note that apkRoot isn't stored in the package settings.
12452        if (pkgSetting != null) {
12453            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12454            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12455        }
12456    }
12457
12458    /**
12459     * Deduces the ABI of a bundled app and sets the relevant fields on the
12460     * parsed pkg object.
12461     *
12462     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12463     *        under which system libraries are installed.
12464     * @param apkName the name of the installed package.
12465     */
12466    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12467        final File codeFile = new File(pkg.codePath);
12468
12469        final boolean has64BitLibs;
12470        final boolean has32BitLibs;
12471        if (isApkFile(codeFile)) {
12472            // Monolithic install
12473            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12474            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12475        } else {
12476            // Cluster install
12477            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12478            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12479                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12480                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12481                has64BitLibs = (new File(rootDir, isa)).exists();
12482            } else {
12483                has64BitLibs = false;
12484            }
12485            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12486                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12487                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12488                has32BitLibs = (new File(rootDir, isa)).exists();
12489            } else {
12490                has32BitLibs = false;
12491            }
12492        }
12493
12494        if (has64BitLibs && !has32BitLibs) {
12495            // The package has 64 bit libs, but not 32 bit libs. Its primary
12496            // ABI should be 64 bit. We can safely assume here that the bundled
12497            // native libraries correspond to the most preferred ABI in the list.
12498
12499            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12500            pkg.applicationInfo.secondaryCpuAbi = null;
12501        } else if (has32BitLibs && !has64BitLibs) {
12502            // The package has 32 bit libs but not 64 bit libs. Its primary
12503            // ABI should be 32 bit.
12504
12505            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12506            pkg.applicationInfo.secondaryCpuAbi = null;
12507        } else if (has32BitLibs && has64BitLibs) {
12508            // The application has both 64 and 32 bit bundled libraries. We check
12509            // here that the app declares multiArch support, and warn if it doesn't.
12510            //
12511            // We will be lenient here and record both ABIs. The primary will be the
12512            // ABI that's higher on the list, i.e, a device that's configured to prefer
12513            // 64 bit apps will see a 64 bit primary ABI,
12514
12515            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12516                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12517            }
12518
12519            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12520                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12521                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12522            } else {
12523                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12524                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12525            }
12526        } else {
12527            pkg.applicationInfo.primaryCpuAbi = null;
12528            pkg.applicationInfo.secondaryCpuAbi = null;
12529        }
12530    }
12531
12532    private void killApplication(String pkgName, int appId, String reason) {
12533        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12534    }
12535
12536    private void killApplication(String pkgName, int appId, int userId, String reason) {
12537        // Request the ActivityManager to kill the process(only for existing packages)
12538        // so that we do not end up in a confused state while the user is still using the older
12539        // version of the application while the new one gets installed.
12540        final long token = Binder.clearCallingIdentity();
12541        try {
12542            IActivityManager am = ActivityManager.getService();
12543            if (am != null) {
12544                try {
12545                    am.killApplication(pkgName, appId, userId, reason);
12546                } catch (RemoteException e) {
12547                }
12548            }
12549        } finally {
12550            Binder.restoreCallingIdentity(token);
12551        }
12552    }
12553
12554    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12555        // Remove the parent package setting
12556        PackageSetting ps = (PackageSetting) pkg.mExtras;
12557        if (ps != null) {
12558            removePackageLI(ps, chatty);
12559        }
12560        // Remove the child package setting
12561        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12562        for (int i = 0; i < childCount; i++) {
12563            PackageParser.Package childPkg = pkg.childPackages.get(i);
12564            ps = (PackageSetting) childPkg.mExtras;
12565            if (ps != null) {
12566                removePackageLI(ps, chatty);
12567            }
12568        }
12569    }
12570
12571    void removePackageLI(PackageSetting ps, boolean chatty) {
12572        if (DEBUG_INSTALL) {
12573            if (chatty)
12574                Log.d(TAG, "Removing package " + ps.name);
12575        }
12576
12577        // writer
12578        synchronized (mPackages) {
12579            mPackages.remove(ps.name);
12580            final PackageParser.Package pkg = ps.pkg;
12581            if (pkg != null) {
12582                cleanPackageDataStructuresLILPw(pkg, chatty);
12583            }
12584        }
12585    }
12586
12587    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12588        if (DEBUG_INSTALL) {
12589            if (chatty)
12590                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12591        }
12592
12593        // writer
12594        synchronized (mPackages) {
12595            // Remove the parent package
12596            mPackages.remove(pkg.applicationInfo.packageName);
12597            cleanPackageDataStructuresLILPw(pkg, chatty);
12598
12599            // Remove the child packages
12600            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12601            for (int i = 0; i < childCount; i++) {
12602                PackageParser.Package childPkg = pkg.childPackages.get(i);
12603                mPackages.remove(childPkg.applicationInfo.packageName);
12604                cleanPackageDataStructuresLILPw(childPkg, chatty);
12605            }
12606        }
12607    }
12608
12609    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12610        int N = pkg.providers.size();
12611        StringBuilder r = null;
12612        int i;
12613        for (i=0; i<N; i++) {
12614            PackageParser.Provider p = pkg.providers.get(i);
12615            mProviders.removeProvider(p);
12616            if (p.info.authority == null) {
12617
12618                /* There was another ContentProvider with this authority when
12619                 * this app was installed so this authority is null,
12620                 * Ignore it as we don't have to unregister the provider.
12621                 */
12622                continue;
12623            }
12624            String names[] = p.info.authority.split(";");
12625            for (int j = 0; j < names.length; j++) {
12626                if (mProvidersByAuthority.get(names[j]) == p) {
12627                    mProvidersByAuthority.remove(names[j]);
12628                    if (DEBUG_REMOVE) {
12629                        if (chatty)
12630                            Log.d(TAG, "Unregistered content provider: " + names[j]
12631                                    + ", className = " + p.info.name + ", isSyncable = "
12632                                    + p.info.isSyncable);
12633                    }
12634                }
12635            }
12636            if (DEBUG_REMOVE && chatty) {
12637                if (r == null) {
12638                    r = new StringBuilder(256);
12639                } else {
12640                    r.append(' ');
12641                }
12642                r.append(p.info.name);
12643            }
12644        }
12645        if (r != null) {
12646            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12647        }
12648
12649        N = pkg.services.size();
12650        r = null;
12651        for (i=0; i<N; i++) {
12652            PackageParser.Service s = pkg.services.get(i);
12653            mServices.removeService(s);
12654            if (chatty) {
12655                if (r == null) {
12656                    r = new StringBuilder(256);
12657                } else {
12658                    r.append(' ');
12659                }
12660                r.append(s.info.name);
12661            }
12662        }
12663        if (r != null) {
12664            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12665        }
12666
12667        N = pkg.receivers.size();
12668        r = null;
12669        for (i=0; i<N; i++) {
12670            PackageParser.Activity a = pkg.receivers.get(i);
12671            mReceivers.removeActivity(a, "receiver");
12672            if (DEBUG_REMOVE && chatty) {
12673                if (r == null) {
12674                    r = new StringBuilder(256);
12675                } else {
12676                    r.append(' ');
12677                }
12678                r.append(a.info.name);
12679            }
12680        }
12681        if (r != null) {
12682            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12683        }
12684
12685        N = pkg.activities.size();
12686        r = null;
12687        for (i=0; i<N; i++) {
12688            PackageParser.Activity a = pkg.activities.get(i);
12689            mActivities.removeActivity(a, "activity");
12690            if (DEBUG_REMOVE && chatty) {
12691                if (r == null) {
12692                    r = new StringBuilder(256);
12693                } else {
12694                    r.append(' ');
12695                }
12696                r.append(a.info.name);
12697            }
12698        }
12699        if (r != null) {
12700            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12701        }
12702
12703        N = pkg.permissions.size();
12704        r = null;
12705        for (i=0; i<N; i++) {
12706            PackageParser.Permission p = pkg.permissions.get(i);
12707            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12708            if (bp == null) {
12709                bp = mSettings.mPermissionTrees.get(p.info.name);
12710            }
12711            if (bp != null && bp.perm == p) {
12712                bp.perm = null;
12713                if (DEBUG_REMOVE && chatty) {
12714                    if (r == null) {
12715                        r = new StringBuilder(256);
12716                    } else {
12717                        r.append(' ');
12718                    }
12719                    r.append(p.info.name);
12720                }
12721            }
12722            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12723                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12724                if (appOpPkgs != null) {
12725                    appOpPkgs.remove(pkg.packageName);
12726                }
12727            }
12728        }
12729        if (r != null) {
12730            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12731        }
12732
12733        N = pkg.requestedPermissions.size();
12734        r = null;
12735        for (i=0; i<N; i++) {
12736            String perm = pkg.requestedPermissions.get(i);
12737            BasePermission bp = mSettings.mPermissions.get(perm);
12738            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12739                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12740                if (appOpPkgs != null) {
12741                    appOpPkgs.remove(pkg.packageName);
12742                    if (appOpPkgs.isEmpty()) {
12743                        mAppOpPermissionPackages.remove(perm);
12744                    }
12745                }
12746            }
12747        }
12748        if (r != null) {
12749            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12750        }
12751
12752        N = pkg.instrumentation.size();
12753        r = null;
12754        for (i=0; i<N; i++) {
12755            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12756            mInstrumentation.remove(a.getComponentName());
12757            if (DEBUG_REMOVE && chatty) {
12758                if (r == null) {
12759                    r = new StringBuilder(256);
12760                } else {
12761                    r.append(' ');
12762                }
12763                r.append(a.info.name);
12764            }
12765        }
12766        if (r != null) {
12767            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12768        }
12769
12770        r = null;
12771        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12772            // Only system apps can hold shared libraries.
12773            if (pkg.libraryNames != null) {
12774                for (i = 0; i < pkg.libraryNames.size(); i++) {
12775                    String name = pkg.libraryNames.get(i);
12776                    if (removeSharedLibraryLPw(name, 0)) {
12777                        if (DEBUG_REMOVE && chatty) {
12778                            if (r == null) {
12779                                r = new StringBuilder(256);
12780                            } else {
12781                                r.append(' ');
12782                            }
12783                            r.append(name);
12784                        }
12785                    }
12786                }
12787            }
12788        }
12789
12790        r = null;
12791
12792        // Any package can hold static shared libraries.
12793        if (pkg.staticSharedLibName != null) {
12794            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12795                if (DEBUG_REMOVE && chatty) {
12796                    if (r == null) {
12797                        r = new StringBuilder(256);
12798                    } else {
12799                        r.append(' ');
12800                    }
12801                    r.append(pkg.staticSharedLibName);
12802                }
12803            }
12804        }
12805
12806        if (r != null) {
12807            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12808        }
12809    }
12810
12811    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12812        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12813            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12814                return true;
12815            }
12816        }
12817        return false;
12818    }
12819
12820    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12821    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12822    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12823
12824    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12825        // Update the parent permissions
12826        updatePermissionsLPw(pkg.packageName, pkg, flags);
12827        // Update the child permissions
12828        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12829        for (int i = 0; i < childCount; i++) {
12830            PackageParser.Package childPkg = pkg.childPackages.get(i);
12831            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12832        }
12833    }
12834
12835    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12836            int flags) {
12837        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12838        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12839    }
12840
12841    private void updatePermissionsLPw(String changingPkg,
12842            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12843        // Make sure there are no dangling permission trees.
12844        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12845        while (it.hasNext()) {
12846            final BasePermission bp = it.next();
12847            if (bp.packageSetting == null) {
12848                // We may not yet have parsed the package, so just see if
12849                // we still know about its settings.
12850                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12851            }
12852            if (bp.packageSetting == null) {
12853                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12854                        + " from package " + bp.sourcePackage);
12855                it.remove();
12856            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12857                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12858                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12859                            + " from package " + bp.sourcePackage);
12860                    flags |= UPDATE_PERMISSIONS_ALL;
12861                    it.remove();
12862                }
12863            }
12864        }
12865
12866        // Make sure all dynamic permissions have been assigned to a package,
12867        // and make sure there are no dangling permissions.
12868        it = mSettings.mPermissions.values().iterator();
12869        while (it.hasNext()) {
12870            final BasePermission bp = it.next();
12871            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12872                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12873                        + bp.name + " pkg=" + bp.sourcePackage
12874                        + " info=" + bp.pendingInfo);
12875                if (bp.packageSetting == null && bp.pendingInfo != null) {
12876                    final BasePermission tree = findPermissionTreeLP(bp.name);
12877                    if (tree != null && tree.perm != null) {
12878                        bp.packageSetting = tree.packageSetting;
12879                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12880                                new PermissionInfo(bp.pendingInfo));
12881                        bp.perm.info.packageName = tree.perm.info.packageName;
12882                        bp.perm.info.name = bp.name;
12883                        bp.uid = tree.uid;
12884                    }
12885                }
12886            }
12887            if (bp.packageSetting == null) {
12888                // We may not yet have parsed the package, so just see if
12889                // we still know about its settings.
12890                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12891            }
12892            if (bp.packageSetting == null) {
12893                Slog.w(TAG, "Removing dangling permission: " + bp.name
12894                        + " from package " + bp.sourcePackage);
12895                it.remove();
12896            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12897                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12898                    Slog.i(TAG, "Removing old permission: " + bp.name
12899                            + " from package " + bp.sourcePackage);
12900                    flags |= UPDATE_PERMISSIONS_ALL;
12901                    it.remove();
12902                }
12903            }
12904        }
12905
12906        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12907        // Now update the permissions for all packages, in particular
12908        // replace the granted permissions of the system packages.
12909        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12910            for (PackageParser.Package pkg : mPackages.values()) {
12911                if (pkg != pkgInfo) {
12912                    // Only replace for packages on requested volume
12913                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12914                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12915                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12916                    grantPermissionsLPw(pkg, replace, changingPkg);
12917                }
12918            }
12919        }
12920
12921        if (pkgInfo != null) {
12922            // Only replace for packages on requested volume
12923            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12924            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12925                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12926            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12927        }
12928        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12929    }
12930
12931    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12932            String packageOfInterest) {
12933        // IMPORTANT: There are two types of permissions: install and runtime.
12934        // Install time permissions are granted when the app is installed to
12935        // all device users and users added in the future. Runtime permissions
12936        // are granted at runtime explicitly to specific users. Normal and signature
12937        // protected permissions are install time permissions. Dangerous permissions
12938        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12939        // otherwise they are runtime permissions. This function does not manage
12940        // runtime permissions except for the case an app targeting Lollipop MR1
12941        // being upgraded to target a newer SDK, in which case dangerous permissions
12942        // are transformed from install time to runtime ones.
12943
12944        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12945        if (ps == null) {
12946            return;
12947        }
12948
12949        PermissionsState permissionsState = ps.getPermissionsState();
12950        PermissionsState origPermissions = permissionsState;
12951
12952        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12953
12954        boolean runtimePermissionsRevoked = false;
12955        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12956
12957        boolean changedInstallPermission = false;
12958
12959        if (replace) {
12960            ps.installPermissionsFixed = false;
12961            if (!ps.isSharedUser()) {
12962                origPermissions = new PermissionsState(permissionsState);
12963                permissionsState.reset();
12964            } else {
12965                // We need to know only about runtime permission changes since the
12966                // calling code always writes the install permissions state but
12967                // the runtime ones are written only if changed. The only cases of
12968                // changed runtime permissions here are promotion of an install to
12969                // runtime and revocation of a runtime from a shared user.
12970                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12971                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12972                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12973                    runtimePermissionsRevoked = true;
12974                }
12975            }
12976        }
12977
12978        permissionsState.setGlobalGids(mGlobalGids);
12979
12980        final int N = pkg.requestedPermissions.size();
12981        for (int i=0; i<N; i++) {
12982            final String name = pkg.requestedPermissions.get(i);
12983            final BasePermission bp = mSettings.mPermissions.get(name);
12984            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12985                    >= Build.VERSION_CODES.M;
12986
12987            if (DEBUG_INSTALL) {
12988                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12989            }
12990
12991            if (bp == null || bp.packageSetting == null) {
12992                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12993                    if (DEBUG_PERMISSIONS) {
12994                        Slog.i(TAG, "Unknown permission " + name
12995                                + " in package " + pkg.packageName);
12996                    }
12997                }
12998                continue;
12999            }
13000
13001
13002            // Limit ephemeral apps to ephemeral allowed permissions.
13003            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
13004                if (DEBUG_PERMISSIONS) {
13005                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
13006                            + pkg.packageName);
13007                }
13008                continue;
13009            }
13010
13011            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
13012                if (DEBUG_PERMISSIONS) {
13013                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
13014                            + pkg.packageName);
13015                }
13016                continue;
13017            }
13018
13019            final String perm = bp.name;
13020            boolean allowedSig = false;
13021            int grant = GRANT_DENIED;
13022
13023            // Keep track of app op permissions.
13024            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
13025                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
13026                if (pkgs == null) {
13027                    pkgs = new ArraySet<>();
13028                    mAppOpPermissionPackages.put(bp.name, pkgs);
13029                }
13030                pkgs.add(pkg.packageName);
13031            }
13032
13033            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
13034            switch (level) {
13035                case PermissionInfo.PROTECTION_NORMAL: {
13036                    // For all apps normal permissions are install time ones.
13037                    grant = GRANT_INSTALL;
13038                } break;
13039
13040                case PermissionInfo.PROTECTION_DANGEROUS: {
13041                    // If a permission review is required for legacy apps we represent
13042                    // their permissions as always granted runtime ones since we need
13043                    // to keep the review required permission flag per user while an
13044                    // install permission's state is shared across all users.
13045                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13046                        // For legacy apps dangerous permissions are install time ones.
13047                        grant = GRANT_INSTALL;
13048                    } else if (origPermissions.hasInstallPermission(bp.name)) {
13049                        // For legacy apps that became modern, install becomes runtime.
13050                        grant = GRANT_UPGRADE;
13051                    } else if (mPromoteSystemApps
13052                            && isSystemApp(ps)
13053                            && mExistingSystemPackages.contains(ps.name)) {
13054                        // For legacy system apps, install becomes runtime.
13055                        // We cannot check hasInstallPermission() for system apps since those
13056                        // permissions were granted implicitly and not persisted pre-M.
13057                        grant = GRANT_UPGRADE;
13058                    } else {
13059                        // For modern apps keep runtime permissions unchanged.
13060                        grant = GRANT_RUNTIME;
13061                    }
13062                } break;
13063
13064                case PermissionInfo.PROTECTION_SIGNATURE: {
13065                    // For all apps signature permissions are install time ones.
13066                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13067                    if (allowedSig) {
13068                        grant = GRANT_INSTALL;
13069                    }
13070                } break;
13071            }
13072
13073            if (DEBUG_PERMISSIONS) {
13074                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13075            }
13076
13077            if (grant != GRANT_DENIED) {
13078                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13079                    // If this is an existing, non-system package, then
13080                    // we can't add any new permissions to it.
13081                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13082                        // Except...  if this is a permission that was added
13083                        // to the platform (note: need to only do this when
13084                        // updating the platform).
13085                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13086                            grant = GRANT_DENIED;
13087                        }
13088                    }
13089                }
13090
13091                switch (grant) {
13092                    case GRANT_INSTALL: {
13093                        // Revoke this as runtime permission to handle the case of
13094                        // a runtime permission being downgraded to an install one.
13095                        // Also in permission review mode we keep dangerous permissions
13096                        // for legacy apps
13097                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13098                            if (origPermissions.getRuntimePermissionState(
13099                                    bp.name, userId) != null) {
13100                                // Revoke the runtime permission and clear the flags.
13101                                origPermissions.revokeRuntimePermission(bp, userId);
13102                                origPermissions.updatePermissionFlags(bp, userId,
13103                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13104                                // If we revoked a permission permission, we have to write.
13105                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13106                                        changedRuntimePermissionUserIds, userId);
13107                            }
13108                        }
13109                        // Grant an install permission.
13110                        if (permissionsState.grantInstallPermission(bp) !=
13111                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13112                            changedInstallPermission = true;
13113                        }
13114                    } break;
13115
13116                    case GRANT_RUNTIME: {
13117                        // Grant previously granted runtime permissions.
13118                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13119                            PermissionState permissionState = origPermissions
13120                                    .getRuntimePermissionState(bp.name, userId);
13121                            int flags = permissionState != null
13122                                    ? permissionState.getFlags() : 0;
13123                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13124                                // Don't propagate the permission in a permission review mode if
13125                                // the former was revoked, i.e. marked to not propagate on upgrade.
13126                                // Note that in a permission review mode install permissions are
13127                                // represented as constantly granted runtime ones since we need to
13128                                // keep a per user state associated with the permission. Also the
13129                                // revoke on upgrade flag is no longer applicable and is reset.
13130                                final boolean revokeOnUpgrade = (flags & PackageManager
13131                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13132                                if (revokeOnUpgrade) {
13133                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13134                                    // Since we changed the flags, we have to write.
13135                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13136                                            changedRuntimePermissionUserIds, userId);
13137                                }
13138                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13139                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13140                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13141                                        // If we cannot put the permission as it was,
13142                                        // we have to write.
13143                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13144                                                changedRuntimePermissionUserIds, userId);
13145                                    }
13146                                }
13147
13148                                // If the app supports runtime permissions no need for a review.
13149                                if (mPermissionReviewRequired
13150                                        && appSupportsRuntimePermissions
13151                                        && (flags & PackageManager
13152                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13153                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13154                                    // Since we changed the flags, we have to write.
13155                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13156                                            changedRuntimePermissionUserIds, userId);
13157                                }
13158                            } else if (mPermissionReviewRequired
13159                                    && !appSupportsRuntimePermissions) {
13160                                // For legacy apps that need a permission review, every new
13161                                // runtime permission is granted but it is pending a review.
13162                                // We also need to review only platform defined runtime
13163                                // permissions as these are the only ones the platform knows
13164                                // how to disable the API to simulate revocation as legacy
13165                                // apps don't expect to run with revoked permissions.
13166                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13167                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13168                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13169                                        // We changed the flags, hence have to write.
13170                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13171                                                changedRuntimePermissionUserIds, userId);
13172                                    }
13173                                }
13174                                if (permissionsState.grantRuntimePermission(bp, userId)
13175                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13176                                    // We changed the permission, hence have to write.
13177                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13178                                            changedRuntimePermissionUserIds, userId);
13179                                }
13180                            }
13181                            // Propagate the permission flags.
13182                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13183                        }
13184                    } break;
13185
13186                    case GRANT_UPGRADE: {
13187                        // Grant runtime permissions for a previously held install permission.
13188                        PermissionState permissionState = origPermissions
13189                                .getInstallPermissionState(bp.name);
13190                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13191
13192                        if (origPermissions.revokeInstallPermission(bp)
13193                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13194                            // We will be transferring the permission flags, so clear them.
13195                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13196                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13197                            changedInstallPermission = true;
13198                        }
13199
13200                        // If the permission is not to be promoted to runtime we ignore it and
13201                        // also its other flags as they are not applicable to install permissions.
13202                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13203                            for (int userId : currentUserIds) {
13204                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13205                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13206                                    // Transfer the permission flags.
13207                                    permissionsState.updatePermissionFlags(bp, userId,
13208                                            flags, flags);
13209                                    // If we granted the permission, we have to write.
13210                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13211                                            changedRuntimePermissionUserIds, userId);
13212                                }
13213                            }
13214                        }
13215                    } break;
13216
13217                    default: {
13218                        if (packageOfInterest == null
13219                                || packageOfInterest.equals(pkg.packageName)) {
13220                            if (DEBUG_PERMISSIONS) {
13221                                Slog.i(TAG, "Not granting permission " + perm
13222                                        + " to package " + pkg.packageName
13223                                        + " because it was previously installed without");
13224                            }
13225                        }
13226                    } break;
13227                }
13228            } else {
13229                if (permissionsState.revokeInstallPermission(bp) !=
13230                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13231                    // Also drop the permission flags.
13232                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13233                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13234                    changedInstallPermission = true;
13235                    Slog.i(TAG, "Un-granting permission " + perm
13236                            + " from package " + pkg.packageName
13237                            + " (protectionLevel=" + bp.protectionLevel
13238                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13239                            + ")");
13240                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13241                    // Don't print warning for app op permissions, since it is fine for them
13242                    // not to be granted, there is a UI for the user to decide.
13243                    if (DEBUG_PERMISSIONS
13244                            && (packageOfInterest == null
13245                                    || packageOfInterest.equals(pkg.packageName))) {
13246                        Slog.i(TAG, "Not granting permission " + perm
13247                                + " to package " + pkg.packageName
13248                                + " (protectionLevel=" + bp.protectionLevel
13249                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13250                                + ")");
13251                    }
13252                }
13253            }
13254        }
13255
13256        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13257                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13258            // This is the first that we have heard about this package, so the
13259            // permissions we have now selected are fixed until explicitly
13260            // changed.
13261            ps.installPermissionsFixed = true;
13262        }
13263
13264        // Persist the runtime permissions state for users with changes. If permissions
13265        // were revoked because no app in the shared user declares them we have to
13266        // write synchronously to avoid losing runtime permissions state.
13267        for (int userId : changedRuntimePermissionUserIds) {
13268            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13269        }
13270    }
13271
13272    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13273        boolean allowed = false;
13274        final int NP = PackageParser.NEW_PERMISSIONS.length;
13275        for (int ip=0; ip<NP; ip++) {
13276            final PackageParser.NewPermissionInfo npi
13277                    = PackageParser.NEW_PERMISSIONS[ip];
13278            if (npi.name.equals(perm)
13279                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13280                allowed = true;
13281                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13282                        + pkg.packageName);
13283                break;
13284            }
13285        }
13286        return allowed;
13287    }
13288
13289    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13290            BasePermission bp, PermissionsState origPermissions) {
13291        boolean privilegedPermission = (bp.protectionLevel
13292                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13293        boolean privappPermissionsDisable =
13294                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13295        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13296        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13297        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13298                && !platformPackage && platformPermission) {
13299            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13300                    .getPrivAppPermissions(pkg.packageName);
13301            final boolean whitelisted =
13302                    allowedPermissions != null && allowedPermissions.contains(perm);
13303            if (!whitelisted) {
13304                Slog.w(TAG, "Privileged permission " + perm + " for package "
13305                        + pkg.packageName + " - not in privapp-permissions whitelist");
13306                // Only report violations for apps on system image
13307                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13308                    // it's only a reportable violation if the permission isn't explicitly denied
13309                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13310                            .getPrivAppDenyPermissions(pkg.packageName);
13311                    final boolean permissionViolation =
13312                            deniedPermissions == null || !deniedPermissions.contains(perm);
13313                    if (permissionViolation) {
13314                        if (mPrivappPermissionsViolations == null) {
13315                            mPrivappPermissionsViolations = new ArraySet<>();
13316                        }
13317                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13318                    } else {
13319                        return false;
13320                    }
13321                }
13322                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13323                    return false;
13324                }
13325            }
13326        }
13327        boolean allowed = (compareSignatures(
13328                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13329                        == PackageManager.SIGNATURE_MATCH)
13330                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13331                        == PackageManager.SIGNATURE_MATCH);
13332        if (!allowed && privilegedPermission) {
13333            if (isSystemApp(pkg)) {
13334                // For updated system applications, a system permission
13335                // is granted only if it had been defined by the original application.
13336                if (pkg.isUpdatedSystemApp()) {
13337                    final PackageSetting sysPs = mSettings
13338                            .getDisabledSystemPkgLPr(pkg.packageName);
13339                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13340                        // If the original was granted this permission, we take
13341                        // that grant decision as read and propagate it to the
13342                        // update.
13343                        if (sysPs.isPrivileged()) {
13344                            allowed = true;
13345                        }
13346                    } else {
13347                        // The system apk may have been updated with an older
13348                        // version of the one on the data partition, but which
13349                        // granted a new system permission that it didn't have
13350                        // before.  In this case we do want to allow the app to
13351                        // now get the new permission if the ancestral apk is
13352                        // privileged to get it.
13353                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13354                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13355                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13356                                    allowed = true;
13357                                    break;
13358                                }
13359                            }
13360                        }
13361                        // Also if a privileged parent package on the system image or any of
13362                        // its children requested a privileged permission, the updated child
13363                        // packages can also get the permission.
13364                        if (pkg.parentPackage != null) {
13365                            final PackageSetting disabledSysParentPs = mSettings
13366                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13367                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13368                                    && disabledSysParentPs.isPrivileged()) {
13369                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13370                                    allowed = true;
13371                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13372                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13373                                    for (int i = 0; i < count; i++) {
13374                                        PackageParser.Package disabledSysChildPkg =
13375                                                disabledSysParentPs.pkg.childPackages.get(i);
13376                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13377                                                perm)) {
13378                                            allowed = true;
13379                                            break;
13380                                        }
13381                                    }
13382                                }
13383                            }
13384                        }
13385                    }
13386                } else {
13387                    allowed = isPrivilegedApp(pkg);
13388                }
13389            }
13390        }
13391        if (!allowed) {
13392            if (!allowed && (bp.protectionLevel
13393                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13394                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13395                // If this was a previously normal/dangerous permission that got moved
13396                // to a system permission as part of the runtime permission redesign, then
13397                // we still want to blindly grant it to old apps.
13398                allowed = true;
13399            }
13400            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13401                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13402                // If this permission is to be granted to the system installer and
13403                // this app is an installer, then it gets the permission.
13404                allowed = true;
13405            }
13406            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13407                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13408                // If this permission is to be granted to the system verifier and
13409                // this app is a verifier, then it gets the permission.
13410                allowed = true;
13411            }
13412            if (!allowed && (bp.protectionLevel
13413                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13414                    && isSystemApp(pkg)) {
13415                // Any pre-installed system app is allowed to get this permission.
13416                allowed = true;
13417            }
13418            if (!allowed && (bp.protectionLevel
13419                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13420                // For development permissions, a development permission
13421                // is granted only if it was already granted.
13422                allowed = origPermissions.hasInstallPermission(perm);
13423            }
13424            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13425                    && pkg.packageName.equals(mSetupWizardPackage)) {
13426                // If this permission is to be granted to the system setup wizard and
13427                // this app is a setup wizard, then it gets the permission.
13428                allowed = true;
13429            }
13430        }
13431        return allowed;
13432    }
13433
13434    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13435        final int permCount = pkg.requestedPermissions.size();
13436        for (int j = 0; j < permCount; j++) {
13437            String requestedPermission = pkg.requestedPermissions.get(j);
13438            if (permission.equals(requestedPermission)) {
13439                return true;
13440            }
13441        }
13442        return false;
13443    }
13444
13445    final class ActivityIntentResolver
13446            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13447        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13448                boolean defaultOnly, int userId) {
13449            if (!sUserManager.exists(userId)) return null;
13450            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13451            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13452        }
13453
13454        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13455                int userId) {
13456            if (!sUserManager.exists(userId)) return null;
13457            mFlags = flags;
13458            return super.queryIntent(intent, resolvedType,
13459                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13460                    userId);
13461        }
13462
13463        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13464                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13465            if (!sUserManager.exists(userId)) return null;
13466            if (packageActivities == null) {
13467                return null;
13468            }
13469            mFlags = flags;
13470            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13471            final int N = packageActivities.size();
13472            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13473                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13474
13475            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13476            for (int i = 0; i < N; ++i) {
13477                intentFilters = packageActivities.get(i).intents;
13478                if (intentFilters != null && intentFilters.size() > 0) {
13479                    PackageParser.ActivityIntentInfo[] array =
13480                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13481                    intentFilters.toArray(array);
13482                    listCut.add(array);
13483                }
13484            }
13485            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13486        }
13487
13488        /**
13489         * Finds a privileged activity that matches the specified activity names.
13490         */
13491        private PackageParser.Activity findMatchingActivity(
13492                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13493            for (PackageParser.Activity sysActivity : activityList) {
13494                if (sysActivity.info.name.equals(activityInfo.name)) {
13495                    return sysActivity;
13496                }
13497                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13498                    return sysActivity;
13499                }
13500                if (sysActivity.info.targetActivity != null) {
13501                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13502                        return sysActivity;
13503                    }
13504                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13505                        return sysActivity;
13506                    }
13507                }
13508            }
13509            return null;
13510        }
13511
13512        public class IterGenerator<E> {
13513            public Iterator<E> generate(ActivityIntentInfo info) {
13514                return null;
13515            }
13516        }
13517
13518        public class ActionIterGenerator extends IterGenerator<String> {
13519            @Override
13520            public Iterator<String> generate(ActivityIntentInfo info) {
13521                return info.actionsIterator();
13522            }
13523        }
13524
13525        public class CategoriesIterGenerator extends IterGenerator<String> {
13526            @Override
13527            public Iterator<String> generate(ActivityIntentInfo info) {
13528                return info.categoriesIterator();
13529            }
13530        }
13531
13532        public class SchemesIterGenerator extends IterGenerator<String> {
13533            @Override
13534            public Iterator<String> generate(ActivityIntentInfo info) {
13535                return info.schemesIterator();
13536            }
13537        }
13538
13539        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13540            @Override
13541            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13542                return info.authoritiesIterator();
13543            }
13544        }
13545
13546        /**
13547         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13548         * MODIFIED. Do not pass in a list that should not be changed.
13549         */
13550        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13551                IterGenerator<T> generator, Iterator<T> searchIterator) {
13552            // loop through the set of actions; every one must be found in the intent filter
13553            while (searchIterator.hasNext()) {
13554                // we must have at least one filter in the list to consider a match
13555                if (intentList.size() == 0) {
13556                    break;
13557                }
13558
13559                final T searchAction = searchIterator.next();
13560
13561                // loop through the set of intent filters
13562                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13563                while (intentIter.hasNext()) {
13564                    final ActivityIntentInfo intentInfo = intentIter.next();
13565                    boolean selectionFound = false;
13566
13567                    // loop through the intent filter's selection criteria; at least one
13568                    // of them must match the searched criteria
13569                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13570                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13571                        final T intentSelection = intentSelectionIter.next();
13572                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13573                            selectionFound = true;
13574                            break;
13575                        }
13576                    }
13577
13578                    // the selection criteria wasn't found in this filter's set; this filter
13579                    // is not a potential match
13580                    if (!selectionFound) {
13581                        intentIter.remove();
13582                    }
13583                }
13584            }
13585        }
13586
13587        private boolean isProtectedAction(ActivityIntentInfo filter) {
13588            final Iterator<String> actionsIter = filter.actionsIterator();
13589            while (actionsIter != null && actionsIter.hasNext()) {
13590                final String filterAction = actionsIter.next();
13591                if (PROTECTED_ACTIONS.contains(filterAction)) {
13592                    return true;
13593                }
13594            }
13595            return false;
13596        }
13597
13598        /**
13599         * Adjusts the priority of the given intent filter according to policy.
13600         * <p>
13601         * <ul>
13602         * <li>The priority for non privileged applications is capped to '0'</li>
13603         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13604         * <li>The priority for unbundled updates to privileged applications is capped to the
13605         *      priority defined on the system partition</li>
13606         * </ul>
13607         * <p>
13608         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13609         * allowed to obtain any priority on any action.
13610         */
13611        private void adjustPriority(
13612                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13613            // nothing to do; priority is fine as-is
13614            if (intent.getPriority() <= 0) {
13615                return;
13616            }
13617
13618            final ActivityInfo activityInfo = intent.activity.info;
13619            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13620
13621            final boolean privilegedApp =
13622                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13623            if (!privilegedApp) {
13624                // non-privileged applications can never define a priority >0
13625                if (DEBUG_FILTERS) {
13626                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13627                            + " package: " + applicationInfo.packageName
13628                            + " activity: " + intent.activity.className
13629                            + " origPrio: " + intent.getPriority());
13630                }
13631                intent.setPriority(0);
13632                return;
13633            }
13634
13635            if (systemActivities == null) {
13636                // the system package is not disabled; we're parsing the system partition
13637                if (isProtectedAction(intent)) {
13638                    if (mDeferProtectedFilters) {
13639                        // We can't deal with these just yet. No component should ever obtain a
13640                        // >0 priority for a protected actions, with ONE exception -- the setup
13641                        // wizard. The setup wizard, however, cannot be known until we're able to
13642                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13643                        // until all intent filters have been processed. Chicken, meet egg.
13644                        // Let the filter temporarily have a high priority and rectify the
13645                        // priorities after all system packages have been scanned.
13646                        mProtectedFilters.add(intent);
13647                        if (DEBUG_FILTERS) {
13648                            Slog.i(TAG, "Protected action; save for later;"
13649                                    + " package: " + applicationInfo.packageName
13650                                    + " activity: " + intent.activity.className
13651                                    + " origPrio: " + intent.getPriority());
13652                        }
13653                        return;
13654                    } else {
13655                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13656                            Slog.i(TAG, "No setup wizard;"
13657                                + " All protected intents capped to priority 0");
13658                        }
13659                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13660                            if (DEBUG_FILTERS) {
13661                                Slog.i(TAG, "Found setup wizard;"
13662                                    + " allow priority " + intent.getPriority() + ";"
13663                                    + " package: " + intent.activity.info.packageName
13664                                    + " activity: " + intent.activity.className
13665                                    + " priority: " + intent.getPriority());
13666                            }
13667                            // setup wizard gets whatever it wants
13668                            return;
13669                        }
13670                        if (DEBUG_FILTERS) {
13671                            Slog.i(TAG, "Protected action; cap priority to 0;"
13672                                    + " package: " + intent.activity.info.packageName
13673                                    + " activity: " + intent.activity.className
13674                                    + " origPrio: " + intent.getPriority());
13675                        }
13676                        intent.setPriority(0);
13677                        return;
13678                    }
13679                }
13680                // privileged apps on the system image get whatever priority they request
13681                return;
13682            }
13683
13684            // privileged app unbundled update ... try to find the same activity
13685            final PackageParser.Activity foundActivity =
13686                    findMatchingActivity(systemActivities, activityInfo);
13687            if (foundActivity == null) {
13688                // this is a new activity; it cannot obtain >0 priority
13689                if (DEBUG_FILTERS) {
13690                    Slog.i(TAG, "New activity; cap priority to 0;"
13691                            + " package: " + applicationInfo.packageName
13692                            + " activity: " + intent.activity.className
13693                            + " origPrio: " + intent.getPriority());
13694                }
13695                intent.setPriority(0);
13696                return;
13697            }
13698
13699            // found activity, now check for filter equivalence
13700
13701            // a shallow copy is enough; we modify the list, not its contents
13702            final List<ActivityIntentInfo> intentListCopy =
13703                    new ArrayList<>(foundActivity.intents);
13704            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13705
13706            // find matching action subsets
13707            final Iterator<String> actionsIterator = intent.actionsIterator();
13708            if (actionsIterator != null) {
13709                getIntentListSubset(
13710                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13711                if (intentListCopy.size() == 0) {
13712                    // no more intents to match; we're not equivalent
13713                    if (DEBUG_FILTERS) {
13714                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13715                                + " package: " + applicationInfo.packageName
13716                                + " activity: " + intent.activity.className
13717                                + " origPrio: " + intent.getPriority());
13718                    }
13719                    intent.setPriority(0);
13720                    return;
13721                }
13722            }
13723
13724            // find matching category subsets
13725            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13726            if (categoriesIterator != null) {
13727                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13728                        categoriesIterator);
13729                if (intentListCopy.size() == 0) {
13730                    // no more intents to match; we're not equivalent
13731                    if (DEBUG_FILTERS) {
13732                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13733                                + " package: " + applicationInfo.packageName
13734                                + " activity: " + intent.activity.className
13735                                + " origPrio: " + intent.getPriority());
13736                    }
13737                    intent.setPriority(0);
13738                    return;
13739                }
13740            }
13741
13742            // find matching schemes subsets
13743            final Iterator<String> schemesIterator = intent.schemesIterator();
13744            if (schemesIterator != null) {
13745                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13746                        schemesIterator);
13747                if (intentListCopy.size() == 0) {
13748                    // no more intents to match; we're not equivalent
13749                    if (DEBUG_FILTERS) {
13750                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13751                                + " package: " + applicationInfo.packageName
13752                                + " activity: " + intent.activity.className
13753                                + " origPrio: " + intent.getPriority());
13754                    }
13755                    intent.setPriority(0);
13756                    return;
13757                }
13758            }
13759
13760            // find matching authorities subsets
13761            final Iterator<IntentFilter.AuthorityEntry>
13762                    authoritiesIterator = intent.authoritiesIterator();
13763            if (authoritiesIterator != null) {
13764                getIntentListSubset(intentListCopy,
13765                        new AuthoritiesIterGenerator(),
13766                        authoritiesIterator);
13767                if (intentListCopy.size() == 0) {
13768                    // no more intents to match; we're not equivalent
13769                    if (DEBUG_FILTERS) {
13770                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13771                                + " package: " + applicationInfo.packageName
13772                                + " activity: " + intent.activity.className
13773                                + " origPrio: " + intent.getPriority());
13774                    }
13775                    intent.setPriority(0);
13776                    return;
13777                }
13778            }
13779
13780            // we found matching filter(s); app gets the max priority of all intents
13781            int cappedPriority = 0;
13782            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13783                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13784            }
13785            if (intent.getPriority() > cappedPriority) {
13786                if (DEBUG_FILTERS) {
13787                    Slog.i(TAG, "Found matching filter(s);"
13788                            + " cap priority to " + cappedPriority + ";"
13789                            + " package: " + applicationInfo.packageName
13790                            + " activity: " + intent.activity.className
13791                            + " origPrio: " + intent.getPriority());
13792                }
13793                intent.setPriority(cappedPriority);
13794                return;
13795            }
13796            // all this for nothing; the requested priority was <= what was on the system
13797        }
13798
13799        public final void addActivity(PackageParser.Activity a, String type) {
13800            mActivities.put(a.getComponentName(), a);
13801            if (DEBUG_SHOW_INFO)
13802                Log.v(
13803                TAG, "  " + type + " " +
13804                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13805            if (DEBUG_SHOW_INFO)
13806                Log.v(TAG, "    Class=" + a.info.name);
13807            final int NI = a.intents.size();
13808            for (int j=0; j<NI; j++) {
13809                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13810                if ("activity".equals(type)) {
13811                    final PackageSetting ps =
13812                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13813                    final List<PackageParser.Activity> systemActivities =
13814                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13815                    adjustPriority(systemActivities, intent);
13816                }
13817                if (DEBUG_SHOW_INFO) {
13818                    Log.v(TAG, "    IntentFilter:");
13819                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13820                }
13821                if (!intent.debugCheck()) {
13822                    Log.w(TAG, "==> For Activity " + a.info.name);
13823                }
13824                addFilter(intent);
13825            }
13826        }
13827
13828        public final void removeActivity(PackageParser.Activity a, String type) {
13829            mActivities.remove(a.getComponentName());
13830            if (DEBUG_SHOW_INFO) {
13831                Log.v(TAG, "  " + type + " "
13832                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13833                                : a.info.name) + ":");
13834                Log.v(TAG, "    Class=" + a.info.name);
13835            }
13836            final int NI = a.intents.size();
13837            for (int j=0; j<NI; j++) {
13838                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13839                if (DEBUG_SHOW_INFO) {
13840                    Log.v(TAG, "    IntentFilter:");
13841                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13842                }
13843                removeFilter(intent);
13844            }
13845        }
13846
13847        @Override
13848        protected boolean allowFilterResult(
13849                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13850            ActivityInfo filterAi = filter.activity.info;
13851            for (int i=dest.size()-1; i>=0; i--) {
13852                ActivityInfo destAi = dest.get(i).activityInfo;
13853                if (destAi.name == filterAi.name
13854                        && destAi.packageName == filterAi.packageName) {
13855                    return false;
13856                }
13857            }
13858            return true;
13859        }
13860
13861        @Override
13862        protected ActivityIntentInfo[] newArray(int size) {
13863            return new ActivityIntentInfo[size];
13864        }
13865
13866        @Override
13867        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13868            if (!sUserManager.exists(userId)) return true;
13869            PackageParser.Package p = filter.activity.owner;
13870            if (p != null) {
13871                PackageSetting ps = (PackageSetting)p.mExtras;
13872                if (ps != null) {
13873                    // System apps are never considered stopped for purposes of
13874                    // filtering, because there may be no way for the user to
13875                    // actually re-launch them.
13876                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13877                            && ps.getStopped(userId);
13878                }
13879            }
13880            return false;
13881        }
13882
13883        @Override
13884        protected boolean isPackageForFilter(String packageName,
13885                PackageParser.ActivityIntentInfo info) {
13886            return packageName.equals(info.activity.owner.packageName);
13887        }
13888
13889        @Override
13890        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13891                int match, int userId) {
13892            if (!sUserManager.exists(userId)) return null;
13893            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13894                return null;
13895            }
13896            final PackageParser.Activity activity = info.activity;
13897            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13898            if (ps == null) {
13899                return null;
13900            }
13901            final PackageUserState userState = ps.readUserState(userId);
13902            ActivityInfo ai =
13903                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13904            if (ai == null) {
13905                return null;
13906            }
13907            final boolean matchExplicitlyVisibleOnly =
13908                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13909            final boolean matchVisibleToInstantApp =
13910                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13911            final boolean componentVisible =
13912                    matchVisibleToInstantApp
13913                    && info.isVisibleToInstantApp()
13914                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13915            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13916            // throw out filters that aren't visible to ephemeral apps
13917            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13918                return null;
13919            }
13920            // throw out instant app filters if we're not explicitly requesting them
13921            if (!matchInstantApp && userState.instantApp) {
13922                return null;
13923            }
13924            // throw out instant app filters if updates are available; will trigger
13925            // instant app resolution
13926            if (userState.instantApp && ps.isUpdateAvailable()) {
13927                return null;
13928            }
13929            final ResolveInfo res = new ResolveInfo();
13930            res.activityInfo = ai;
13931            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13932                res.filter = info;
13933            }
13934            if (info != null) {
13935                res.handleAllWebDataURI = info.handleAllWebDataURI();
13936            }
13937            res.priority = info.getPriority();
13938            res.preferredOrder = activity.owner.mPreferredOrder;
13939            //System.out.println("Result: " + res.activityInfo.className +
13940            //                   " = " + res.priority);
13941            res.match = match;
13942            res.isDefault = info.hasDefault;
13943            res.labelRes = info.labelRes;
13944            res.nonLocalizedLabel = info.nonLocalizedLabel;
13945            if (userNeedsBadging(userId)) {
13946                res.noResourceId = true;
13947            } else {
13948                res.icon = info.icon;
13949            }
13950            res.iconResourceId = info.icon;
13951            res.system = res.activityInfo.applicationInfo.isSystemApp();
13952            res.isInstantAppAvailable = userState.instantApp;
13953            return res;
13954        }
13955
13956        @Override
13957        protected void sortResults(List<ResolveInfo> results) {
13958            Collections.sort(results, mResolvePrioritySorter);
13959        }
13960
13961        @Override
13962        protected void dumpFilter(PrintWriter out, String prefix,
13963                PackageParser.ActivityIntentInfo filter) {
13964            out.print(prefix); out.print(
13965                    Integer.toHexString(System.identityHashCode(filter.activity)));
13966                    out.print(' ');
13967                    filter.activity.printComponentShortName(out);
13968                    out.print(" filter ");
13969                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13970        }
13971
13972        @Override
13973        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13974            return filter.activity;
13975        }
13976
13977        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13978            PackageParser.Activity activity = (PackageParser.Activity)label;
13979            out.print(prefix); out.print(
13980                    Integer.toHexString(System.identityHashCode(activity)));
13981                    out.print(' ');
13982                    activity.printComponentShortName(out);
13983            if (count > 1) {
13984                out.print(" ("); out.print(count); out.print(" filters)");
13985            }
13986            out.println();
13987        }
13988
13989        // Keys are String (activity class name), values are Activity.
13990        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13991                = new ArrayMap<ComponentName, PackageParser.Activity>();
13992        private int mFlags;
13993    }
13994
13995    private final class ServiceIntentResolver
13996            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13997        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13998                boolean defaultOnly, int userId) {
13999            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14000            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14001        }
14002
14003        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14004                int userId) {
14005            if (!sUserManager.exists(userId)) return null;
14006            mFlags = flags;
14007            return super.queryIntent(intent, resolvedType,
14008                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14009                    userId);
14010        }
14011
14012        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14013                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14014            if (!sUserManager.exists(userId)) return null;
14015            if (packageServices == null) {
14016                return null;
14017            }
14018            mFlags = flags;
14019            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14020            final int N = packageServices.size();
14021            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14022                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14023
14024            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14025            for (int i = 0; i < N; ++i) {
14026                intentFilters = packageServices.get(i).intents;
14027                if (intentFilters != null && intentFilters.size() > 0) {
14028                    PackageParser.ServiceIntentInfo[] array =
14029                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14030                    intentFilters.toArray(array);
14031                    listCut.add(array);
14032                }
14033            }
14034            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14035        }
14036
14037        public final void addService(PackageParser.Service s) {
14038            mServices.put(s.getComponentName(), s);
14039            if (DEBUG_SHOW_INFO) {
14040                Log.v(TAG, "  "
14041                        + (s.info.nonLocalizedLabel != null
14042                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14043                Log.v(TAG, "    Class=" + s.info.name);
14044            }
14045            final int NI = s.intents.size();
14046            int j;
14047            for (j=0; j<NI; j++) {
14048                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14049                if (DEBUG_SHOW_INFO) {
14050                    Log.v(TAG, "    IntentFilter:");
14051                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14052                }
14053                if (!intent.debugCheck()) {
14054                    Log.w(TAG, "==> For Service " + s.info.name);
14055                }
14056                addFilter(intent);
14057            }
14058        }
14059
14060        public final void removeService(PackageParser.Service s) {
14061            mServices.remove(s.getComponentName());
14062            if (DEBUG_SHOW_INFO) {
14063                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14064                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14065                Log.v(TAG, "    Class=" + s.info.name);
14066            }
14067            final int NI = s.intents.size();
14068            int j;
14069            for (j=0; j<NI; j++) {
14070                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14071                if (DEBUG_SHOW_INFO) {
14072                    Log.v(TAG, "    IntentFilter:");
14073                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14074                }
14075                removeFilter(intent);
14076            }
14077        }
14078
14079        @Override
14080        protected boolean allowFilterResult(
14081                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14082            ServiceInfo filterSi = filter.service.info;
14083            for (int i=dest.size()-1; i>=0; i--) {
14084                ServiceInfo destAi = dest.get(i).serviceInfo;
14085                if (destAi.name == filterSi.name
14086                        && destAi.packageName == filterSi.packageName) {
14087                    return false;
14088                }
14089            }
14090            return true;
14091        }
14092
14093        @Override
14094        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14095            return new PackageParser.ServiceIntentInfo[size];
14096        }
14097
14098        @Override
14099        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14100            if (!sUserManager.exists(userId)) return true;
14101            PackageParser.Package p = filter.service.owner;
14102            if (p != null) {
14103                PackageSetting ps = (PackageSetting)p.mExtras;
14104                if (ps != null) {
14105                    // System apps are never considered stopped for purposes of
14106                    // filtering, because there may be no way for the user to
14107                    // actually re-launch them.
14108                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14109                            && ps.getStopped(userId);
14110                }
14111            }
14112            return false;
14113        }
14114
14115        @Override
14116        protected boolean isPackageForFilter(String packageName,
14117                PackageParser.ServiceIntentInfo info) {
14118            return packageName.equals(info.service.owner.packageName);
14119        }
14120
14121        @Override
14122        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14123                int match, int userId) {
14124            if (!sUserManager.exists(userId)) return null;
14125            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14126            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14127                return null;
14128            }
14129            final PackageParser.Service service = info.service;
14130            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14131            if (ps == null) {
14132                return null;
14133            }
14134            final PackageUserState userState = ps.readUserState(userId);
14135            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14136                    userState, userId);
14137            if (si == null) {
14138                return null;
14139            }
14140            final boolean matchVisibleToInstantApp =
14141                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14142            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14143            // throw out filters that aren't visible to ephemeral apps
14144            if (matchVisibleToInstantApp
14145                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14146                return null;
14147            }
14148            // throw out ephemeral filters if we're not explicitly requesting them
14149            if (!isInstantApp && userState.instantApp) {
14150                return null;
14151            }
14152            // throw out instant app filters if updates are available; will trigger
14153            // instant app resolution
14154            if (userState.instantApp && ps.isUpdateAvailable()) {
14155                return null;
14156            }
14157            final ResolveInfo res = new ResolveInfo();
14158            res.serviceInfo = si;
14159            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14160                res.filter = filter;
14161            }
14162            res.priority = info.getPriority();
14163            res.preferredOrder = service.owner.mPreferredOrder;
14164            res.match = match;
14165            res.isDefault = info.hasDefault;
14166            res.labelRes = info.labelRes;
14167            res.nonLocalizedLabel = info.nonLocalizedLabel;
14168            res.icon = info.icon;
14169            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14170            return res;
14171        }
14172
14173        @Override
14174        protected void sortResults(List<ResolveInfo> results) {
14175            Collections.sort(results, mResolvePrioritySorter);
14176        }
14177
14178        @Override
14179        protected void dumpFilter(PrintWriter out, String prefix,
14180                PackageParser.ServiceIntentInfo filter) {
14181            out.print(prefix); out.print(
14182                    Integer.toHexString(System.identityHashCode(filter.service)));
14183                    out.print(' ');
14184                    filter.service.printComponentShortName(out);
14185                    out.print(" filter ");
14186                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14187        }
14188
14189        @Override
14190        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14191            return filter.service;
14192        }
14193
14194        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14195            PackageParser.Service service = (PackageParser.Service)label;
14196            out.print(prefix); out.print(
14197                    Integer.toHexString(System.identityHashCode(service)));
14198                    out.print(' ');
14199                    service.printComponentShortName(out);
14200            if (count > 1) {
14201                out.print(" ("); out.print(count); out.print(" filters)");
14202            }
14203            out.println();
14204        }
14205
14206//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14207//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14208//            final List<ResolveInfo> retList = Lists.newArrayList();
14209//            while (i.hasNext()) {
14210//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14211//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14212//                    retList.add(resolveInfo);
14213//                }
14214//            }
14215//            return retList;
14216//        }
14217
14218        // Keys are String (activity class name), values are Activity.
14219        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14220                = new ArrayMap<ComponentName, PackageParser.Service>();
14221        private int mFlags;
14222    }
14223
14224    private final class ProviderIntentResolver
14225            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14226        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14227                boolean defaultOnly, int userId) {
14228            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14229            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14230        }
14231
14232        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14233                int userId) {
14234            if (!sUserManager.exists(userId))
14235                return null;
14236            mFlags = flags;
14237            return super.queryIntent(intent, resolvedType,
14238                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14239                    userId);
14240        }
14241
14242        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14243                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14244            if (!sUserManager.exists(userId))
14245                return null;
14246            if (packageProviders == null) {
14247                return null;
14248            }
14249            mFlags = flags;
14250            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14251            final int N = packageProviders.size();
14252            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14253                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14254
14255            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14256            for (int i = 0; i < N; ++i) {
14257                intentFilters = packageProviders.get(i).intents;
14258                if (intentFilters != null && intentFilters.size() > 0) {
14259                    PackageParser.ProviderIntentInfo[] array =
14260                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14261                    intentFilters.toArray(array);
14262                    listCut.add(array);
14263                }
14264            }
14265            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14266        }
14267
14268        public final void addProvider(PackageParser.Provider p) {
14269            if (mProviders.containsKey(p.getComponentName())) {
14270                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14271                return;
14272            }
14273
14274            mProviders.put(p.getComponentName(), p);
14275            if (DEBUG_SHOW_INFO) {
14276                Log.v(TAG, "  "
14277                        + (p.info.nonLocalizedLabel != null
14278                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14279                Log.v(TAG, "    Class=" + p.info.name);
14280            }
14281            final int NI = p.intents.size();
14282            int j;
14283            for (j = 0; j < NI; j++) {
14284                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14285                if (DEBUG_SHOW_INFO) {
14286                    Log.v(TAG, "    IntentFilter:");
14287                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14288                }
14289                if (!intent.debugCheck()) {
14290                    Log.w(TAG, "==> For Provider " + p.info.name);
14291                }
14292                addFilter(intent);
14293            }
14294        }
14295
14296        public final void removeProvider(PackageParser.Provider p) {
14297            mProviders.remove(p.getComponentName());
14298            if (DEBUG_SHOW_INFO) {
14299                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14300                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14301                Log.v(TAG, "    Class=" + p.info.name);
14302            }
14303            final int NI = p.intents.size();
14304            int j;
14305            for (j = 0; j < NI; j++) {
14306                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14307                if (DEBUG_SHOW_INFO) {
14308                    Log.v(TAG, "    IntentFilter:");
14309                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14310                }
14311                removeFilter(intent);
14312            }
14313        }
14314
14315        @Override
14316        protected boolean allowFilterResult(
14317                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14318            ProviderInfo filterPi = filter.provider.info;
14319            for (int i = dest.size() - 1; i >= 0; i--) {
14320                ProviderInfo destPi = dest.get(i).providerInfo;
14321                if (destPi.name == filterPi.name
14322                        && destPi.packageName == filterPi.packageName) {
14323                    return false;
14324                }
14325            }
14326            return true;
14327        }
14328
14329        @Override
14330        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14331            return new PackageParser.ProviderIntentInfo[size];
14332        }
14333
14334        @Override
14335        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14336            if (!sUserManager.exists(userId))
14337                return true;
14338            PackageParser.Package p = filter.provider.owner;
14339            if (p != null) {
14340                PackageSetting ps = (PackageSetting) p.mExtras;
14341                if (ps != null) {
14342                    // System apps are never considered stopped for purposes of
14343                    // filtering, because there may be no way for the user to
14344                    // actually re-launch them.
14345                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14346                            && ps.getStopped(userId);
14347                }
14348            }
14349            return false;
14350        }
14351
14352        @Override
14353        protected boolean isPackageForFilter(String packageName,
14354                PackageParser.ProviderIntentInfo info) {
14355            return packageName.equals(info.provider.owner.packageName);
14356        }
14357
14358        @Override
14359        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14360                int match, int userId) {
14361            if (!sUserManager.exists(userId))
14362                return null;
14363            final PackageParser.ProviderIntentInfo info = filter;
14364            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14365                return null;
14366            }
14367            final PackageParser.Provider provider = info.provider;
14368            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14369            if (ps == null) {
14370                return null;
14371            }
14372            final PackageUserState userState = ps.readUserState(userId);
14373            final boolean matchVisibleToInstantApp =
14374                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14375            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14376            // throw out filters that aren't visible to instant applications
14377            if (matchVisibleToInstantApp
14378                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14379                return null;
14380            }
14381            // throw out instant application filters if we're not explicitly requesting them
14382            if (!isInstantApp && userState.instantApp) {
14383                return null;
14384            }
14385            // throw out instant application filters if updates are available; will trigger
14386            // instant application resolution
14387            if (userState.instantApp && ps.isUpdateAvailable()) {
14388                return null;
14389            }
14390            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14391                    userState, userId);
14392            if (pi == null) {
14393                return null;
14394            }
14395            final ResolveInfo res = new ResolveInfo();
14396            res.providerInfo = pi;
14397            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14398                res.filter = filter;
14399            }
14400            res.priority = info.getPriority();
14401            res.preferredOrder = provider.owner.mPreferredOrder;
14402            res.match = match;
14403            res.isDefault = info.hasDefault;
14404            res.labelRes = info.labelRes;
14405            res.nonLocalizedLabel = info.nonLocalizedLabel;
14406            res.icon = info.icon;
14407            res.system = res.providerInfo.applicationInfo.isSystemApp();
14408            return res;
14409        }
14410
14411        @Override
14412        protected void sortResults(List<ResolveInfo> results) {
14413            Collections.sort(results, mResolvePrioritySorter);
14414        }
14415
14416        @Override
14417        protected void dumpFilter(PrintWriter out, String prefix,
14418                PackageParser.ProviderIntentInfo filter) {
14419            out.print(prefix);
14420            out.print(
14421                    Integer.toHexString(System.identityHashCode(filter.provider)));
14422            out.print(' ');
14423            filter.provider.printComponentShortName(out);
14424            out.print(" filter ");
14425            out.println(Integer.toHexString(System.identityHashCode(filter)));
14426        }
14427
14428        @Override
14429        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14430            return filter.provider;
14431        }
14432
14433        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14434            PackageParser.Provider provider = (PackageParser.Provider)label;
14435            out.print(prefix); out.print(
14436                    Integer.toHexString(System.identityHashCode(provider)));
14437                    out.print(' ');
14438                    provider.printComponentShortName(out);
14439            if (count > 1) {
14440                out.print(" ("); out.print(count); out.print(" filters)");
14441            }
14442            out.println();
14443        }
14444
14445        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14446                = new ArrayMap<ComponentName, PackageParser.Provider>();
14447        private int mFlags;
14448    }
14449
14450    static final class EphemeralIntentResolver
14451            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14452        /**
14453         * The result that has the highest defined order. Ordering applies on a
14454         * per-package basis. Mapping is from package name to Pair of order and
14455         * EphemeralResolveInfo.
14456         * <p>
14457         * NOTE: This is implemented as a field variable for convenience and efficiency.
14458         * By having a field variable, we're able to track filter ordering as soon as
14459         * a non-zero order is defined. Otherwise, multiple loops across the result set
14460         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14461         * this needs to be contained entirely within {@link #filterResults}.
14462         */
14463        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14464
14465        @Override
14466        protected AuxiliaryResolveInfo[] newArray(int size) {
14467            return new AuxiliaryResolveInfo[size];
14468        }
14469
14470        @Override
14471        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14472            return true;
14473        }
14474
14475        @Override
14476        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14477                int userId) {
14478            if (!sUserManager.exists(userId)) {
14479                return null;
14480            }
14481            final String packageName = responseObj.resolveInfo.getPackageName();
14482            final Integer order = responseObj.getOrder();
14483            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14484                    mOrderResult.get(packageName);
14485            // ordering is enabled and this item's order isn't high enough
14486            if (lastOrderResult != null && lastOrderResult.first >= order) {
14487                return null;
14488            }
14489            final InstantAppResolveInfo res = responseObj.resolveInfo;
14490            if (order > 0) {
14491                // non-zero order, enable ordering
14492                mOrderResult.put(packageName, new Pair<>(order, res));
14493            }
14494            return responseObj;
14495        }
14496
14497        @Override
14498        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14499            // only do work if ordering is enabled [most of the time it won't be]
14500            if (mOrderResult.size() == 0) {
14501                return;
14502            }
14503            int resultSize = results.size();
14504            for (int i = 0; i < resultSize; i++) {
14505                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14506                final String packageName = info.getPackageName();
14507                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14508                if (savedInfo == null) {
14509                    // package doesn't having ordering
14510                    continue;
14511                }
14512                if (savedInfo.second == info) {
14513                    // circled back to the highest ordered item; remove from order list
14514                    mOrderResult.remove(packageName);
14515                    if (mOrderResult.size() == 0) {
14516                        // no more ordered items
14517                        break;
14518                    }
14519                    continue;
14520                }
14521                // item has a worse order, remove it from the result list
14522                results.remove(i);
14523                resultSize--;
14524                i--;
14525            }
14526        }
14527    }
14528
14529    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14530            new Comparator<ResolveInfo>() {
14531        public int compare(ResolveInfo r1, ResolveInfo r2) {
14532            int v1 = r1.priority;
14533            int v2 = r2.priority;
14534            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14535            if (v1 != v2) {
14536                return (v1 > v2) ? -1 : 1;
14537            }
14538            v1 = r1.preferredOrder;
14539            v2 = r2.preferredOrder;
14540            if (v1 != v2) {
14541                return (v1 > v2) ? -1 : 1;
14542            }
14543            if (r1.isDefault != r2.isDefault) {
14544                return r1.isDefault ? -1 : 1;
14545            }
14546            v1 = r1.match;
14547            v2 = r2.match;
14548            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14549            if (v1 != v2) {
14550                return (v1 > v2) ? -1 : 1;
14551            }
14552            if (r1.system != r2.system) {
14553                return r1.system ? -1 : 1;
14554            }
14555            if (r1.activityInfo != null) {
14556                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14557            }
14558            if (r1.serviceInfo != null) {
14559                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14560            }
14561            if (r1.providerInfo != null) {
14562                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14563            }
14564            return 0;
14565        }
14566    };
14567
14568    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14569            new Comparator<ProviderInfo>() {
14570        public int compare(ProviderInfo p1, ProviderInfo p2) {
14571            final int v1 = p1.initOrder;
14572            final int v2 = p2.initOrder;
14573            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14574        }
14575    };
14576
14577    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14578            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14579            final int[] userIds) {
14580        mHandler.post(new Runnable() {
14581            @Override
14582            public void run() {
14583                try {
14584                    final IActivityManager am = ActivityManager.getService();
14585                    if (am == null) return;
14586                    final int[] resolvedUserIds;
14587                    if (userIds == null) {
14588                        resolvedUserIds = am.getRunningUserIds();
14589                    } else {
14590                        resolvedUserIds = userIds;
14591                    }
14592                    for (int id : resolvedUserIds) {
14593                        final Intent intent = new Intent(action,
14594                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14595                        if (extras != null) {
14596                            intent.putExtras(extras);
14597                        }
14598                        if (targetPkg != null) {
14599                            intent.setPackage(targetPkg);
14600                        }
14601                        // Modify the UID when posting to other users
14602                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14603                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14604                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14605                            intent.putExtra(Intent.EXTRA_UID, uid);
14606                        }
14607                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14608                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14609                        if (DEBUG_BROADCASTS) {
14610                            RuntimeException here = new RuntimeException("here");
14611                            here.fillInStackTrace();
14612                            Slog.d(TAG, "Sending to user " + id + ": "
14613                                    + intent.toShortString(false, true, false, false)
14614                                    + " " + intent.getExtras(), here);
14615                        }
14616                        am.broadcastIntent(null, intent, null, finishedReceiver,
14617                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14618                                null, finishedReceiver != null, false, id);
14619                    }
14620                } catch (RemoteException ex) {
14621                }
14622            }
14623        });
14624    }
14625
14626    /**
14627     * Check if the external storage media is available. This is true if there
14628     * is a mounted external storage medium or if the external storage is
14629     * emulated.
14630     */
14631    private boolean isExternalMediaAvailable() {
14632        return mMediaMounted || Environment.isExternalStorageEmulated();
14633    }
14634
14635    @Override
14636    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14637        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14638            return null;
14639        }
14640        if (!isExternalMediaAvailable()) {
14641                // If the external storage is no longer mounted at this point,
14642                // the caller may not have been able to delete all of this
14643                // packages files and can not delete any more.  Bail.
14644            return null;
14645        }
14646        synchronized (mPackages) {
14647            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14648            if (lastPackage != null) {
14649                pkgs.remove(lastPackage);
14650            }
14651            if (pkgs.size() > 0) {
14652                return pkgs.get(0);
14653            }
14654        }
14655        return null;
14656    }
14657
14658    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14659        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14660                userId, andCode ? 1 : 0, packageName);
14661        if (mSystemReady) {
14662            msg.sendToTarget();
14663        } else {
14664            if (mPostSystemReadyMessages == null) {
14665                mPostSystemReadyMessages = new ArrayList<>();
14666            }
14667            mPostSystemReadyMessages.add(msg);
14668        }
14669    }
14670
14671    void startCleaningPackages() {
14672        // reader
14673        if (!isExternalMediaAvailable()) {
14674            return;
14675        }
14676        synchronized (mPackages) {
14677            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14678                return;
14679            }
14680        }
14681        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14682        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14683        IActivityManager am = ActivityManager.getService();
14684        if (am != null) {
14685            int dcsUid = -1;
14686            synchronized (mPackages) {
14687                if (!mDefaultContainerWhitelisted) {
14688                    mDefaultContainerWhitelisted = true;
14689                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14690                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14691                }
14692            }
14693            try {
14694                if (dcsUid > 0) {
14695                    am.backgroundWhitelistUid(dcsUid);
14696                }
14697                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14698                        UserHandle.USER_SYSTEM);
14699            } catch (RemoteException e) {
14700            }
14701        }
14702    }
14703
14704    @Override
14705    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14706            int installFlags, String installerPackageName, int userId) {
14707        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14708
14709        final int callingUid = Binder.getCallingUid();
14710        enforceCrossUserPermission(callingUid, userId,
14711                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14712
14713        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14714            try {
14715                if (observer != null) {
14716                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14717                }
14718            } catch (RemoteException re) {
14719            }
14720            return;
14721        }
14722
14723        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14724            installFlags |= PackageManager.INSTALL_FROM_ADB;
14725
14726        } else {
14727            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14728            // about installerPackageName.
14729
14730            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14731            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14732        }
14733
14734        UserHandle user;
14735        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14736            user = UserHandle.ALL;
14737        } else {
14738            user = new UserHandle(userId);
14739        }
14740
14741        // Only system components can circumvent runtime permissions when installing.
14742        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14743                && mContext.checkCallingOrSelfPermission(Manifest.permission
14744                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14745            throw new SecurityException("You need the "
14746                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14747                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14748        }
14749
14750        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14751                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14752            throw new IllegalArgumentException(
14753                    "New installs into ASEC containers no longer supported");
14754        }
14755
14756        final File originFile = new File(originPath);
14757        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14758
14759        final Message msg = mHandler.obtainMessage(INIT_COPY);
14760        final VerificationInfo verificationInfo = new VerificationInfo(
14761                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14762        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14763                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14764                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14765                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14766        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14767        msg.obj = params;
14768
14769        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14770                System.identityHashCode(msg.obj));
14771        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14772                System.identityHashCode(msg.obj));
14773
14774        mHandler.sendMessage(msg);
14775    }
14776
14777
14778    /**
14779     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14780     * it is acting on behalf on an enterprise or the user).
14781     *
14782     * Note that the ordering of the conditionals in this method is important. The checks we perform
14783     * are as follows, in this order:
14784     *
14785     * 1) If the install is being performed by a system app, we can trust the app to have set the
14786     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14787     *    what it is.
14788     * 2) If the install is being performed by a device or profile owner app, the install reason
14789     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14790     *    set the install reason correctly. If the app targets an older SDK version where install
14791     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14792     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14793     * 3) In all other cases, the install is being performed by a regular app that is neither part
14794     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14795     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14796     *    set to enterprise policy and if so, change it to unknown instead.
14797     */
14798    private int fixUpInstallReason(String installerPackageName, int installerUid,
14799            int installReason) {
14800        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14801                == PERMISSION_GRANTED) {
14802            // If the install is being performed by a system app, we trust that app to have set the
14803            // install reason correctly.
14804            return installReason;
14805        }
14806
14807        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14808            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14809        if (dpm != null) {
14810            ComponentName owner = null;
14811            try {
14812                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14813                if (owner == null) {
14814                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14815                }
14816            } catch (RemoteException e) {
14817            }
14818            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14819                // If the install is being performed by a device or profile owner, the install
14820                // reason should be enterprise policy.
14821                return PackageManager.INSTALL_REASON_POLICY;
14822            }
14823        }
14824
14825        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14826            // If the install is being performed by a regular app (i.e. neither system app nor
14827            // device or profile owner), we have no reason to believe that the app is acting on
14828            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14829            // change it to unknown instead.
14830            return PackageManager.INSTALL_REASON_UNKNOWN;
14831        }
14832
14833        // If the install is being performed by a regular app and the install reason was set to any
14834        // value but enterprise policy, leave the install reason unchanged.
14835        return installReason;
14836    }
14837
14838    void installStage(String packageName, File stagedDir, String stagedCid,
14839            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14840            String installerPackageName, int installerUid, UserHandle user,
14841            Certificate[][] certificates) {
14842        if (DEBUG_EPHEMERAL) {
14843            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14844                Slog.d(TAG, "Ephemeral install of " + packageName);
14845            }
14846        }
14847        final VerificationInfo verificationInfo = new VerificationInfo(
14848                sessionParams.originatingUri, sessionParams.referrerUri,
14849                sessionParams.originatingUid, installerUid);
14850
14851        final OriginInfo origin;
14852        if (stagedDir != null) {
14853            origin = OriginInfo.fromStagedFile(stagedDir);
14854        } else {
14855            origin = OriginInfo.fromStagedContainer(stagedCid);
14856        }
14857
14858        final Message msg = mHandler.obtainMessage(INIT_COPY);
14859        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14860                sessionParams.installReason);
14861        final InstallParams params = new InstallParams(origin, null, observer,
14862                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14863                verificationInfo, user, sessionParams.abiOverride,
14864                sessionParams.grantedRuntimePermissions, certificates, installReason);
14865        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14866        msg.obj = params;
14867
14868        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14869                System.identityHashCode(msg.obj));
14870        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14871                System.identityHashCode(msg.obj));
14872
14873        mHandler.sendMessage(msg);
14874    }
14875
14876    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14877            int userId) {
14878        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14879        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14880                false /*startReceiver*/, pkgSetting.appId, userId);
14881
14882        // Send a session commit broadcast
14883        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14884        info.installReason = pkgSetting.getInstallReason(userId);
14885        info.appPackageName = packageName;
14886        sendSessionCommitBroadcast(info, userId);
14887    }
14888
14889    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14890            boolean includeStopped, int appId, int... userIds) {
14891        if (ArrayUtils.isEmpty(userIds)) {
14892            return;
14893        }
14894        Bundle extras = new Bundle(1);
14895        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14896        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14897
14898        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14899                packageName, extras, 0, null, null, userIds);
14900        if (sendBootCompleted) {
14901            mHandler.post(() -> {
14902                        for (int userId : userIds) {
14903                            sendBootCompletedBroadcastToSystemApp(
14904                                    packageName, includeStopped, userId);
14905                        }
14906                    }
14907            );
14908        }
14909    }
14910
14911    /**
14912     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14913     * automatically without needing an explicit launch.
14914     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14915     */
14916    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14917            int userId) {
14918        // If user is not running, the app didn't miss any broadcast
14919        if (!mUserManagerInternal.isUserRunning(userId)) {
14920            return;
14921        }
14922        final IActivityManager am = ActivityManager.getService();
14923        try {
14924            // Deliver LOCKED_BOOT_COMPLETED first
14925            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14926                    .setPackage(packageName);
14927            if (includeStopped) {
14928                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14929            }
14930            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14931            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14932                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14933
14934            // Deliver BOOT_COMPLETED only if user is unlocked
14935            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14936                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14937                if (includeStopped) {
14938                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14939                }
14940                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14941                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14942            }
14943        } catch (RemoteException e) {
14944            throw e.rethrowFromSystemServer();
14945        }
14946    }
14947
14948    @Override
14949    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14950            int userId) {
14951        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14952        PackageSetting pkgSetting;
14953        final int callingUid = Binder.getCallingUid();
14954        enforceCrossUserPermission(callingUid, userId,
14955                true /* requireFullPermission */, true /* checkShell */,
14956                "setApplicationHiddenSetting for user " + userId);
14957
14958        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14959            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14960            return false;
14961        }
14962
14963        long callingId = Binder.clearCallingIdentity();
14964        try {
14965            boolean sendAdded = false;
14966            boolean sendRemoved = false;
14967            // writer
14968            synchronized (mPackages) {
14969                pkgSetting = mSettings.mPackages.get(packageName);
14970                if (pkgSetting == null) {
14971                    return false;
14972                }
14973                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14974                    return false;
14975                }
14976                // Do not allow "android" is being disabled
14977                if ("android".equals(packageName)) {
14978                    Slog.w(TAG, "Cannot hide package: android");
14979                    return false;
14980                }
14981                // Cannot hide static shared libs as they are considered
14982                // a part of the using app (emulating static linking). Also
14983                // static libs are installed always on internal storage.
14984                PackageParser.Package pkg = mPackages.get(packageName);
14985                if (pkg != null && pkg.staticSharedLibName != null) {
14986                    Slog.w(TAG, "Cannot hide package: " + packageName
14987                            + " providing static shared library: "
14988                            + pkg.staticSharedLibName);
14989                    return false;
14990                }
14991                // Only allow protected packages to hide themselves.
14992                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14993                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14994                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14995                    return false;
14996                }
14997
14998                if (pkgSetting.getHidden(userId) != hidden) {
14999                    pkgSetting.setHidden(hidden, userId);
15000                    mSettings.writePackageRestrictionsLPr(userId);
15001                    if (hidden) {
15002                        sendRemoved = true;
15003                    } else {
15004                        sendAdded = true;
15005                    }
15006                }
15007            }
15008            if (sendAdded) {
15009                sendPackageAddedForUser(packageName, pkgSetting, userId);
15010                return true;
15011            }
15012            if (sendRemoved) {
15013                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15014                        "hiding pkg");
15015                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15016                return true;
15017            }
15018        } finally {
15019            Binder.restoreCallingIdentity(callingId);
15020        }
15021        return false;
15022    }
15023
15024    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15025            int userId) {
15026        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15027        info.removedPackage = packageName;
15028        info.installerPackageName = pkgSetting.installerPackageName;
15029        info.removedUsers = new int[] {userId};
15030        info.broadcastUsers = new int[] {userId};
15031        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15032        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15033    }
15034
15035    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15036        if (pkgList.length > 0) {
15037            Bundle extras = new Bundle(1);
15038            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15039
15040            sendPackageBroadcast(
15041                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15042                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15043                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15044                    new int[] {userId});
15045        }
15046    }
15047
15048    /**
15049     * Returns true if application is not found or there was an error. Otherwise it returns
15050     * the hidden state of the package for the given user.
15051     */
15052    @Override
15053    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15054        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15055        final int callingUid = Binder.getCallingUid();
15056        enforceCrossUserPermission(callingUid, userId,
15057                true /* requireFullPermission */, false /* checkShell */,
15058                "getApplicationHidden for user " + userId);
15059        PackageSetting ps;
15060        long callingId = Binder.clearCallingIdentity();
15061        try {
15062            // writer
15063            synchronized (mPackages) {
15064                ps = mSettings.mPackages.get(packageName);
15065                if (ps == null) {
15066                    return true;
15067                }
15068                if (filterAppAccessLPr(ps, callingUid, userId)) {
15069                    return true;
15070                }
15071                return ps.getHidden(userId);
15072            }
15073        } finally {
15074            Binder.restoreCallingIdentity(callingId);
15075        }
15076    }
15077
15078    /**
15079     * @hide
15080     */
15081    @Override
15082    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15083            int installReason) {
15084        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15085                null);
15086        PackageSetting pkgSetting;
15087        final int callingUid = Binder.getCallingUid();
15088        enforceCrossUserPermission(callingUid, userId,
15089                true /* requireFullPermission */, true /* checkShell */,
15090                "installExistingPackage for user " + userId);
15091        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15092            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15093        }
15094
15095        long callingId = Binder.clearCallingIdentity();
15096        try {
15097            boolean installed = false;
15098            final boolean instantApp =
15099                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15100            final boolean fullApp =
15101                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15102
15103            // writer
15104            synchronized (mPackages) {
15105                pkgSetting = mSettings.mPackages.get(packageName);
15106                if (pkgSetting == null) {
15107                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15108                }
15109                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15110                    // only allow the existing package to be used if it's installed as a full
15111                    // application for at least one user
15112                    boolean installAllowed = false;
15113                    for (int checkUserId : sUserManager.getUserIds()) {
15114                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15115                        if (installAllowed) {
15116                            break;
15117                        }
15118                    }
15119                    if (!installAllowed) {
15120                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15121                    }
15122                }
15123                if (!pkgSetting.getInstalled(userId)) {
15124                    pkgSetting.setInstalled(true, userId);
15125                    pkgSetting.setHidden(false, userId);
15126                    pkgSetting.setInstallReason(installReason, userId);
15127                    mSettings.writePackageRestrictionsLPr(userId);
15128                    mSettings.writeKernelMappingLPr(pkgSetting);
15129                    installed = true;
15130                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15131                    // upgrade app from instant to full; we don't allow app downgrade
15132                    installed = true;
15133                }
15134                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15135            }
15136
15137            if (installed) {
15138                if (pkgSetting.pkg != null) {
15139                    synchronized (mInstallLock) {
15140                        // We don't need to freeze for a brand new install
15141                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15142                    }
15143                }
15144                sendPackageAddedForUser(packageName, pkgSetting, userId);
15145                synchronized (mPackages) {
15146                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15147                }
15148            }
15149        } finally {
15150            Binder.restoreCallingIdentity(callingId);
15151        }
15152
15153        return PackageManager.INSTALL_SUCCEEDED;
15154    }
15155
15156    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15157            boolean instantApp, boolean fullApp) {
15158        // no state specified; do nothing
15159        if (!instantApp && !fullApp) {
15160            return;
15161        }
15162        if (userId != UserHandle.USER_ALL) {
15163            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15164                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15165            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15166                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15167            }
15168        } else {
15169            for (int currentUserId : sUserManager.getUserIds()) {
15170                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15171                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15172                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15173                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15174                }
15175            }
15176        }
15177    }
15178
15179    boolean isUserRestricted(int userId, String restrictionKey) {
15180        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15181        if (restrictions.getBoolean(restrictionKey, false)) {
15182            Log.w(TAG, "User is restricted: " + restrictionKey);
15183            return true;
15184        }
15185        return false;
15186    }
15187
15188    @Override
15189    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15190            int userId) {
15191        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15192        final int callingUid = Binder.getCallingUid();
15193        enforceCrossUserPermission(callingUid, userId,
15194                true /* requireFullPermission */, true /* checkShell */,
15195                "setPackagesSuspended for user " + userId);
15196
15197        if (ArrayUtils.isEmpty(packageNames)) {
15198            return packageNames;
15199        }
15200
15201        // List of package names for whom the suspended state has changed.
15202        List<String> changedPackages = new ArrayList<>(packageNames.length);
15203        // List of package names for whom the suspended state is not set as requested in this
15204        // method.
15205        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15206        long callingId = Binder.clearCallingIdentity();
15207        try {
15208            for (int i = 0; i < packageNames.length; i++) {
15209                String packageName = packageNames[i];
15210                boolean changed = false;
15211                final int appId;
15212                synchronized (mPackages) {
15213                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15214                    if (pkgSetting == null
15215                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15216                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15217                                + "\". Skipping suspending/un-suspending.");
15218                        unactionedPackages.add(packageName);
15219                        continue;
15220                    }
15221                    appId = pkgSetting.appId;
15222                    if (pkgSetting.getSuspended(userId) != suspended) {
15223                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15224                            unactionedPackages.add(packageName);
15225                            continue;
15226                        }
15227                        pkgSetting.setSuspended(suspended, userId);
15228                        mSettings.writePackageRestrictionsLPr(userId);
15229                        changed = true;
15230                        changedPackages.add(packageName);
15231                    }
15232                }
15233
15234                if (changed && suspended) {
15235                    killApplication(packageName, UserHandle.getUid(userId, appId),
15236                            "suspending package");
15237                }
15238            }
15239        } finally {
15240            Binder.restoreCallingIdentity(callingId);
15241        }
15242
15243        if (!changedPackages.isEmpty()) {
15244            sendPackagesSuspendedForUser(changedPackages.toArray(
15245                    new String[changedPackages.size()]), userId, suspended);
15246        }
15247
15248        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15249    }
15250
15251    @Override
15252    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15253        final int callingUid = Binder.getCallingUid();
15254        enforceCrossUserPermission(callingUid, userId,
15255                true /* requireFullPermission */, false /* checkShell */,
15256                "isPackageSuspendedForUser for user " + userId);
15257        synchronized (mPackages) {
15258            final PackageSetting ps = mSettings.mPackages.get(packageName);
15259            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15260                throw new IllegalArgumentException("Unknown target package: " + packageName);
15261            }
15262            return ps.getSuspended(userId);
15263        }
15264    }
15265
15266    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15267        if (isPackageDeviceAdmin(packageName, userId)) {
15268            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15269                    + "\": has an active device admin");
15270            return false;
15271        }
15272
15273        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15274        if (packageName.equals(activeLauncherPackageName)) {
15275            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15276                    + "\": contains the active launcher");
15277            return false;
15278        }
15279
15280        if (packageName.equals(mRequiredInstallerPackage)) {
15281            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15282                    + "\": required for package installation");
15283            return false;
15284        }
15285
15286        if (packageName.equals(mRequiredUninstallerPackage)) {
15287            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15288                    + "\": required for package uninstallation");
15289            return false;
15290        }
15291
15292        if (packageName.equals(mRequiredVerifierPackage)) {
15293            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15294                    + "\": required for package verification");
15295            return false;
15296        }
15297
15298        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15299            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15300                    + "\": is the default dialer");
15301            return false;
15302        }
15303
15304        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15305            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15306                    + "\": protected package");
15307            return false;
15308        }
15309
15310        // Cannot suspend static shared libs as they are considered
15311        // a part of the using app (emulating static linking). Also
15312        // static libs are installed always on internal storage.
15313        PackageParser.Package pkg = mPackages.get(packageName);
15314        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15315            Slog.w(TAG, "Cannot suspend package: " + packageName
15316                    + " providing static shared library: "
15317                    + pkg.staticSharedLibName);
15318            return false;
15319        }
15320
15321        return true;
15322    }
15323
15324    private String getActiveLauncherPackageName(int userId) {
15325        Intent intent = new Intent(Intent.ACTION_MAIN);
15326        intent.addCategory(Intent.CATEGORY_HOME);
15327        ResolveInfo resolveInfo = resolveIntent(
15328                intent,
15329                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15330                PackageManager.MATCH_DEFAULT_ONLY,
15331                userId);
15332
15333        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15334    }
15335
15336    private String getDefaultDialerPackageName(int userId) {
15337        synchronized (mPackages) {
15338            return mSettings.getDefaultDialerPackageNameLPw(userId);
15339        }
15340    }
15341
15342    @Override
15343    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15344        mContext.enforceCallingOrSelfPermission(
15345                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15346                "Only package verification agents can verify applications");
15347
15348        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15349        final PackageVerificationResponse response = new PackageVerificationResponse(
15350                verificationCode, Binder.getCallingUid());
15351        msg.arg1 = id;
15352        msg.obj = response;
15353        mHandler.sendMessage(msg);
15354    }
15355
15356    @Override
15357    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15358            long millisecondsToDelay) {
15359        mContext.enforceCallingOrSelfPermission(
15360                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15361                "Only package verification agents can extend verification timeouts");
15362
15363        final PackageVerificationState state = mPendingVerification.get(id);
15364        final PackageVerificationResponse response = new PackageVerificationResponse(
15365                verificationCodeAtTimeout, Binder.getCallingUid());
15366
15367        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15368            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15369        }
15370        if (millisecondsToDelay < 0) {
15371            millisecondsToDelay = 0;
15372        }
15373        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15374                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15375            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15376        }
15377
15378        if ((state != null) && !state.timeoutExtended()) {
15379            state.extendTimeout();
15380
15381            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15382            msg.arg1 = id;
15383            msg.obj = response;
15384            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15385        }
15386    }
15387
15388    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15389            int verificationCode, UserHandle user) {
15390        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15391        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15392        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15393        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15394        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15395
15396        mContext.sendBroadcastAsUser(intent, user,
15397                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15398    }
15399
15400    private ComponentName matchComponentForVerifier(String packageName,
15401            List<ResolveInfo> receivers) {
15402        ActivityInfo targetReceiver = null;
15403
15404        final int NR = receivers.size();
15405        for (int i = 0; i < NR; i++) {
15406            final ResolveInfo info = receivers.get(i);
15407            if (info.activityInfo == null) {
15408                continue;
15409            }
15410
15411            if (packageName.equals(info.activityInfo.packageName)) {
15412                targetReceiver = info.activityInfo;
15413                break;
15414            }
15415        }
15416
15417        if (targetReceiver == null) {
15418            return null;
15419        }
15420
15421        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15422    }
15423
15424    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15425            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15426        if (pkgInfo.verifiers.length == 0) {
15427            return null;
15428        }
15429
15430        final int N = pkgInfo.verifiers.length;
15431        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15432        for (int i = 0; i < N; i++) {
15433            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15434
15435            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15436                    receivers);
15437            if (comp == null) {
15438                continue;
15439            }
15440
15441            final int verifierUid = getUidForVerifier(verifierInfo);
15442            if (verifierUid == -1) {
15443                continue;
15444            }
15445
15446            if (DEBUG_VERIFY) {
15447                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15448                        + " with the correct signature");
15449            }
15450            sufficientVerifiers.add(comp);
15451            verificationState.addSufficientVerifier(verifierUid);
15452        }
15453
15454        return sufficientVerifiers;
15455    }
15456
15457    private int getUidForVerifier(VerifierInfo verifierInfo) {
15458        synchronized (mPackages) {
15459            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15460            if (pkg == null) {
15461                return -1;
15462            } else if (pkg.mSignatures.length != 1) {
15463                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15464                        + " has more than one signature; ignoring");
15465                return -1;
15466            }
15467
15468            /*
15469             * If the public key of the package's signature does not match
15470             * our expected public key, then this is a different package and
15471             * we should skip.
15472             */
15473
15474            final byte[] expectedPublicKey;
15475            try {
15476                final Signature verifierSig = pkg.mSignatures[0];
15477                final PublicKey publicKey = verifierSig.getPublicKey();
15478                expectedPublicKey = publicKey.getEncoded();
15479            } catch (CertificateException e) {
15480                return -1;
15481            }
15482
15483            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15484
15485            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15486                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15487                        + " does not have the expected public key; ignoring");
15488                return -1;
15489            }
15490
15491            return pkg.applicationInfo.uid;
15492        }
15493    }
15494
15495    @Override
15496    public void finishPackageInstall(int token, boolean didLaunch) {
15497        enforceSystemOrRoot("Only the system is allowed to finish installs");
15498
15499        if (DEBUG_INSTALL) {
15500            Slog.v(TAG, "BM finishing package install for " + token);
15501        }
15502        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15503
15504        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15505        mHandler.sendMessage(msg);
15506    }
15507
15508    /**
15509     * Get the verification agent timeout.  Used for both the APK verifier and the
15510     * intent filter verifier.
15511     *
15512     * @return verification timeout in milliseconds
15513     */
15514    private long getVerificationTimeout() {
15515        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15516                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15517                DEFAULT_VERIFICATION_TIMEOUT);
15518    }
15519
15520    /**
15521     * Get the default verification agent response code.
15522     *
15523     * @return default verification response code
15524     */
15525    private int getDefaultVerificationResponse(UserHandle user) {
15526        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15527            return PackageManager.VERIFICATION_REJECT;
15528        }
15529        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15530                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15531                DEFAULT_VERIFICATION_RESPONSE);
15532    }
15533
15534    /**
15535     * Check whether or not package verification has been enabled.
15536     *
15537     * @return true if verification should be performed
15538     */
15539    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15540        if (!DEFAULT_VERIFY_ENABLE) {
15541            return false;
15542        }
15543
15544        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15545
15546        // Check if installing from ADB
15547        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15548            // Do not run verification in a test harness environment
15549            if (ActivityManager.isRunningInTestHarness()) {
15550                return false;
15551            }
15552            if (ensureVerifyAppsEnabled) {
15553                return true;
15554            }
15555            // Check if the developer does not want package verification for ADB installs
15556            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15557                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15558                return false;
15559            }
15560        } else {
15561            // only when not installed from ADB, skip verification for instant apps when
15562            // the installer and verifier are the same.
15563            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15564                if (mInstantAppInstallerActivity != null
15565                        && mInstantAppInstallerActivity.packageName.equals(
15566                                mRequiredVerifierPackage)) {
15567                    try {
15568                        mContext.getSystemService(AppOpsManager.class)
15569                                .checkPackage(installerUid, mRequiredVerifierPackage);
15570                        if (DEBUG_VERIFY) {
15571                            Slog.i(TAG, "disable verification for instant app");
15572                        }
15573                        return false;
15574                    } catch (SecurityException ignore) { }
15575                }
15576            }
15577        }
15578
15579        if (ensureVerifyAppsEnabled) {
15580            return true;
15581        }
15582
15583        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15584                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15585    }
15586
15587    @Override
15588    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15589            throws RemoteException {
15590        mContext.enforceCallingOrSelfPermission(
15591                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15592                "Only intentfilter verification agents can verify applications");
15593
15594        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15595        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15596                Binder.getCallingUid(), verificationCode, failedDomains);
15597        msg.arg1 = id;
15598        msg.obj = response;
15599        mHandler.sendMessage(msg);
15600    }
15601
15602    @Override
15603    public int getIntentVerificationStatus(String packageName, int userId) {
15604        final int callingUid = Binder.getCallingUid();
15605        if (UserHandle.getUserId(callingUid) != userId) {
15606            mContext.enforceCallingOrSelfPermission(
15607                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15608                    "getIntentVerificationStatus" + userId);
15609        }
15610        if (getInstantAppPackageName(callingUid) != null) {
15611            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15612        }
15613        synchronized (mPackages) {
15614            final PackageSetting ps = mSettings.mPackages.get(packageName);
15615            if (ps == null
15616                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15617                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15618            }
15619            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15620        }
15621    }
15622
15623    @Override
15624    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15625        mContext.enforceCallingOrSelfPermission(
15626                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15627
15628        boolean result = false;
15629        synchronized (mPackages) {
15630            final PackageSetting ps = mSettings.mPackages.get(packageName);
15631            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15632                return false;
15633            }
15634            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15635        }
15636        if (result) {
15637            scheduleWritePackageRestrictionsLocked(userId);
15638        }
15639        return result;
15640    }
15641
15642    @Override
15643    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15644            String packageName) {
15645        final int callingUid = Binder.getCallingUid();
15646        if (getInstantAppPackageName(callingUid) != null) {
15647            return ParceledListSlice.emptyList();
15648        }
15649        synchronized (mPackages) {
15650            final PackageSetting ps = mSettings.mPackages.get(packageName);
15651            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15652                return ParceledListSlice.emptyList();
15653            }
15654            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15655        }
15656    }
15657
15658    @Override
15659    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15660        if (TextUtils.isEmpty(packageName)) {
15661            return ParceledListSlice.emptyList();
15662        }
15663        final int callingUid = Binder.getCallingUid();
15664        final int callingUserId = UserHandle.getUserId(callingUid);
15665        synchronized (mPackages) {
15666            PackageParser.Package pkg = mPackages.get(packageName);
15667            if (pkg == null || pkg.activities == null) {
15668                return ParceledListSlice.emptyList();
15669            }
15670            if (pkg.mExtras == null) {
15671                return ParceledListSlice.emptyList();
15672            }
15673            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15674            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15675                return ParceledListSlice.emptyList();
15676            }
15677            final int count = pkg.activities.size();
15678            ArrayList<IntentFilter> result = new ArrayList<>();
15679            for (int n=0; n<count; n++) {
15680                PackageParser.Activity activity = pkg.activities.get(n);
15681                if (activity.intents != null && activity.intents.size() > 0) {
15682                    result.addAll(activity.intents);
15683                }
15684            }
15685            return new ParceledListSlice<>(result);
15686        }
15687    }
15688
15689    @Override
15690    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15691        mContext.enforceCallingOrSelfPermission(
15692                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15693        if (UserHandle.getCallingUserId() != userId) {
15694            mContext.enforceCallingOrSelfPermission(
15695                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15696        }
15697
15698        synchronized (mPackages) {
15699            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15700            if (packageName != null) {
15701                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15702                        packageName, userId);
15703            }
15704            return result;
15705        }
15706    }
15707
15708    @Override
15709    public String getDefaultBrowserPackageName(int userId) {
15710        if (UserHandle.getCallingUserId() != userId) {
15711            mContext.enforceCallingOrSelfPermission(
15712                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15713        }
15714        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15715            return null;
15716        }
15717        synchronized (mPackages) {
15718            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15719        }
15720    }
15721
15722    /**
15723     * Get the "allow unknown sources" setting.
15724     *
15725     * @return the current "allow unknown sources" setting
15726     */
15727    private int getUnknownSourcesSettings() {
15728        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15729                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15730                -1);
15731    }
15732
15733    @Override
15734    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15735        final int callingUid = Binder.getCallingUid();
15736        if (getInstantAppPackageName(callingUid) != null) {
15737            return;
15738        }
15739        // writer
15740        synchronized (mPackages) {
15741            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15742            if (targetPackageSetting == null
15743                    || filterAppAccessLPr(
15744                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15745                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15746            }
15747
15748            PackageSetting installerPackageSetting;
15749            if (installerPackageName != null) {
15750                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15751                if (installerPackageSetting == null) {
15752                    throw new IllegalArgumentException("Unknown installer package: "
15753                            + installerPackageName);
15754                }
15755            } else {
15756                installerPackageSetting = null;
15757            }
15758
15759            Signature[] callerSignature;
15760            Object obj = mSettings.getUserIdLPr(callingUid);
15761            if (obj != null) {
15762                if (obj instanceof SharedUserSetting) {
15763                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15764                } else if (obj instanceof PackageSetting) {
15765                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15766                } else {
15767                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15768                }
15769            } else {
15770                throw new SecurityException("Unknown calling UID: " + callingUid);
15771            }
15772
15773            // Verify: can't set installerPackageName to a package that is
15774            // not signed with the same cert as the caller.
15775            if (installerPackageSetting != null) {
15776                if (compareSignatures(callerSignature,
15777                        installerPackageSetting.signatures.mSignatures)
15778                        != PackageManager.SIGNATURE_MATCH) {
15779                    throw new SecurityException(
15780                            "Caller does not have same cert as new installer package "
15781                            + installerPackageName);
15782                }
15783            }
15784
15785            // Verify: if target already has an installer package, it must
15786            // be signed with the same cert as the caller.
15787            if (targetPackageSetting.installerPackageName != null) {
15788                PackageSetting setting = mSettings.mPackages.get(
15789                        targetPackageSetting.installerPackageName);
15790                // If the currently set package isn't valid, then it's always
15791                // okay to change it.
15792                if (setting != null) {
15793                    if (compareSignatures(callerSignature,
15794                            setting.signatures.mSignatures)
15795                            != PackageManager.SIGNATURE_MATCH) {
15796                        throw new SecurityException(
15797                                "Caller does not have same cert as old installer package "
15798                                + targetPackageSetting.installerPackageName);
15799                    }
15800                }
15801            }
15802
15803            // Okay!
15804            targetPackageSetting.installerPackageName = installerPackageName;
15805            if (installerPackageName != null) {
15806                mSettings.mInstallerPackages.add(installerPackageName);
15807            }
15808            scheduleWriteSettingsLocked();
15809        }
15810    }
15811
15812    @Override
15813    public void setApplicationCategoryHint(String packageName, int categoryHint,
15814            String callerPackageName) {
15815        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15816            throw new SecurityException("Instant applications don't have access to this method");
15817        }
15818        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15819                callerPackageName);
15820        synchronized (mPackages) {
15821            PackageSetting ps = mSettings.mPackages.get(packageName);
15822            if (ps == null) {
15823                throw new IllegalArgumentException("Unknown target package " + packageName);
15824            }
15825            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15826                throw new IllegalArgumentException("Unknown target package " + packageName);
15827            }
15828            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15829                throw new IllegalArgumentException("Calling package " + callerPackageName
15830                        + " is not installer for " + packageName);
15831            }
15832
15833            if (ps.categoryHint != categoryHint) {
15834                ps.categoryHint = categoryHint;
15835                scheduleWriteSettingsLocked();
15836            }
15837        }
15838    }
15839
15840    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15841        // Queue up an async operation since the package installation may take a little while.
15842        mHandler.post(new Runnable() {
15843            public void run() {
15844                mHandler.removeCallbacks(this);
15845                 // Result object to be returned
15846                PackageInstalledInfo res = new PackageInstalledInfo();
15847                res.setReturnCode(currentStatus);
15848                res.uid = -1;
15849                res.pkg = null;
15850                res.removedInfo = null;
15851                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15852                    args.doPreInstall(res.returnCode);
15853                    synchronized (mInstallLock) {
15854                        installPackageTracedLI(args, res);
15855                    }
15856                    args.doPostInstall(res.returnCode, res.uid);
15857                }
15858
15859                // A restore should be performed at this point if (a) the install
15860                // succeeded, (b) the operation is not an update, and (c) the new
15861                // package has not opted out of backup participation.
15862                final boolean update = res.removedInfo != null
15863                        && res.removedInfo.removedPackage != null;
15864                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15865                boolean doRestore = !update
15866                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15867
15868                // Set up the post-install work request bookkeeping.  This will be used
15869                // and cleaned up by the post-install event handling regardless of whether
15870                // there's a restore pass performed.  Token values are >= 1.
15871                int token;
15872                if (mNextInstallToken < 0) mNextInstallToken = 1;
15873                token = mNextInstallToken++;
15874
15875                PostInstallData data = new PostInstallData(args, res);
15876                mRunningInstalls.put(token, data);
15877                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15878
15879                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15880                    // Pass responsibility to the Backup Manager.  It will perform a
15881                    // restore if appropriate, then pass responsibility back to the
15882                    // Package Manager to run the post-install observer callbacks
15883                    // and broadcasts.
15884                    IBackupManager bm = IBackupManager.Stub.asInterface(
15885                            ServiceManager.getService(Context.BACKUP_SERVICE));
15886                    if (bm != null) {
15887                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15888                                + " to BM for possible restore");
15889                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15890                        try {
15891                            // TODO: http://b/22388012
15892                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15893                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15894                            } else {
15895                                doRestore = false;
15896                            }
15897                        } catch (RemoteException e) {
15898                            // can't happen; the backup manager is local
15899                        } catch (Exception e) {
15900                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15901                            doRestore = false;
15902                        }
15903                    } else {
15904                        Slog.e(TAG, "Backup Manager not found!");
15905                        doRestore = false;
15906                    }
15907                }
15908
15909                if (!doRestore) {
15910                    // No restore possible, or the Backup Manager was mysteriously not
15911                    // available -- just fire the post-install work request directly.
15912                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15913
15914                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15915
15916                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15917                    mHandler.sendMessage(msg);
15918                }
15919            }
15920        });
15921    }
15922
15923    /**
15924     * Callback from PackageSettings whenever an app is first transitioned out of the
15925     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15926     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15927     * here whether the app is the target of an ongoing install, and only send the
15928     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15929     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15930     * handling.
15931     */
15932    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15933        // Serialize this with the rest of the install-process message chain.  In the
15934        // restore-at-install case, this Runnable will necessarily run before the
15935        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15936        // are coherent.  In the non-restore case, the app has already completed install
15937        // and been launched through some other means, so it is not in a problematic
15938        // state for observers to see the FIRST_LAUNCH signal.
15939        mHandler.post(new Runnable() {
15940            @Override
15941            public void run() {
15942                for (int i = 0; i < mRunningInstalls.size(); i++) {
15943                    final PostInstallData data = mRunningInstalls.valueAt(i);
15944                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15945                        continue;
15946                    }
15947                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15948                        // right package; but is it for the right user?
15949                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15950                            if (userId == data.res.newUsers[uIndex]) {
15951                                if (DEBUG_BACKUP) {
15952                                    Slog.i(TAG, "Package " + pkgName
15953                                            + " being restored so deferring FIRST_LAUNCH");
15954                                }
15955                                return;
15956                            }
15957                        }
15958                    }
15959                }
15960                // didn't find it, so not being restored
15961                if (DEBUG_BACKUP) {
15962                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15963                }
15964                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15965            }
15966        });
15967    }
15968
15969    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15970        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15971                installerPkg, null, userIds);
15972    }
15973
15974    private abstract class HandlerParams {
15975        private static final int MAX_RETRIES = 4;
15976
15977        /**
15978         * Number of times startCopy() has been attempted and had a non-fatal
15979         * error.
15980         */
15981        private int mRetries = 0;
15982
15983        /** User handle for the user requesting the information or installation. */
15984        private final UserHandle mUser;
15985        String traceMethod;
15986        int traceCookie;
15987
15988        HandlerParams(UserHandle user) {
15989            mUser = user;
15990        }
15991
15992        UserHandle getUser() {
15993            return mUser;
15994        }
15995
15996        HandlerParams setTraceMethod(String traceMethod) {
15997            this.traceMethod = traceMethod;
15998            return this;
15999        }
16000
16001        HandlerParams setTraceCookie(int traceCookie) {
16002            this.traceCookie = traceCookie;
16003            return this;
16004        }
16005
16006        final boolean startCopy() {
16007            boolean res;
16008            try {
16009                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
16010
16011                if (++mRetries > MAX_RETRIES) {
16012                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16013                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
16014                    handleServiceError();
16015                    return false;
16016                } else {
16017                    handleStartCopy();
16018                    res = true;
16019                }
16020            } catch (RemoteException e) {
16021                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16022                mHandler.sendEmptyMessage(MCS_RECONNECT);
16023                res = false;
16024            }
16025            handleReturnCode();
16026            return res;
16027        }
16028
16029        final void serviceError() {
16030            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16031            handleServiceError();
16032            handleReturnCode();
16033        }
16034
16035        abstract void handleStartCopy() throws RemoteException;
16036        abstract void handleServiceError();
16037        abstract void handleReturnCode();
16038    }
16039
16040    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16041        for (File path : paths) {
16042            try {
16043                mcs.clearDirectory(path.getAbsolutePath());
16044            } catch (RemoteException e) {
16045            }
16046        }
16047    }
16048
16049    static class OriginInfo {
16050        /**
16051         * Location where install is coming from, before it has been
16052         * copied/renamed into place. This could be a single monolithic APK
16053         * file, or a cluster directory. This location may be untrusted.
16054         */
16055        final File file;
16056        final String cid;
16057
16058        /**
16059         * Flag indicating that {@link #file} or {@link #cid} has already been
16060         * staged, meaning downstream users don't need to defensively copy the
16061         * contents.
16062         */
16063        final boolean staged;
16064
16065        /**
16066         * Flag indicating that {@link #file} or {@link #cid} is an already
16067         * installed app that is being moved.
16068         */
16069        final boolean existing;
16070
16071        final String resolvedPath;
16072        final File resolvedFile;
16073
16074        static OriginInfo fromNothing() {
16075            return new OriginInfo(null, null, false, false);
16076        }
16077
16078        static OriginInfo fromUntrustedFile(File file) {
16079            return new OriginInfo(file, null, false, false);
16080        }
16081
16082        static OriginInfo fromExistingFile(File file) {
16083            return new OriginInfo(file, null, false, true);
16084        }
16085
16086        static OriginInfo fromStagedFile(File file) {
16087            return new OriginInfo(file, null, true, false);
16088        }
16089
16090        static OriginInfo fromStagedContainer(String cid) {
16091            return new OriginInfo(null, cid, true, false);
16092        }
16093
16094        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16095            this.file = file;
16096            this.cid = cid;
16097            this.staged = staged;
16098            this.existing = existing;
16099
16100            if (cid != null) {
16101                resolvedPath = PackageHelper.getSdDir(cid);
16102                resolvedFile = new File(resolvedPath);
16103            } else if (file != null) {
16104                resolvedPath = file.getAbsolutePath();
16105                resolvedFile = file;
16106            } else {
16107                resolvedPath = null;
16108                resolvedFile = null;
16109            }
16110        }
16111    }
16112
16113    static class MoveInfo {
16114        final int moveId;
16115        final String fromUuid;
16116        final String toUuid;
16117        final String packageName;
16118        final String dataAppName;
16119        final int appId;
16120        final String seinfo;
16121        final int targetSdkVersion;
16122
16123        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16124                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16125            this.moveId = moveId;
16126            this.fromUuid = fromUuid;
16127            this.toUuid = toUuid;
16128            this.packageName = packageName;
16129            this.dataAppName = dataAppName;
16130            this.appId = appId;
16131            this.seinfo = seinfo;
16132            this.targetSdkVersion = targetSdkVersion;
16133        }
16134    }
16135
16136    static class VerificationInfo {
16137        /** A constant used to indicate that a uid value is not present. */
16138        public static final int NO_UID = -1;
16139
16140        /** URI referencing where the package was downloaded from. */
16141        final Uri originatingUri;
16142
16143        /** HTTP referrer URI associated with the originatingURI. */
16144        final Uri referrer;
16145
16146        /** UID of the application that the install request originated from. */
16147        final int originatingUid;
16148
16149        /** UID of application requesting the install */
16150        final int installerUid;
16151
16152        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16153            this.originatingUri = originatingUri;
16154            this.referrer = referrer;
16155            this.originatingUid = originatingUid;
16156            this.installerUid = installerUid;
16157        }
16158    }
16159
16160    class InstallParams extends HandlerParams {
16161        final OriginInfo origin;
16162        final MoveInfo move;
16163        final IPackageInstallObserver2 observer;
16164        int installFlags;
16165        final String installerPackageName;
16166        final String volumeUuid;
16167        private InstallArgs mArgs;
16168        private int mRet;
16169        final String packageAbiOverride;
16170        final String[] grantedRuntimePermissions;
16171        final VerificationInfo verificationInfo;
16172        final Certificate[][] certificates;
16173        final int installReason;
16174
16175        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16176                int installFlags, String installerPackageName, String volumeUuid,
16177                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16178                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16179            super(user);
16180            this.origin = origin;
16181            this.move = move;
16182            this.observer = observer;
16183            this.installFlags = installFlags;
16184            this.installerPackageName = installerPackageName;
16185            this.volumeUuid = volumeUuid;
16186            this.verificationInfo = verificationInfo;
16187            this.packageAbiOverride = packageAbiOverride;
16188            this.grantedRuntimePermissions = grantedPermissions;
16189            this.certificates = certificates;
16190            this.installReason = installReason;
16191        }
16192
16193        @Override
16194        public String toString() {
16195            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16196                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16197        }
16198
16199        private int installLocationPolicy(PackageInfoLite pkgLite) {
16200            String packageName = pkgLite.packageName;
16201            int installLocation = pkgLite.installLocation;
16202            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16203            // reader
16204            synchronized (mPackages) {
16205                // Currently installed package which the new package is attempting to replace or
16206                // null if no such package is installed.
16207                PackageParser.Package installedPkg = mPackages.get(packageName);
16208                // Package which currently owns the data which the new package will own if installed.
16209                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16210                // will be null whereas dataOwnerPkg will contain information about the package
16211                // which was uninstalled while keeping its data.
16212                PackageParser.Package dataOwnerPkg = installedPkg;
16213                if (dataOwnerPkg  == null) {
16214                    PackageSetting ps = mSettings.mPackages.get(packageName);
16215                    if (ps != null) {
16216                        dataOwnerPkg = ps.pkg;
16217                    }
16218                }
16219
16220                if (dataOwnerPkg != null) {
16221                    // If installed, the package will get access to data left on the device by its
16222                    // predecessor. As a security measure, this is permited only if this is not a
16223                    // version downgrade or if the predecessor package is marked as debuggable and
16224                    // a downgrade is explicitly requested.
16225                    //
16226                    // On debuggable platform builds, downgrades are permitted even for
16227                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16228                    // not offer security guarantees and thus it's OK to disable some security
16229                    // mechanisms to make debugging/testing easier on those builds. However, even on
16230                    // debuggable builds downgrades of packages are permitted only if requested via
16231                    // installFlags. This is because we aim to keep the behavior of debuggable
16232                    // platform builds as close as possible to the behavior of non-debuggable
16233                    // platform builds.
16234                    final boolean downgradeRequested =
16235                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16236                    final boolean packageDebuggable =
16237                                (dataOwnerPkg.applicationInfo.flags
16238                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16239                    final boolean downgradePermitted =
16240                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16241                    if (!downgradePermitted) {
16242                        try {
16243                            checkDowngrade(dataOwnerPkg, pkgLite);
16244                        } catch (PackageManagerException e) {
16245                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16246                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16247                        }
16248                    }
16249                }
16250
16251                if (installedPkg != null) {
16252                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16253                        // Check for updated system application.
16254                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16255                            if (onSd) {
16256                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16257                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16258                            }
16259                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16260                        } else {
16261                            if (onSd) {
16262                                // Install flag overrides everything.
16263                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16264                            }
16265                            // If current upgrade specifies particular preference
16266                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16267                                // Application explicitly specified internal.
16268                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16269                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16270                                // App explictly prefers external. Let policy decide
16271                            } else {
16272                                // Prefer previous location
16273                                if (isExternal(installedPkg)) {
16274                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16275                                }
16276                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16277                            }
16278                        }
16279                    } else {
16280                        // Invalid install. Return error code
16281                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16282                    }
16283                }
16284            }
16285            // All the special cases have been taken care of.
16286            // Return result based on recommended install location.
16287            if (onSd) {
16288                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16289            }
16290            return pkgLite.recommendedInstallLocation;
16291        }
16292
16293        /*
16294         * Invoke remote method to get package information and install
16295         * location values. Override install location based on default
16296         * policy if needed and then create install arguments based
16297         * on the install location.
16298         */
16299        public void handleStartCopy() throws RemoteException {
16300            int ret = PackageManager.INSTALL_SUCCEEDED;
16301
16302            // If we're already staged, we've firmly committed to an install location
16303            if (origin.staged) {
16304                if (origin.file != null) {
16305                    installFlags |= PackageManager.INSTALL_INTERNAL;
16306                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16307                } else if (origin.cid != null) {
16308                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16309                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16310                } else {
16311                    throw new IllegalStateException("Invalid stage location");
16312                }
16313            }
16314
16315            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16316            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16317            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16318            PackageInfoLite pkgLite = null;
16319
16320            if (onInt && onSd) {
16321                // Check if both bits are set.
16322                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16323                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16324            } else if (onSd && ephemeral) {
16325                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16326                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16327            } else {
16328                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16329                        packageAbiOverride);
16330
16331                if (DEBUG_EPHEMERAL && ephemeral) {
16332                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16333                }
16334
16335                /*
16336                 * If we have too little free space, try to free cache
16337                 * before giving up.
16338                 */
16339                if (!origin.staged && pkgLite.recommendedInstallLocation
16340                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16341                    // TODO: focus freeing disk space on the target device
16342                    final StorageManager storage = StorageManager.from(mContext);
16343                    final long lowThreshold = storage.getStorageLowBytes(
16344                            Environment.getDataDirectory());
16345
16346                    final long sizeBytes = mContainerService.calculateInstalledSize(
16347                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16348
16349                    try {
16350                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16351                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16352                                installFlags, packageAbiOverride);
16353                    } catch (InstallerException e) {
16354                        Slog.w(TAG, "Failed to free cache", e);
16355                    }
16356
16357                    /*
16358                     * The cache free must have deleted the file we
16359                     * downloaded to install.
16360                     *
16361                     * TODO: fix the "freeCache" call to not delete
16362                     *       the file we care about.
16363                     */
16364                    if (pkgLite.recommendedInstallLocation
16365                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16366                        pkgLite.recommendedInstallLocation
16367                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16368                    }
16369                }
16370            }
16371
16372            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16373                int loc = pkgLite.recommendedInstallLocation;
16374                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16375                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16376                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16377                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16378                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16379                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16380                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16381                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16382                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16383                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16384                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16385                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16386                } else {
16387                    // Override with defaults if needed.
16388                    loc = installLocationPolicy(pkgLite);
16389                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16390                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16391                    } else if (!onSd && !onInt) {
16392                        // Override install location with flags
16393                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16394                            // Set the flag to install on external media.
16395                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16396                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16397                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16398                            if (DEBUG_EPHEMERAL) {
16399                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16400                            }
16401                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16402                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16403                                    |PackageManager.INSTALL_INTERNAL);
16404                        } else {
16405                            // Make sure the flag for installing on external
16406                            // media is unset
16407                            installFlags |= PackageManager.INSTALL_INTERNAL;
16408                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16409                        }
16410                    }
16411                }
16412            }
16413
16414            final InstallArgs args = createInstallArgs(this);
16415            mArgs = args;
16416
16417            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16418                // TODO: http://b/22976637
16419                // Apps installed for "all" users use the device owner to verify the app
16420                UserHandle verifierUser = getUser();
16421                if (verifierUser == UserHandle.ALL) {
16422                    verifierUser = UserHandle.SYSTEM;
16423                }
16424
16425                /*
16426                 * Determine if we have any installed package verifiers. If we
16427                 * do, then we'll defer to them to verify the packages.
16428                 */
16429                final int requiredUid = mRequiredVerifierPackage == null ? -1
16430                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16431                                verifierUser.getIdentifier());
16432                final int installerUid =
16433                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16434                if (!origin.existing && requiredUid != -1
16435                        && isVerificationEnabled(
16436                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16437                    final Intent verification = new Intent(
16438                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16439                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16440                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16441                            PACKAGE_MIME_TYPE);
16442                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16443
16444                    // Query all live verifiers based on current user state
16445                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16446                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16447                            false /*allowDynamicSplits*/);
16448
16449                    if (DEBUG_VERIFY) {
16450                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16451                                + verification.toString() + " with " + pkgLite.verifiers.length
16452                                + " optional verifiers");
16453                    }
16454
16455                    final int verificationId = mPendingVerificationToken++;
16456
16457                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16458
16459                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16460                            installerPackageName);
16461
16462                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16463                            installFlags);
16464
16465                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16466                            pkgLite.packageName);
16467
16468                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16469                            pkgLite.versionCode);
16470
16471                    if (verificationInfo != null) {
16472                        if (verificationInfo.originatingUri != null) {
16473                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16474                                    verificationInfo.originatingUri);
16475                        }
16476                        if (verificationInfo.referrer != null) {
16477                            verification.putExtra(Intent.EXTRA_REFERRER,
16478                                    verificationInfo.referrer);
16479                        }
16480                        if (verificationInfo.originatingUid >= 0) {
16481                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16482                                    verificationInfo.originatingUid);
16483                        }
16484                        if (verificationInfo.installerUid >= 0) {
16485                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16486                                    verificationInfo.installerUid);
16487                        }
16488                    }
16489
16490                    final PackageVerificationState verificationState = new PackageVerificationState(
16491                            requiredUid, args);
16492
16493                    mPendingVerification.append(verificationId, verificationState);
16494
16495                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16496                            receivers, verificationState);
16497
16498                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16499                    final long idleDuration = getVerificationTimeout();
16500
16501                    /*
16502                     * If any sufficient verifiers were listed in the package
16503                     * manifest, attempt to ask them.
16504                     */
16505                    if (sufficientVerifiers != null) {
16506                        final int N = sufficientVerifiers.size();
16507                        if (N == 0) {
16508                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16509                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16510                        } else {
16511                            for (int i = 0; i < N; i++) {
16512                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16513                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16514                                        verifierComponent.getPackageName(), idleDuration,
16515                                        verifierUser.getIdentifier(), false, "package verifier");
16516
16517                                final Intent sufficientIntent = new Intent(verification);
16518                                sufficientIntent.setComponent(verifierComponent);
16519                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16520                            }
16521                        }
16522                    }
16523
16524                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16525                            mRequiredVerifierPackage, receivers);
16526                    if (ret == PackageManager.INSTALL_SUCCEEDED
16527                            && mRequiredVerifierPackage != null) {
16528                        Trace.asyncTraceBegin(
16529                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16530                        /*
16531                         * Send the intent to the required verification agent,
16532                         * but only start the verification timeout after the
16533                         * target BroadcastReceivers have run.
16534                         */
16535                        verification.setComponent(requiredVerifierComponent);
16536                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16537                                mRequiredVerifierPackage, idleDuration,
16538                                verifierUser.getIdentifier(), false, "package verifier");
16539                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16540                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16541                                new BroadcastReceiver() {
16542                                    @Override
16543                                    public void onReceive(Context context, Intent intent) {
16544                                        final Message msg = mHandler
16545                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16546                                        msg.arg1 = verificationId;
16547                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16548                                    }
16549                                }, null, 0, null, null);
16550
16551                        /*
16552                         * We don't want the copy to proceed until verification
16553                         * succeeds, so null out this field.
16554                         */
16555                        mArgs = null;
16556                    }
16557                } else {
16558                    /*
16559                     * No package verification is enabled, so immediately start
16560                     * the remote call to initiate copy using temporary file.
16561                     */
16562                    ret = args.copyApk(mContainerService, true);
16563                }
16564            }
16565
16566            mRet = ret;
16567        }
16568
16569        @Override
16570        void handleReturnCode() {
16571            // If mArgs is null, then MCS couldn't be reached. When it
16572            // reconnects, it will try again to install. At that point, this
16573            // will succeed.
16574            if (mArgs != null) {
16575                processPendingInstall(mArgs, mRet);
16576            }
16577        }
16578
16579        @Override
16580        void handleServiceError() {
16581            mArgs = createInstallArgs(this);
16582            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16583        }
16584
16585        public boolean isForwardLocked() {
16586            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16587        }
16588    }
16589
16590    /**
16591     * Used during creation of InstallArgs
16592     *
16593     * @param installFlags package installation flags
16594     * @return true if should be installed on external storage
16595     */
16596    private static boolean installOnExternalAsec(int installFlags) {
16597        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16598            return false;
16599        }
16600        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16601            return true;
16602        }
16603        return false;
16604    }
16605
16606    /**
16607     * Used during creation of InstallArgs
16608     *
16609     * @param installFlags package installation flags
16610     * @return true if should be installed as forward locked
16611     */
16612    private static boolean installForwardLocked(int installFlags) {
16613        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16614    }
16615
16616    private InstallArgs createInstallArgs(InstallParams params) {
16617        if (params.move != null) {
16618            return new MoveInstallArgs(params);
16619        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16620            return new AsecInstallArgs(params);
16621        } else {
16622            return new FileInstallArgs(params);
16623        }
16624    }
16625
16626    /**
16627     * Create args that describe an existing installed package. Typically used
16628     * when cleaning up old installs, or used as a move source.
16629     */
16630    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16631            String resourcePath, String[] instructionSets) {
16632        final boolean isInAsec;
16633        if (installOnExternalAsec(installFlags)) {
16634            /* Apps on SD card are always in ASEC containers. */
16635            isInAsec = true;
16636        } else if (installForwardLocked(installFlags)
16637                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16638            /*
16639             * Forward-locked apps are only in ASEC containers if they're the
16640             * new style
16641             */
16642            isInAsec = true;
16643        } else {
16644            isInAsec = false;
16645        }
16646
16647        if (isInAsec) {
16648            return new AsecInstallArgs(codePath, instructionSets,
16649                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16650        } else {
16651            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16652        }
16653    }
16654
16655    static abstract class InstallArgs {
16656        /** @see InstallParams#origin */
16657        final OriginInfo origin;
16658        /** @see InstallParams#move */
16659        final MoveInfo move;
16660
16661        final IPackageInstallObserver2 observer;
16662        // Always refers to PackageManager flags only
16663        final int installFlags;
16664        final String installerPackageName;
16665        final String volumeUuid;
16666        final UserHandle user;
16667        final String abiOverride;
16668        final String[] installGrantPermissions;
16669        /** If non-null, drop an async trace when the install completes */
16670        final String traceMethod;
16671        final int traceCookie;
16672        final Certificate[][] certificates;
16673        final int installReason;
16674
16675        // The list of instruction sets supported by this app. This is currently
16676        // only used during the rmdex() phase to clean up resources. We can get rid of this
16677        // if we move dex files under the common app path.
16678        /* nullable */ String[] instructionSets;
16679
16680        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16681                int installFlags, String installerPackageName, String volumeUuid,
16682                UserHandle user, String[] instructionSets,
16683                String abiOverride, String[] installGrantPermissions,
16684                String traceMethod, int traceCookie, Certificate[][] certificates,
16685                int installReason) {
16686            this.origin = origin;
16687            this.move = move;
16688            this.installFlags = installFlags;
16689            this.observer = observer;
16690            this.installerPackageName = installerPackageName;
16691            this.volumeUuid = volumeUuid;
16692            this.user = user;
16693            this.instructionSets = instructionSets;
16694            this.abiOverride = abiOverride;
16695            this.installGrantPermissions = installGrantPermissions;
16696            this.traceMethod = traceMethod;
16697            this.traceCookie = traceCookie;
16698            this.certificates = certificates;
16699            this.installReason = installReason;
16700        }
16701
16702        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16703        abstract int doPreInstall(int status);
16704
16705        /**
16706         * Rename package into final resting place. All paths on the given
16707         * scanned package should be updated to reflect the rename.
16708         */
16709        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16710        abstract int doPostInstall(int status, int uid);
16711
16712        /** @see PackageSettingBase#codePathString */
16713        abstract String getCodePath();
16714        /** @see PackageSettingBase#resourcePathString */
16715        abstract String getResourcePath();
16716
16717        // Need installer lock especially for dex file removal.
16718        abstract void cleanUpResourcesLI();
16719        abstract boolean doPostDeleteLI(boolean delete);
16720
16721        /**
16722         * Called before the source arguments are copied. This is used mostly
16723         * for MoveParams when it needs to read the source file to put it in the
16724         * destination.
16725         */
16726        int doPreCopy() {
16727            return PackageManager.INSTALL_SUCCEEDED;
16728        }
16729
16730        /**
16731         * Called after the source arguments are copied. This is used mostly for
16732         * MoveParams when it needs to read the source file to put it in the
16733         * destination.
16734         */
16735        int doPostCopy(int uid) {
16736            return PackageManager.INSTALL_SUCCEEDED;
16737        }
16738
16739        protected boolean isFwdLocked() {
16740            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16741        }
16742
16743        protected boolean isExternalAsec() {
16744            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16745        }
16746
16747        protected boolean isEphemeral() {
16748            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16749        }
16750
16751        UserHandle getUser() {
16752            return user;
16753        }
16754    }
16755
16756    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16757        if (!allCodePaths.isEmpty()) {
16758            if (instructionSets == null) {
16759                throw new IllegalStateException("instructionSet == null");
16760            }
16761            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16762            for (String codePath : allCodePaths) {
16763                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16764                    try {
16765                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16766                    } catch (InstallerException ignored) {
16767                    }
16768                }
16769            }
16770        }
16771    }
16772
16773    /**
16774     * Logic to handle installation of non-ASEC applications, including copying
16775     * and renaming logic.
16776     */
16777    class FileInstallArgs extends InstallArgs {
16778        private File codeFile;
16779        private File resourceFile;
16780
16781        // Example topology:
16782        // /data/app/com.example/base.apk
16783        // /data/app/com.example/split_foo.apk
16784        // /data/app/com.example/lib/arm/libfoo.so
16785        // /data/app/com.example/lib/arm64/libfoo.so
16786        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16787
16788        /** New install */
16789        FileInstallArgs(InstallParams params) {
16790            super(params.origin, params.move, params.observer, params.installFlags,
16791                    params.installerPackageName, params.volumeUuid,
16792                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16793                    params.grantedRuntimePermissions,
16794                    params.traceMethod, params.traceCookie, params.certificates,
16795                    params.installReason);
16796            if (isFwdLocked()) {
16797                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16798            }
16799        }
16800
16801        /** Existing install */
16802        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16803            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16804                    null, null, null, 0, null /*certificates*/,
16805                    PackageManager.INSTALL_REASON_UNKNOWN);
16806            this.codeFile = (codePath != null) ? new File(codePath) : null;
16807            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16808        }
16809
16810        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16811            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16812            try {
16813                return doCopyApk(imcs, temp);
16814            } finally {
16815                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16816            }
16817        }
16818
16819        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16820            if (origin.staged) {
16821                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16822                codeFile = origin.file;
16823                resourceFile = origin.file;
16824                return PackageManager.INSTALL_SUCCEEDED;
16825            }
16826
16827            try {
16828                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16829                final File tempDir =
16830                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16831                codeFile = tempDir;
16832                resourceFile = tempDir;
16833            } catch (IOException e) {
16834                Slog.w(TAG, "Failed to create copy file: " + e);
16835                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16836            }
16837
16838            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16839                @Override
16840                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16841                    if (!FileUtils.isValidExtFilename(name)) {
16842                        throw new IllegalArgumentException("Invalid filename: " + name);
16843                    }
16844                    try {
16845                        final File file = new File(codeFile, name);
16846                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16847                                O_RDWR | O_CREAT, 0644);
16848                        Os.chmod(file.getAbsolutePath(), 0644);
16849                        return new ParcelFileDescriptor(fd);
16850                    } catch (ErrnoException e) {
16851                        throw new RemoteException("Failed to open: " + e.getMessage());
16852                    }
16853                }
16854            };
16855
16856            int ret = PackageManager.INSTALL_SUCCEEDED;
16857            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16858            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16859                Slog.e(TAG, "Failed to copy package");
16860                return ret;
16861            }
16862
16863            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16864            NativeLibraryHelper.Handle handle = null;
16865            try {
16866                handle = NativeLibraryHelper.Handle.create(codeFile);
16867                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16868                        abiOverride);
16869            } catch (IOException e) {
16870                Slog.e(TAG, "Copying native libraries failed", e);
16871                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16872            } finally {
16873                IoUtils.closeQuietly(handle);
16874            }
16875
16876            return ret;
16877        }
16878
16879        int doPreInstall(int status) {
16880            if (status != PackageManager.INSTALL_SUCCEEDED) {
16881                cleanUp();
16882            }
16883            return status;
16884        }
16885
16886        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16887            if (status != PackageManager.INSTALL_SUCCEEDED) {
16888                cleanUp();
16889                return false;
16890            }
16891
16892            final File targetDir = codeFile.getParentFile();
16893            final File beforeCodeFile = codeFile;
16894            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16895
16896            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16897            try {
16898                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16899            } catch (ErrnoException e) {
16900                Slog.w(TAG, "Failed to rename", e);
16901                return false;
16902            }
16903
16904            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16905                Slog.w(TAG, "Failed to restorecon");
16906                return false;
16907            }
16908
16909            // Reflect the rename internally
16910            codeFile = afterCodeFile;
16911            resourceFile = afterCodeFile;
16912
16913            // Reflect the rename in scanned details
16914            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16915            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16916                    afterCodeFile, pkg.baseCodePath));
16917            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16918                    afterCodeFile, pkg.splitCodePaths));
16919
16920            // Reflect the rename in app info
16921            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16922            pkg.setApplicationInfoCodePath(pkg.codePath);
16923            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16924            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16925            pkg.setApplicationInfoResourcePath(pkg.codePath);
16926            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16927            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16928
16929            return true;
16930        }
16931
16932        int doPostInstall(int status, int uid) {
16933            if (status != PackageManager.INSTALL_SUCCEEDED) {
16934                cleanUp();
16935            }
16936            return status;
16937        }
16938
16939        @Override
16940        String getCodePath() {
16941            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16942        }
16943
16944        @Override
16945        String getResourcePath() {
16946            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16947        }
16948
16949        private boolean cleanUp() {
16950            if (codeFile == null || !codeFile.exists()) {
16951                return false;
16952            }
16953
16954            removeCodePathLI(codeFile);
16955
16956            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16957                resourceFile.delete();
16958            }
16959
16960            return true;
16961        }
16962
16963        void cleanUpResourcesLI() {
16964            // Try enumerating all code paths before deleting
16965            List<String> allCodePaths = Collections.EMPTY_LIST;
16966            if (codeFile != null && codeFile.exists()) {
16967                try {
16968                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16969                    allCodePaths = pkg.getAllCodePaths();
16970                } catch (PackageParserException e) {
16971                    // Ignored; we tried our best
16972                }
16973            }
16974
16975            cleanUp();
16976            removeDexFiles(allCodePaths, instructionSets);
16977        }
16978
16979        boolean doPostDeleteLI(boolean delete) {
16980            // XXX err, shouldn't we respect the delete flag?
16981            cleanUpResourcesLI();
16982            return true;
16983        }
16984    }
16985
16986    private boolean isAsecExternal(String cid) {
16987        final String asecPath = PackageHelper.getSdFilesystem(cid);
16988        return !asecPath.startsWith(mAsecInternalPath);
16989    }
16990
16991    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16992            PackageManagerException {
16993        if (copyRet < 0) {
16994            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16995                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16996                throw new PackageManagerException(copyRet, message);
16997            }
16998        }
16999    }
17000
17001    /**
17002     * Extract the StorageManagerService "container ID" from the full code path of an
17003     * .apk.
17004     */
17005    static String cidFromCodePath(String fullCodePath) {
17006        int eidx = fullCodePath.lastIndexOf("/");
17007        String subStr1 = fullCodePath.substring(0, eidx);
17008        int sidx = subStr1.lastIndexOf("/");
17009        return subStr1.substring(sidx+1, eidx);
17010    }
17011
17012    /**
17013     * Logic to handle installation of ASEC applications, including copying and
17014     * renaming logic.
17015     */
17016    class AsecInstallArgs extends InstallArgs {
17017        static final String RES_FILE_NAME = "pkg.apk";
17018        static final String PUBLIC_RES_FILE_NAME = "res.zip";
17019
17020        String cid;
17021        String packagePath;
17022        String resourcePath;
17023
17024        /** New install */
17025        AsecInstallArgs(InstallParams params) {
17026            super(params.origin, params.move, params.observer, params.installFlags,
17027                    params.installerPackageName, params.volumeUuid,
17028                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17029                    params.grantedRuntimePermissions,
17030                    params.traceMethod, params.traceCookie, params.certificates,
17031                    params.installReason);
17032        }
17033
17034        /** Existing install */
17035        AsecInstallArgs(String fullCodePath, String[] instructionSets,
17036                        boolean isExternal, boolean isForwardLocked) {
17037            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17038                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17039                    instructionSets, null, null, null, 0, null /*certificates*/,
17040                    PackageManager.INSTALL_REASON_UNKNOWN);
17041            // Hackily pretend we're still looking at a full code path
17042            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17043                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17044            }
17045
17046            // Extract cid from fullCodePath
17047            int eidx = fullCodePath.lastIndexOf("/");
17048            String subStr1 = fullCodePath.substring(0, eidx);
17049            int sidx = subStr1.lastIndexOf("/");
17050            cid = subStr1.substring(sidx+1, eidx);
17051            setMountPath(subStr1);
17052        }
17053
17054        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17055            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17056                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17057                    instructionSets, null, null, null, 0, null /*certificates*/,
17058                    PackageManager.INSTALL_REASON_UNKNOWN);
17059            this.cid = cid;
17060            setMountPath(PackageHelper.getSdDir(cid));
17061        }
17062
17063        void createCopyFile() {
17064            cid = mInstallerService.allocateExternalStageCidLegacy();
17065        }
17066
17067        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17068            if (origin.staged && origin.cid != null) {
17069                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17070                cid = origin.cid;
17071                setMountPath(PackageHelper.getSdDir(cid));
17072                return PackageManager.INSTALL_SUCCEEDED;
17073            }
17074
17075            if (temp) {
17076                createCopyFile();
17077            } else {
17078                /*
17079                 * Pre-emptively destroy the container since it's destroyed if
17080                 * copying fails due to it existing anyway.
17081                 */
17082                PackageHelper.destroySdDir(cid);
17083            }
17084
17085            final String newMountPath = imcs.copyPackageToContainer(
17086                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17087                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17088
17089            if (newMountPath != null) {
17090                setMountPath(newMountPath);
17091                return PackageManager.INSTALL_SUCCEEDED;
17092            } else {
17093                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17094            }
17095        }
17096
17097        @Override
17098        String getCodePath() {
17099            return packagePath;
17100        }
17101
17102        @Override
17103        String getResourcePath() {
17104            return resourcePath;
17105        }
17106
17107        int doPreInstall(int status) {
17108            if (status != PackageManager.INSTALL_SUCCEEDED) {
17109                // Destroy container
17110                PackageHelper.destroySdDir(cid);
17111            } else {
17112                boolean mounted = PackageHelper.isContainerMounted(cid);
17113                if (!mounted) {
17114                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17115                            Process.SYSTEM_UID);
17116                    if (newMountPath != null) {
17117                        setMountPath(newMountPath);
17118                    } else {
17119                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17120                    }
17121                }
17122            }
17123            return status;
17124        }
17125
17126        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17127            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17128            String newMountPath = null;
17129            if (PackageHelper.isContainerMounted(cid)) {
17130                // Unmount the container
17131                if (!PackageHelper.unMountSdDir(cid)) {
17132                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17133                    return false;
17134                }
17135            }
17136            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17137                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17138                        " which might be stale. Will try to clean up.");
17139                // Clean up the stale container and proceed to recreate.
17140                if (!PackageHelper.destroySdDir(newCacheId)) {
17141                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17142                    return false;
17143                }
17144                // Successfully cleaned up stale container. Try to rename again.
17145                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17146                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17147                            + " inspite of cleaning it up.");
17148                    return false;
17149                }
17150            }
17151            if (!PackageHelper.isContainerMounted(newCacheId)) {
17152                Slog.w(TAG, "Mounting container " + newCacheId);
17153                newMountPath = PackageHelper.mountSdDir(newCacheId,
17154                        getEncryptKey(), Process.SYSTEM_UID);
17155            } else {
17156                newMountPath = PackageHelper.getSdDir(newCacheId);
17157            }
17158            if (newMountPath == null) {
17159                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17160                return false;
17161            }
17162            Log.i(TAG, "Succesfully renamed " + cid +
17163                    " to " + newCacheId +
17164                    " at new path: " + newMountPath);
17165            cid = newCacheId;
17166
17167            final File beforeCodeFile = new File(packagePath);
17168            setMountPath(newMountPath);
17169            final File afterCodeFile = new File(packagePath);
17170
17171            // Reflect the rename in scanned details
17172            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17173            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17174                    afterCodeFile, pkg.baseCodePath));
17175            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17176                    afterCodeFile, pkg.splitCodePaths));
17177
17178            // Reflect the rename in app info
17179            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17180            pkg.setApplicationInfoCodePath(pkg.codePath);
17181            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17182            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17183            pkg.setApplicationInfoResourcePath(pkg.codePath);
17184            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17185            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17186
17187            return true;
17188        }
17189
17190        private void setMountPath(String mountPath) {
17191            final File mountFile = new File(mountPath);
17192
17193            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17194            if (monolithicFile.exists()) {
17195                packagePath = monolithicFile.getAbsolutePath();
17196                if (isFwdLocked()) {
17197                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17198                } else {
17199                    resourcePath = packagePath;
17200                }
17201            } else {
17202                packagePath = mountFile.getAbsolutePath();
17203                resourcePath = packagePath;
17204            }
17205        }
17206
17207        int doPostInstall(int status, int uid) {
17208            if (status != PackageManager.INSTALL_SUCCEEDED) {
17209                cleanUp();
17210            } else {
17211                final int groupOwner;
17212                final String protectedFile;
17213                if (isFwdLocked()) {
17214                    groupOwner = UserHandle.getSharedAppGid(uid);
17215                    protectedFile = RES_FILE_NAME;
17216                } else {
17217                    groupOwner = -1;
17218                    protectedFile = null;
17219                }
17220
17221                if (uid < Process.FIRST_APPLICATION_UID
17222                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17223                    Slog.e(TAG, "Failed to finalize " + cid);
17224                    PackageHelper.destroySdDir(cid);
17225                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17226                }
17227
17228                boolean mounted = PackageHelper.isContainerMounted(cid);
17229                if (!mounted) {
17230                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17231                }
17232            }
17233            return status;
17234        }
17235
17236        private void cleanUp() {
17237            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17238
17239            // Destroy secure container
17240            PackageHelper.destroySdDir(cid);
17241        }
17242
17243        private List<String> getAllCodePaths() {
17244            final File codeFile = new File(getCodePath());
17245            if (codeFile != null && codeFile.exists()) {
17246                try {
17247                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17248                    return pkg.getAllCodePaths();
17249                } catch (PackageParserException e) {
17250                    // Ignored; we tried our best
17251                }
17252            }
17253            return Collections.EMPTY_LIST;
17254        }
17255
17256        void cleanUpResourcesLI() {
17257            // Enumerate all code paths before deleting
17258            cleanUpResourcesLI(getAllCodePaths());
17259        }
17260
17261        private void cleanUpResourcesLI(List<String> allCodePaths) {
17262            cleanUp();
17263            removeDexFiles(allCodePaths, instructionSets);
17264        }
17265
17266        String getPackageName() {
17267            return getAsecPackageName(cid);
17268        }
17269
17270        boolean doPostDeleteLI(boolean delete) {
17271            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17272            final List<String> allCodePaths = getAllCodePaths();
17273            boolean mounted = PackageHelper.isContainerMounted(cid);
17274            if (mounted) {
17275                // Unmount first
17276                if (PackageHelper.unMountSdDir(cid)) {
17277                    mounted = false;
17278                }
17279            }
17280            if (!mounted && delete) {
17281                cleanUpResourcesLI(allCodePaths);
17282            }
17283            return !mounted;
17284        }
17285
17286        @Override
17287        int doPreCopy() {
17288            if (isFwdLocked()) {
17289                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17290                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17291                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17292                }
17293            }
17294
17295            return PackageManager.INSTALL_SUCCEEDED;
17296        }
17297
17298        @Override
17299        int doPostCopy(int uid) {
17300            if (isFwdLocked()) {
17301                if (uid < Process.FIRST_APPLICATION_UID
17302                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17303                                RES_FILE_NAME)) {
17304                    Slog.e(TAG, "Failed to finalize " + cid);
17305                    PackageHelper.destroySdDir(cid);
17306                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17307                }
17308            }
17309
17310            return PackageManager.INSTALL_SUCCEEDED;
17311        }
17312    }
17313
17314    /**
17315     * Logic to handle movement of existing installed applications.
17316     */
17317    class MoveInstallArgs extends InstallArgs {
17318        private File codeFile;
17319        private File resourceFile;
17320
17321        /** New install */
17322        MoveInstallArgs(InstallParams params) {
17323            super(params.origin, params.move, params.observer, params.installFlags,
17324                    params.installerPackageName, params.volumeUuid,
17325                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17326                    params.grantedRuntimePermissions,
17327                    params.traceMethod, params.traceCookie, params.certificates,
17328                    params.installReason);
17329        }
17330
17331        int copyApk(IMediaContainerService imcs, boolean temp) {
17332            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17333                    + move.fromUuid + " to " + move.toUuid);
17334            synchronized (mInstaller) {
17335                try {
17336                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17337                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17338                } catch (InstallerException e) {
17339                    Slog.w(TAG, "Failed to move app", e);
17340                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17341                }
17342            }
17343
17344            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17345            resourceFile = codeFile;
17346            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17347
17348            return PackageManager.INSTALL_SUCCEEDED;
17349        }
17350
17351        int doPreInstall(int status) {
17352            if (status != PackageManager.INSTALL_SUCCEEDED) {
17353                cleanUp(move.toUuid);
17354            }
17355            return status;
17356        }
17357
17358        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17359            if (status != PackageManager.INSTALL_SUCCEEDED) {
17360                cleanUp(move.toUuid);
17361                return false;
17362            }
17363
17364            // Reflect the move in app info
17365            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17366            pkg.setApplicationInfoCodePath(pkg.codePath);
17367            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17368            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17369            pkg.setApplicationInfoResourcePath(pkg.codePath);
17370            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17371            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17372
17373            return true;
17374        }
17375
17376        int doPostInstall(int status, int uid) {
17377            if (status == PackageManager.INSTALL_SUCCEEDED) {
17378                cleanUp(move.fromUuid);
17379            } else {
17380                cleanUp(move.toUuid);
17381            }
17382            return status;
17383        }
17384
17385        @Override
17386        String getCodePath() {
17387            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17388        }
17389
17390        @Override
17391        String getResourcePath() {
17392            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17393        }
17394
17395        private boolean cleanUp(String volumeUuid) {
17396            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17397                    move.dataAppName);
17398            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17399            final int[] userIds = sUserManager.getUserIds();
17400            synchronized (mInstallLock) {
17401                // Clean up both app data and code
17402                // All package moves are frozen until finished
17403                for (int userId : userIds) {
17404                    try {
17405                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17406                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17407                    } catch (InstallerException e) {
17408                        Slog.w(TAG, String.valueOf(e));
17409                    }
17410                }
17411                removeCodePathLI(codeFile);
17412            }
17413            return true;
17414        }
17415
17416        void cleanUpResourcesLI() {
17417            throw new UnsupportedOperationException();
17418        }
17419
17420        boolean doPostDeleteLI(boolean delete) {
17421            throw new UnsupportedOperationException();
17422        }
17423    }
17424
17425    static String getAsecPackageName(String packageCid) {
17426        int idx = packageCid.lastIndexOf("-");
17427        if (idx == -1) {
17428            return packageCid;
17429        }
17430        return packageCid.substring(0, idx);
17431    }
17432
17433    // Utility method used to create code paths based on package name and available index.
17434    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17435        String idxStr = "";
17436        int idx = 1;
17437        // Fall back to default value of idx=1 if prefix is not
17438        // part of oldCodePath
17439        if (oldCodePath != null) {
17440            String subStr = oldCodePath;
17441            // Drop the suffix right away
17442            if (suffix != null && subStr.endsWith(suffix)) {
17443                subStr = subStr.substring(0, subStr.length() - suffix.length());
17444            }
17445            // If oldCodePath already contains prefix find out the
17446            // ending index to either increment or decrement.
17447            int sidx = subStr.lastIndexOf(prefix);
17448            if (sidx != -1) {
17449                subStr = subStr.substring(sidx + prefix.length());
17450                if (subStr != null) {
17451                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17452                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17453                    }
17454                    try {
17455                        idx = Integer.parseInt(subStr);
17456                        if (idx <= 1) {
17457                            idx++;
17458                        } else {
17459                            idx--;
17460                        }
17461                    } catch(NumberFormatException e) {
17462                    }
17463                }
17464            }
17465        }
17466        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17467        return prefix + idxStr;
17468    }
17469
17470    private File getNextCodePath(File targetDir, String packageName) {
17471        File result;
17472        SecureRandom random = new SecureRandom();
17473        byte[] bytes = new byte[16];
17474        do {
17475            random.nextBytes(bytes);
17476            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17477            result = new File(targetDir, packageName + "-" + suffix);
17478        } while (result.exists());
17479        return result;
17480    }
17481
17482    // Utility method that returns the relative package path with respect
17483    // to the installation directory. Like say for /data/data/com.test-1.apk
17484    // string com.test-1 is returned.
17485    static String deriveCodePathName(String codePath) {
17486        if (codePath == null) {
17487            return null;
17488        }
17489        final File codeFile = new File(codePath);
17490        final String name = codeFile.getName();
17491        if (codeFile.isDirectory()) {
17492            return name;
17493        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17494            final int lastDot = name.lastIndexOf('.');
17495            return name.substring(0, lastDot);
17496        } else {
17497            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17498            return null;
17499        }
17500    }
17501
17502    static class PackageInstalledInfo {
17503        String name;
17504        int uid;
17505        // The set of users that originally had this package installed.
17506        int[] origUsers;
17507        // The set of users that now have this package installed.
17508        int[] newUsers;
17509        PackageParser.Package pkg;
17510        int returnCode;
17511        String returnMsg;
17512        String installerPackageName;
17513        PackageRemovedInfo removedInfo;
17514        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17515
17516        public void setError(int code, String msg) {
17517            setReturnCode(code);
17518            setReturnMessage(msg);
17519            Slog.w(TAG, msg);
17520        }
17521
17522        public void setError(String msg, PackageParserException e) {
17523            setReturnCode(e.error);
17524            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17525            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17526            for (int i = 0; i < childCount; i++) {
17527                addedChildPackages.valueAt(i).setError(msg, e);
17528            }
17529            Slog.w(TAG, msg, e);
17530        }
17531
17532        public void setError(String msg, PackageManagerException e) {
17533            returnCode = e.error;
17534            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17535            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17536            for (int i = 0; i < childCount; i++) {
17537                addedChildPackages.valueAt(i).setError(msg, e);
17538            }
17539            Slog.w(TAG, msg, e);
17540        }
17541
17542        public void setReturnCode(int returnCode) {
17543            this.returnCode = returnCode;
17544            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17545            for (int i = 0; i < childCount; i++) {
17546                addedChildPackages.valueAt(i).returnCode = returnCode;
17547            }
17548        }
17549
17550        private void setReturnMessage(String returnMsg) {
17551            this.returnMsg = returnMsg;
17552            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17553            for (int i = 0; i < childCount; i++) {
17554                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17555            }
17556        }
17557
17558        // In some error cases we want to convey more info back to the observer
17559        String origPackage;
17560        String origPermission;
17561    }
17562
17563    /*
17564     * Install a non-existing package.
17565     */
17566    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17567            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17568            PackageInstalledInfo res, int installReason) {
17569        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17570
17571        // Remember this for later, in case we need to rollback this install
17572        String pkgName = pkg.packageName;
17573
17574        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17575
17576        synchronized(mPackages) {
17577            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17578            if (renamedPackage != null) {
17579                // A package with the same name is already installed, though
17580                // it has been renamed to an older name.  The package we
17581                // are trying to install should be installed as an update to
17582                // the existing one, but that has not been requested, so bail.
17583                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17584                        + " without first uninstalling package running as "
17585                        + renamedPackage);
17586                return;
17587            }
17588            if (mPackages.containsKey(pkgName)) {
17589                // Don't allow installation over an existing package with the same name.
17590                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17591                        + " without first uninstalling.");
17592                return;
17593            }
17594        }
17595
17596        try {
17597            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17598                    System.currentTimeMillis(), user);
17599
17600            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17601
17602            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17603                prepareAppDataAfterInstallLIF(newPackage);
17604
17605            } else {
17606                // Remove package from internal structures, but keep around any
17607                // data that might have already existed
17608                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17609                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17610            }
17611        } catch (PackageManagerException e) {
17612            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17613        }
17614
17615        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17616    }
17617
17618    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17619        // Can't rotate keys during boot or if sharedUser.
17620        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17621                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17622            return false;
17623        }
17624        // app is using upgradeKeySets; make sure all are valid
17625        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17626        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17627        for (int i = 0; i < upgradeKeySets.length; i++) {
17628            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17629                Slog.wtf(TAG, "Package "
17630                         + (oldPs.name != null ? oldPs.name : "<null>")
17631                         + " contains upgrade-key-set reference to unknown key-set: "
17632                         + upgradeKeySets[i]
17633                         + " reverting to signatures check.");
17634                return false;
17635            }
17636        }
17637        return true;
17638    }
17639
17640    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17641        // Upgrade keysets are being used.  Determine if new package has a superset of the
17642        // required keys.
17643        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17644        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17645        for (int i = 0; i < upgradeKeySets.length; i++) {
17646            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17647            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17648                return true;
17649            }
17650        }
17651        return false;
17652    }
17653
17654    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17655        try (DigestInputStream digestStream =
17656                new DigestInputStream(new FileInputStream(file), digest)) {
17657            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17658        }
17659    }
17660
17661    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17662            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17663            int installReason) {
17664        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17665
17666        final PackageParser.Package oldPackage;
17667        final PackageSetting ps;
17668        final String pkgName = pkg.packageName;
17669        final int[] allUsers;
17670        final int[] installedUsers;
17671
17672        synchronized(mPackages) {
17673            oldPackage = mPackages.get(pkgName);
17674            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17675
17676            // don't allow upgrade to target a release SDK from a pre-release SDK
17677            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17678                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17679            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17680                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17681            if (oldTargetsPreRelease
17682                    && !newTargetsPreRelease
17683                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17684                Slog.w(TAG, "Can't install package targeting released sdk");
17685                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17686                return;
17687            }
17688
17689            ps = mSettings.mPackages.get(pkgName);
17690
17691            // verify signatures are valid
17692            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17693                if (!checkUpgradeKeySetLP(ps, pkg)) {
17694                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17695                            "New package not signed by keys specified by upgrade-keysets: "
17696                                    + pkgName);
17697                    return;
17698                }
17699            } else {
17700                // default to original signature matching
17701                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17702                        != PackageManager.SIGNATURE_MATCH) {
17703                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17704                            "New package has a different signature: " + pkgName);
17705                    return;
17706                }
17707            }
17708
17709            // don't allow a system upgrade unless the upgrade hash matches
17710            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17711                byte[] digestBytes = null;
17712                try {
17713                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17714                    updateDigest(digest, new File(pkg.baseCodePath));
17715                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17716                        for (String path : pkg.splitCodePaths) {
17717                            updateDigest(digest, new File(path));
17718                        }
17719                    }
17720                    digestBytes = digest.digest();
17721                } catch (NoSuchAlgorithmException | IOException e) {
17722                    res.setError(INSTALL_FAILED_INVALID_APK,
17723                            "Could not compute hash: " + pkgName);
17724                    return;
17725                }
17726                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17727                    res.setError(INSTALL_FAILED_INVALID_APK,
17728                            "New package fails restrict-update check: " + pkgName);
17729                    return;
17730                }
17731                // retain upgrade restriction
17732                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17733            }
17734
17735            // Check for shared user id changes
17736            String invalidPackageName =
17737                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17738            if (invalidPackageName != null) {
17739                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17740                        "Package " + invalidPackageName + " tried to change user "
17741                                + oldPackage.mSharedUserId);
17742                return;
17743            }
17744
17745            // check if the new package supports all of the abis which the old package supports
17746            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
17747            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
17748            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
17749                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17750                        "Update to package " + pkgName + " doesn't support multi arch");
17751                return;
17752            }
17753
17754            // In case of rollback, remember per-user/profile install state
17755            allUsers = sUserManager.getUserIds();
17756            installedUsers = ps.queryInstalledUsers(allUsers, true);
17757
17758            // don't allow an upgrade from full to ephemeral
17759            if (isInstantApp) {
17760                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17761                    for (int currentUser : allUsers) {
17762                        if (!ps.getInstantApp(currentUser)) {
17763                            // can't downgrade from full to instant
17764                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17765                                    + " for user: " + currentUser);
17766                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17767                            return;
17768                        }
17769                    }
17770                } else if (!ps.getInstantApp(user.getIdentifier())) {
17771                    // can't downgrade from full to instant
17772                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17773                            + " for user: " + user.getIdentifier());
17774                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17775                    return;
17776                }
17777            }
17778        }
17779
17780        // Update what is removed
17781        res.removedInfo = new PackageRemovedInfo(this);
17782        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17783        res.removedInfo.removedPackage = oldPackage.packageName;
17784        res.removedInfo.installerPackageName = ps.installerPackageName;
17785        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17786        res.removedInfo.isUpdate = true;
17787        res.removedInfo.origUsers = installedUsers;
17788        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17789        for (int i = 0; i < installedUsers.length; i++) {
17790            final int userId = installedUsers[i];
17791            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17792        }
17793
17794        final int childCount = (oldPackage.childPackages != null)
17795                ? oldPackage.childPackages.size() : 0;
17796        for (int i = 0; i < childCount; i++) {
17797            boolean childPackageUpdated = false;
17798            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17799            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17800            if (res.addedChildPackages != null) {
17801                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17802                if (childRes != null) {
17803                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17804                    childRes.removedInfo.removedPackage = childPkg.packageName;
17805                    if (childPs != null) {
17806                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17807                    }
17808                    childRes.removedInfo.isUpdate = true;
17809                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17810                    childPackageUpdated = true;
17811                }
17812            }
17813            if (!childPackageUpdated) {
17814                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17815                childRemovedRes.removedPackage = childPkg.packageName;
17816                if (childPs != null) {
17817                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17818                }
17819                childRemovedRes.isUpdate = false;
17820                childRemovedRes.dataRemoved = true;
17821                synchronized (mPackages) {
17822                    if (childPs != null) {
17823                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17824                    }
17825                }
17826                if (res.removedInfo.removedChildPackages == null) {
17827                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17828                }
17829                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17830            }
17831        }
17832
17833        boolean sysPkg = (isSystemApp(oldPackage));
17834        if (sysPkg) {
17835            // Set the system/privileged flags as needed
17836            final boolean privileged =
17837                    (oldPackage.applicationInfo.privateFlags
17838                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17839            final int systemPolicyFlags = policyFlags
17840                    | PackageParser.PARSE_IS_SYSTEM
17841                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17842
17843            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17844                    user, allUsers, installerPackageName, res, installReason);
17845        } else {
17846            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17847                    user, allUsers, installerPackageName, res, installReason);
17848        }
17849    }
17850
17851    @Override
17852    public List<String> getPreviousCodePaths(String packageName) {
17853        final int callingUid = Binder.getCallingUid();
17854        final List<String> result = new ArrayList<>();
17855        if (getInstantAppPackageName(callingUid) != null) {
17856            return result;
17857        }
17858        final PackageSetting ps = mSettings.mPackages.get(packageName);
17859        if (ps != null
17860                && ps.oldCodePaths != null
17861                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17862            result.addAll(ps.oldCodePaths);
17863        }
17864        return result;
17865    }
17866
17867    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17868            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17869            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17870            int installReason) {
17871        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17872                + deletedPackage);
17873
17874        String pkgName = deletedPackage.packageName;
17875        boolean deletedPkg = true;
17876        boolean addedPkg = false;
17877        boolean updatedSettings = false;
17878        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17879        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17880                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17881
17882        final long origUpdateTime = (pkg.mExtras != null)
17883                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17884
17885        // First delete the existing package while retaining the data directory
17886        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17887                res.removedInfo, true, pkg)) {
17888            // If the existing package wasn't successfully deleted
17889            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17890            deletedPkg = false;
17891        } else {
17892            // Successfully deleted the old package; proceed with replace.
17893
17894            // If deleted package lived in a container, give users a chance to
17895            // relinquish resources before killing.
17896            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17897                if (DEBUG_INSTALL) {
17898                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17899                }
17900                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17901                final ArrayList<String> pkgList = new ArrayList<String>(1);
17902                pkgList.add(deletedPackage.applicationInfo.packageName);
17903                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17904            }
17905
17906            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17907                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17908            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17909
17910            try {
17911                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17912                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17913                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17914                        installReason);
17915
17916                // Update the in-memory copy of the previous code paths.
17917                PackageSetting ps = mSettings.mPackages.get(pkgName);
17918                if (!killApp) {
17919                    if (ps.oldCodePaths == null) {
17920                        ps.oldCodePaths = new ArraySet<>();
17921                    }
17922                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17923                    if (deletedPackage.splitCodePaths != null) {
17924                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17925                    }
17926                } else {
17927                    ps.oldCodePaths = null;
17928                }
17929                if (ps.childPackageNames != null) {
17930                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17931                        final String childPkgName = ps.childPackageNames.get(i);
17932                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17933                        childPs.oldCodePaths = ps.oldCodePaths;
17934                    }
17935                }
17936                // set instant app status, but, only if it's explicitly specified
17937                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17938                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17939                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17940                prepareAppDataAfterInstallLIF(newPackage);
17941                addedPkg = true;
17942                mDexManager.notifyPackageUpdated(newPackage.packageName,
17943                        newPackage.baseCodePath, newPackage.splitCodePaths);
17944            } catch (PackageManagerException e) {
17945                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17946            }
17947        }
17948
17949        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17950            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17951
17952            // Revert all internal state mutations and added folders for the failed install
17953            if (addedPkg) {
17954                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17955                        res.removedInfo, true, null);
17956            }
17957
17958            // Restore the old package
17959            if (deletedPkg) {
17960                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17961                File restoreFile = new File(deletedPackage.codePath);
17962                // Parse old package
17963                boolean oldExternal = isExternal(deletedPackage);
17964                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17965                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17966                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17967                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17968                try {
17969                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17970                            null);
17971                } catch (PackageManagerException e) {
17972                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17973                            + e.getMessage());
17974                    return;
17975                }
17976
17977                synchronized (mPackages) {
17978                    // Ensure the installer package name up to date
17979                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17980
17981                    // Update permissions for restored package
17982                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17983
17984                    mSettings.writeLPr();
17985                }
17986
17987                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17988            }
17989        } else {
17990            synchronized (mPackages) {
17991                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17992                if (ps != null) {
17993                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17994                    if (res.removedInfo.removedChildPackages != null) {
17995                        final int childCount = res.removedInfo.removedChildPackages.size();
17996                        // Iterate in reverse as we may modify the collection
17997                        for (int i = childCount - 1; i >= 0; i--) {
17998                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17999                            if (res.addedChildPackages.containsKey(childPackageName)) {
18000                                res.removedInfo.removedChildPackages.removeAt(i);
18001                            } else {
18002                                PackageRemovedInfo childInfo = res.removedInfo
18003                                        .removedChildPackages.valueAt(i);
18004                                childInfo.removedForAllUsers = mPackages.get(
18005                                        childInfo.removedPackage) == null;
18006                            }
18007                        }
18008                    }
18009                }
18010            }
18011        }
18012    }
18013
18014    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
18015            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
18016            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
18017            int installReason) {
18018        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
18019                + ", old=" + deletedPackage);
18020
18021        final boolean disabledSystem;
18022
18023        // Remove existing system package
18024        removePackageLI(deletedPackage, true);
18025
18026        synchronized (mPackages) {
18027            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
18028        }
18029        if (!disabledSystem) {
18030            // We didn't need to disable the .apk as a current system package,
18031            // which means we are replacing another update that is already
18032            // installed.  We need to make sure to delete the older one's .apk.
18033            res.removedInfo.args = createInstallArgsForExisting(0,
18034                    deletedPackage.applicationInfo.getCodePath(),
18035                    deletedPackage.applicationInfo.getResourcePath(),
18036                    getAppDexInstructionSets(deletedPackage.applicationInfo));
18037        } else {
18038            res.removedInfo.args = null;
18039        }
18040
18041        // Successfully disabled the old package. Now proceed with re-installation
18042        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18043                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18044        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
18045
18046        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18047        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18048                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18049
18050        PackageParser.Package newPackage = null;
18051        try {
18052            // Add the package to the internal data structures
18053            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18054
18055            // Set the update and install times
18056            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18057            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18058                    System.currentTimeMillis());
18059
18060            // Update the package dynamic state if succeeded
18061            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18062                // Now that the install succeeded make sure we remove data
18063                // directories for any child package the update removed.
18064                final int deletedChildCount = (deletedPackage.childPackages != null)
18065                        ? deletedPackage.childPackages.size() : 0;
18066                final int newChildCount = (newPackage.childPackages != null)
18067                        ? newPackage.childPackages.size() : 0;
18068                for (int i = 0; i < deletedChildCount; i++) {
18069                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18070                    boolean childPackageDeleted = true;
18071                    for (int j = 0; j < newChildCount; j++) {
18072                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18073                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18074                            childPackageDeleted = false;
18075                            break;
18076                        }
18077                    }
18078                    if (childPackageDeleted) {
18079                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18080                                deletedChildPkg.packageName);
18081                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18082                            PackageRemovedInfo removedChildRes = res.removedInfo
18083                                    .removedChildPackages.get(deletedChildPkg.packageName);
18084                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18085                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18086                        }
18087                    }
18088                }
18089
18090                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18091                        installReason);
18092                prepareAppDataAfterInstallLIF(newPackage);
18093
18094                mDexManager.notifyPackageUpdated(newPackage.packageName,
18095                            newPackage.baseCodePath, newPackage.splitCodePaths);
18096            }
18097        } catch (PackageManagerException e) {
18098            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18099            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18100        }
18101
18102        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18103            // Re installation failed. Restore old information
18104            // Remove new pkg information
18105            if (newPackage != null) {
18106                removeInstalledPackageLI(newPackage, true);
18107            }
18108            // Add back the old system package
18109            try {
18110                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18111            } catch (PackageManagerException e) {
18112                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18113            }
18114
18115            synchronized (mPackages) {
18116                if (disabledSystem) {
18117                    enableSystemPackageLPw(deletedPackage);
18118                }
18119
18120                // Ensure the installer package name up to date
18121                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18122
18123                // Update permissions for restored package
18124                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18125
18126                mSettings.writeLPr();
18127            }
18128
18129            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18130                    + " after failed upgrade");
18131        }
18132    }
18133
18134    /**
18135     * Checks whether the parent or any of the child packages have a change shared
18136     * user. For a package to be a valid update the shred users of the parent and
18137     * the children should match. We may later support changing child shared users.
18138     * @param oldPkg The updated package.
18139     * @param newPkg The update package.
18140     * @return The shared user that change between the versions.
18141     */
18142    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18143            PackageParser.Package newPkg) {
18144        // Check parent shared user
18145        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18146            return newPkg.packageName;
18147        }
18148        // Check child shared users
18149        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18150        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18151        for (int i = 0; i < newChildCount; i++) {
18152            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18153            // If this child was present, did it have the same shared user?
18154            for (int j = 0; j < oldChildCount; j++) {
18155                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18156                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18157                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18158                    return newChildPkg.packageName;
18159                }
18160            }
18161        }
18162        return null;
18163    }
18164
18165    private void removeNativeBinariesLI(PackageSetting ps) {
18166        // Remove the lib path for the parent package
18167        if (ps != null) {
18168            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18169            // Remove the lib path for the child packages
18170            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18171            for (int i = 0; i < childCount; i++) {
18172                PackageSetting childPs = null;
18173                synchronized (mPackages) {
18174                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18175                }
18176                if (childPs != null) {
18177                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18178                            .legacyNativeLibraryPathString);
18179                }
18180            }
18181        }
18182    }
18183
18184    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18185        // Enable the parent package
18186        mSettings.enableSystemPackageLPw(pkg.packageName);
18187        // Enable the child packages
18188        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18189        for (int i = 0; i < childCount; i++) {
18190            PackageParser.Package childPkg = pkg.childPackages.get(i);
18191            mSettings.enableSystemPackageLPw(childPkg.packageName);
18192        }
18193    }
18194
18195    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18196            PackageParser.Package newPkg) {
18197        // Disable the parent package (parent always replaced)
18198        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18199        // Disable the child packages
18200        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18201        for (int i = 0; i < childCount; i++) {
18202            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18203            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18204            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18205        }
18206        return disabled;
18207    }
18208
18209    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18210            String installerPackageName) {
18211        // Enable the parent package
18212        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18213        // Enable the child packages
18214        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18215        for (int i = 0; i < childCount; i++) {
18216            PackageParser.Package childPkg = pkg.childPackages.get(i);
18217            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18218        }
18219    }
18220
18221    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18222        // Collect all used permissions in the UID
18223        ArraySet<String> usedPermissions = new ArraySet<>();
18224        final int packageCount = su.packages.size();
18225        for (int i = 0; i < packageCount; i++) {
18226            PackageSetting ps = su.packages.valueAt(i);
18227            if (ps.pkg == null) {
18228                continue;
18229            }
18230            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18231            for (int j = 0; j < requestedPermCount; j++) {
18232                String permission = ps.pkg.requestedPermissions.get(j);
18233                BasePermission bp = mSettings.mPermissions.get(permission);
18234                if (bp != null) {
18235                    usedPermissions.add(permission);
18236                }
18237            }
18238        }
18239
18240        PermissionsState permissionsState = su.getPermissionsState();
18241        // Prune install permissions
18242        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18243        final int installPermCount = installPermStates.size();
18244        for (int i = installPermCount - 1; i >= 0;  i--) {
18245            PermissionState permissionState = installPermStates.get(i);
18246            if (!usedPermissions.contains(permissionState.getName())) {
18247                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18248                if (bp != null) {
18249                    permissionsState.revokeInstallPermission(bp);
18250                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18251                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18252                }
18253            }
18254        }
18255
18256        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18257
18258        // Prune runtime permissions
18259        for (int userId : allUserIds) {
18260            List<PermissionState> runtimePermStates = permissionsState
18261                    .getRuntimePermissionStates(userId);
18262            final int runtimePermCount = runtimePermStates.size();
18263            for (int i = runtimePermCount - 1; i >= 0; i--) {
18264                PermissionState permissionState = runtimePermStates.get(i);
18265                if (!usedPermissions.contains(permissionState.getName())) {
18266                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18267                    if (bp != null) {
18268                        permissionsState.revokeRuntimePermission(bp, userId);
18269                        permissionsState.updatePermissionFlags(bp, userId,
18270                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18271                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18272                                runtimePermissionChangedUserIds, userId);
18273                    }
18274                }
18275            }
18276        }
18277
18278        return runtimePermissionChangedUserIds;
18279    }
18280
18281    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18282            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18283        // Update the parent package setting
18284        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18285                res, user, installReason);
18286        // Update the child packages setting
18287        final int childCount = (newPackage.childPackages != null)
18288                ? newPackage.childPackages.size() : 0;
18289        for (int i = 0; i < childCount; i++) {
18290            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18291            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18292            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18293                    childRes.origUsers, childRes, user, installReason);
18294        }
18295    }
18296
18297    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18298            String installerPackageName, int[] allUsers, int[] installedForUsers,
18299            PackageInstalledInfo res, UserHandle user, int installReason) {
18300        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18301
18302        String pkgName = newPackage.packageName;
18303        synchronized (mPackages) {
18304            //write settings. the installStatus will be incomplete at this stage.
18305            //note that the new package setting would have already been
18306            //added to mPackages. It hasn't been persisted yet.
18307            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18308            // TODO: Remove this write? It's also written at the end of this method
18309            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18310            mSettings.writeLPr();
18311            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18312        }
18313
18314        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18315        synchronized (mPackages) {
18316            updatePermissionsLPw(newPackage.packageName, newPackage,
18317                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18318                            ? UPDATE_PERMISSIONS_ALL : 0));
18319            // For system-bundled packages, we assume that installing an upgraded version
18320            // of the package implies that the user actually wants to run that new code,
18321            // so we enable the package.
18322            PackageSetting ps = mSettings.mPackages.get(pkgName);
18323            final int userId = user.getIdentifier();
18324            if (ps != null) {
18325                if (isSystemApp(newPackage)) {
18326                    if (DEBUG_INSTALL) {
18327                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18328                    }
18329                    // Enable system package for requested users
18330                    if (res.origUsers != null) {
18331                        for (int origUserId : res.origUsers) {
18332                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18333                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18334                                        origUserId, installerPackageName);
18335                            }
18336                        }
18337                    }
18338                    // Also convey the prior install/uninstall state
18339                    if (allUsers != null && installedForUsers != null) {
18340                        for (int currentUserId : allUsers) {
18341                            final boolean installed = ArrayUtils.contains(
18342                                    installedForUsers, currentUserId);
18343                            if (DEBUG_INSTALL) {
18344                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18345                            }
18346                            ps.setInstalled(installed, currentUserId);
18347                        }
18348                        // these install state changes will be persisted in the
18349                        // upcoming call to mSettings.writeLPr().
18350                    }
18351                }
18352                // It's implied that when a user requests installation, they want the app to be
18353                // installed and enabled.
18354                if (userId != UserHandle.USER_ALL) {
18355                    ps.setInstalled(true, userId);
18356                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18357                }
18358
18359                // When replacing an existing package, preserve the original install reason for all
18360                // users that had the package installed before.
18361                final Set<Integer> previousUserIds = new ArraySet<>();
18362                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18363                    final int installReasonCount = res.removedInfo.installReasons.size();
18364                    for (int i = 0; i < installReasonCount; i++) {
18365                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18366                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18367                        ps.setInstallReason(previousInstallReason, previousUserId);
18368                        previousUserIds.add(previousUserId);
18369                    }
18370                }
18371
18372                // Set install reason for users that are having the package newly installed.
18373                if (userId == UserHandle.USER_ALL) {
18374                    for (int currentUserId : sUserManager.getUserIds()) {
18375                        if (!previousUserIds.contains(currentUserId)) {
18376                            ps.setInstallReason(installReason, currentUserId);
18377                        }
18378                    }
18379                } else if (!previousUserIds.contains(userId)) {
18380                    ps.setInstallReason(installReason, userId);
18381                }
18382                mSettings.writeKernelMappingLPr(ps);
18383            }
18384            res.name = pkgName;
18385            res.uid = newPackage.applicationInfo.uid;
18386            res.pkg = newPackage;
18387            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18388            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18389            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18390            //to update install status
18391            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18392            mSettings.writeLPr();
18393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18394        }
18395
18396        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18397    }
18398
18399    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18400        try {
18401            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18402            installPackageLI(args, res);
18403        } finally {
18404            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18405        }
18406    }
18407
18408    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18409        final int installFlags = args.installFlags;
18410        final String installerPackageName = args.installerPackageName;
18411        final String volumeUuid = args.volumeUuid;
18412        final File tmpPackageFile = new File(args.getCodePath());
18413        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18414        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18415                || (args.volumeUuid != null));
18416        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18417        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18418        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18419        final boolean virtualPreload =
18420                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18421        boolean replace = false;
18422        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18423        if (args.move != null) {
18424            // moving a complete application; perform an initial scan on the new install location
18425            scanFlags |= SCAN_INITIAL;
18426        }
18427        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18428            scanFlags |= SCAN_DONT_KILL_APP;
18429        }
18430        if (instantApp) {
18431            scanFlags |= SCAN_AS_INSTANT_APP;
18432        }
18433        if (fullApp) {
18434            scanFlags |= SCAN_AS_FULL_APP;
18435        }
18436        if (virtualPreload) {
18437            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18438        }
18439
18440        // Result object to be returned
18441        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18442        res.installerPackageName = installerPackageName;
18443
18444        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18445
18446        // Sanity check
18447        if (instantApp && (forwardLocked || onExternal)) {
18448            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18449                    + " external=" + onExternal);
18450            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18451            return;
18452        }
18453
18454        // Retrieve PackageSettings and parse package
18455        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18456                | PackageParser.PARSE_ENFORCE_CODE
18457                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18458                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18459                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18460                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18461        PackageParser pp = new PackageParser();
18462        pp.setSeparateProcesses(mSeparateProcesses);
18463        pp.setDisplayMetrics(mMetrics);
18464        pp.setCallback(mPackageParserCallback);
18465
18466        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18467        final PackageParser.Package pkg;
18468        try {
18469            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18470        } catch (PackageParserException e) {
18471            res.setError("Failed parse during installPackageLI", e);
18472            return;
18473        } finally {
18474            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18475        }
18476
18477        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18478        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18479            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18480            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18481                    "Instant app package must target O");
18482            return;
18483        }
18484        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18485            Slog.w(TAG, "Instant app package " + pkg.packageName
18486                    + " does not target targetSandboxVersion 2");
18487            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18488                    "Instant app package must use targetSanboxVersion 2");
18489            return;
18490        }
18491
18492        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18493            // Static shared libraries have synthetic package names
18494            renameStaticSharedLibraryPackage(pkg);
18495
18496            // No static shared libs on external storage
18497            if (onExternal) {
18498                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18499                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18500                        "Packages declaring static-shared libs cannot be updated");
18501                return;
18502            }
18503        }
18504
18505        // If we are installing a clustered package add results for the children
18506        if (pkg.childPackages != null) {
18507            synchronized (mPackages) {
18508                final int childCount = pkg.childPackages.size();
18509                for (int i = 0; i < childCount; i++) {
18510                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18511                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18512                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18513                    childRes.pkg = childPkg;
18514                    childRes.name = childPkg.packageName;
18515                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18516                    if (childPs != null) {
18517                        childRes.origUsers = childPs.queryInstalledUsers(
18518                                sUserManager.getUserIds(), true);
18519                    }
18520                    if ((mPackages.containsKey(childPkg.packageName))) {
18521                        childRes.removedInfo = new PackageRemovedInfo(this);
18522                        childRes.removedInfo.removedPackage = childPkg.packageName;
18523                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18524                    }
18525                    if (res.addedChildPackages == null) {
18526                        res.addedChildPackages = new ArrayMap<>();
18527                    }
18528                    res.addedChildPackages.put(childPkg.packageName, childRes);
18529                }
18530            }
18531        }
18532
18533        // If package doesn't declare API override, mark that we have an install
18534        // time CPU ABI override.
18535        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18536            pkg.cpuAbiOverride = args.abiOverride;
18537        }
18538
18539        String pkgName = res.name = pkg.packageName;
18540        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18541            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18542                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18543                return;
18544            }
18545        }
18546
18547        try {
18548            // either use what we've been given or parse directly from the APK
18549            if (args.certificates != null) {
18550                try {
18551                    PackageParser.populateCertificates(pkg, args.certificates);
18552                } catch (PackageParserException e) {
18553                    // there was something wrong with the certificates we were given;
18554                    // try to pull them from the APK
18555                    PackageParser.collectCertificates(pkg, parseFlags);
18556                }
18557            } else {
18558                PackageParser.collectCertificates(pkg, parseFlags);
18559            }
18560        } catch (PackageParserException e) {
18561            res.setError("Failed collect during installPackageLI", e);
18562            return;
18563        }
18564
18565        // Get rid of all references to package scan path via parser.
18566        pp = null;
18567        String oldCodePath = null;
18568        boolean systemApp = false;
18569        synchronized (mPackages) {
18570            // Check if installing already existing package
18571            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18572                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18573                if (pkg.mOriginalPackages != null
18574                        && pkg.mOriginalPackages.contains(oldName)
18575                        && mPackages.containsKey(oldName)) {
18576                    // This package is derived from an original package,
18577                    // and this device has been updating from that original
18578                    // name.  We must continue using the original name, so
18579                    // rename the new package here.
18580                    pkg.setPackageName(oldName);
18581                    pkgName = pkg.packageName;
18582                    replace = true;
18583                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18584                            + oldName + " pkgName=" + pkgName);
18585                } else if (mPackages.containsKey(pkgName)) {
18586                    // This package, under its official name, already exists
18587                    // on the device; we should replace it.
18588                    replace = true;
18589                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18590                }
18591
18592                // Child packages are installed through the parent package
18593                if (pkg.parentPackage != null) {
18594                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18595                            "Package " + pkg.packageName + " is child of package "
18596                                    + pkg.parentPackage.parentPackage + ". Child packages "
18597                                    + "can be updated only through the parent package.");
18598                    return;
18599                }
18600
18601                if (replace) {
18602                    // Prevent apps opting out from runtime permissions
18603                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18604                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18605                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18606                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18607                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18608                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18609                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18610                                        + " doesn't support runtime permissions but the old"
18611                                        + " target SDK " + oldTargetSdk + " does.");
18612                        return;
18613                    }
18614                    // Prevent persistent apps from being updated
18615                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
18616                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
18617                                "Package " + oldPackage.packageName + " is a persistent app. "
18618                                        + "Persistent apps are not updateable.");
18619                        return;
18620                    }
18621                    // Prevent apps from downgrading their targetSandbox.
18622                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18623                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18624                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18625                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18626                                "Package " + pkg.packageName + " new target sandbox "
18627                                + newTargetSandbox + " is incompatible with the previous value of"
18628                                + oldTargetSandbox + ".");
18629                        return;
18630                    }
18631
18632                    // Prevent installing of child packages
18633                    if (oldPackage.parentPackage != null) {
18634                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18635                                "Package " + pkg.packageName + " is child of package "
18636                                        + oldPackage.parentPackage + ". Child packages "
18637                                        + "can be updated only through the parent package.");
18638                        return;
18639                    }
18640                }
18641            }
18642
18643            PackageSetting ps = mSettings.mPackages.get(pkgName);
18644            if (ps != null) {
18645                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18646
18647                // Static shared libs have same package with different versions where
18648                // we internally use a synthetic package name to allow multiple versions
18649                // of the same package, therefore we need to compare signatures against
18650                // the package setting for the latest library version.
18651                PackageSetting signatureCheckPs = ps;
18652                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18653                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18654                    if (libraryEntry != null) {
18655                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18656                    }
18657                }
18658
18659                // Quick sanity check that we're signed correctly if updating;
18660                // we'll check this again later when scanning, but we want to
18661                // bail early here before tripping over redefined permissions.
18662                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18663                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18664                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18665                                + pkg.packageName + " upgrade keys do not match the "
18666                                + "previously installed version");
18667                        return;
18668                    }
18669                } else {
18670                    try {
18671                        verifySignaturesLP(signatureCheckPs, pkg);
18672                    } catch (PackageManagerException e) {
18673                        res.setError(e.error, e.getMessage());
18674                        return;
18675                    }
18676                }
18677
18678                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18679                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18680                    systemApp = (ps.pkg.applicationInfo.flags &
18681                            ApplicationInfo.FLAG_SYSTEM) != 0;
18682                }
18683                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18684            }
18685
18686            int N = pkg.permissions.size();
18687            for (int i = N-1; i >= 0; i--) {
18688                PackageParser.Permission perm = pkg.permissions.get(i);
18689                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18690
18691                // Don't allow anyone but the system to define ephemeral permissions.
18692                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18693                        && !systemApp) {
18694                    Slog.w(TAG, "Non-System package " + pkg.packageName
18695                            + " attempting to delcare ephemeral permission "
18696                            + perm.info.name + "; Removing ephemeral.");
18697                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18698                }
18699                // Check whether the newly-scanned package wants to define an already-defined perm
18700                if (bp != null) {
18701                    // If the defining package is signed with our cert, it's okay.  This
18702                    // also includes the "updating the same package" case, of course.
18703                    // "updating same package" could also involve key-rotation.
18704                    final boolean sigsOk;
18705                    if (bp.sourcePackage.equals(pkg.packageName)
18706                            && (bp.packageSetting instanceof PackageSetting)
18707                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18708                                    scanFlags))) {
18709                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18710                    } else {
18711                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18712                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18713                    }
18714                    if (!sigsOk) {
18715                        // If the owning package is the system itself, we log but allow
18716                        // install to proceed; we fail the install on all other permission
18717                        // redefinitions.
18718                        if (!bp.sourcePackage.equals("android")) {
18719                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18720                                    + pkg.packageName + " attempting to redeclare permission "
18721                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18722                            res.origPermission = perm.info.name;
18723                            res.origPackage = bp.sourcePackage;
18724                            return;
18725                        } else {
18726                            Slog.w(TAG, "Package " + pkg.packageName
18727                                    + " attempting to redeclare system permission "
18728                                    + perm.info.name + "; ignoring new declaration");
18729                            pkg.permissions.remove(i);
18730                        }
18731                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18732                        // Prevent apps to change protection level to dangerous from any other
18733                        // type as this would allow a privilege escalation where an app adds a
18734                        // normal/signature permission in other app's group and later redefines
18735                        // it as dangerous leading to the group auto-grant.
18736                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18737                                == PermissionInfo.PROTECTION_DANGEROUS) {
18738                            if (bp != null && !bp.isRuntime()) {
18739                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18740                                        + "non-runtime permission " + perm.info.name
18741                                        + " to runtime; keeping old protection level");
18742                                perm.info.protectionLevel = bp.protectionLevel;
18743                            }
18744                        }
18745                    }
18746                }
18747            }
18748        }
18749
18750        if (systemApp) {
18751            if (onExternal) {
18752                // Abort update; system app can't be replaced with app on sdcard
18753                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18754                        "Cannot install updates to system apps on sdcard");
18755                return;
18756            } else if (instantApp) {
18757                // Abort update; system app can't be replaced with an instant app
18758                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18759                        "Cannot update a system app with an instant app");
18760                return;
18761            }
18762        }
18763
18764        if (args.move != null) {
18765            // We did an in-place move, so dex is ready to roll
18766            scanFlags |= SCAN_NO_DEX;
18767            scanFlags |= SCAN_MOVE;
18768
18769            synchronized (mPackages) {
18770                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18771                if (ps == null) {
18772                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18773                            "Missing settings for moved package " + pkgName);
18774                }
18775
18776                // We moved the entire application as-is, so bring over the
18777                // previously derived ABI information.
18778                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18779                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18780            }
18781
18782        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18783            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18784            scanFlags |= SCAN_NO_DEX;
18785
18786            try {
18787                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18788                    args.abiOverride : pkg.cpuAbiOverride);
18789                final boolean extractNativeLibs = !pkg.isLibrary();
18790                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18791                        extractNativeLibs, mAppLib32InstallDir);
18792            } catch (PackageManagerException pme) {
18793                Slog.e(TAG, "Error deriving application ABI", pme);
18794                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18795                return;
18796            }
18797
18798            // Shared libraries for the package need to be updated.
18799            synchronized (mPackages) {
18800                try {
18801                    updateSharedLibrariesLPr(pkg, null);
18802                } catch (PackageManagerException e) {
18803                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18804                }
18805            }
18806        }
18807
18808        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18809            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18810            return;
18811        }
18812
18813        if (!instantApp) {
18814            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18815        } else {
18816            if (DEBUG_DOMAIN_VERIFICATION) {
18817                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
18818            }
18819        }
18820
18821        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18822                "installPackageLI")) {
18823            if (replace) {
18824                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18825                    // Static libs have a synthetic package name containing the version
18826                    // and cannot be updated as an update would get a new package name,
18827                    // unless this is the exact same version code which is useful for
18828                    // development.
18829                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18830                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18831                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18832                                + "static-shared libs cannot be updated");
18833                        return;
18834                    }
18835                }
18836                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18837                        installerPackageName, res, args.installReason);
18838            } else {
18839                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18840                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18841            }
18842        }
18843
18844        // Check whether we need to dexopt the app.
18845        //
18846        // NOTE: it is IMPORTANT to call dexopt:
18847        //   - after doRename which will sync the package data from PackageParser.Package and its
18848        //     corresponding ApplicationInfo.
18849        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
18850        //     uid of the application (pkg.applicationInfo.uid).
18851        //     This update happens in place!
18852        //
18853        // We only need to dexopt if the package meets ALL of the following conditions:
18854        //   1) it is not forward locked.
18855        //   2) it is not on on an external ASEC container.
18856        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18857        //
18858        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18859        // complete, so we skip this step during installation. Instead, we'll take extra time
18860        // the first time the instant app starts. It's preferred to do it this way to provide
18861        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18862        // middle of running an instant app. The default behaviour can be overridden
18863        // via gservices.
18864        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
18865                && !forwardLocked
18866                && !pkg.applicationInfo.isExternalAsec()
18867                && (!instantApp || Global.getInt(mContext.getContentResolver(),
18868                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18869
18870        if (performDexopt) {
18871            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18872            // Do not run PackageDexOptimizer through the local performDexOpt
18873            // method because `pkg` may not be in `mPackages` yet.
18874            //
18875            // Also, don't fail application installs if the dexopt step fails.
18876            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18877                    REASON_INSTALL,
18878                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
18879            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18880                    null /* instructionSets */,
18881                    getOrCreateCompilerPackageStats(pkg),
18882                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18883                    dexoptOptions);
18884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18885        }
18886
18887        // Notify BackgroundDexOptService that the package has been changed.
18888        // If this is an update of a package which used to fail to compile,
18889        // BackgroundDexOptService will remove it from its blacklist.
18890        // TODO: Layering violation
18891        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18892
18893        synchronized (mPackages) {
18894            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18895            if (ps != null) {
18896                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18897                ps.setUpdateAvailable(false /*updateAvailable*/);
18898            }
18899
18900            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18901            for (int i = 0; i < childCount; i++) {
18902                PackageParser.Package childPkg = pkg.childPackages.get(i);
18903                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18904                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18905                if (childPs != null) {
18906                    childRes.newUsers = childPs.queryInstalledUsers(
18907                            sUserManager.getUserIds(), true);
18908                }
18909            }
18910
18911            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18912                updateSequenceNumberLP(ps, res.newUsers);
18913                updateInstantAppInstallerLocked(pkgName);
18914            }
18915        }
18916    }
18917
18918    private void startIntentFilterVerifications(int userId, boolean replacing,
18919            PackageParser.Package pkg) {
18920        if (mIntentFilterVerifierComponent == null) {
18921            Slog.w(TAG, "No IntentFilter verification will not be done as "
18922                    + "there is no IntentFilterVerifier available!");
18923            return;
18924        }
18925
18926        final int verifierUid = getPackageUid(
18927                mIntentFilterVerifierComponent.getPackageName(),
18928                MATCH_DEBUG_TRIAGED_MISSING,
18929                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18930
18931        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18932        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18933        mHandler.sendMessage(msg);
18934
18935        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18936        for (int i = 0; i < childCount; i++) {
18937            PackageParser.Package childPkg = pkg.childPackages.get(i);
18938            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18939            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18940            mHandler.sendMessage(msg);
18941        }
18942    }
18943
18944    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18945            PackageParser.Package pkg) {
18946        int size = pkg.activities.size();
18947        if (size == 0) {
18948            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18949                    "No activity, so no need to verify any IntentFilter!");
18950            return;
18951        }
18952
18953        final boolean hasDomainURLs = hasDomainURLs(pkg);
18954        if (!hasDomainURLs) {
18955            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18956                    "No domain URLs, so no need to verify any IntentFilter!");
18957            return;
18958        }
18959
18960        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18961                + " if any IntentFilter from the " + size
18962                + " Activities needs verification ...");
18963
18964        int count = 0;
18965        final String packageName = pkg.packageName;
18966
18967        synchronized (mPackages) {
18968            // If this is a new install and we see that we've already run verification for this
18969            // package, we have nothing to do: it means the state was restored from backup.
18970            if (!replacing) {
18971                IntentFilterVerificationInfo ivi =
18972                        mSettings.getIntentFilterVerificationLPr(packageName);
18973                if (ivi != null) {
18974                    if (DEBUG_DOMAIN_VERIFICATION) {
18975                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18976                                + ivi.getStatusString());
18977                    }
18978                    return;
18979                }
18980            }
18981
18982            // If any filters need to be verified, then all need to be.
18983            boolean needToVerify = false;
18984            for (PackageParser.Activity a : pkg.activities) {
18985                for (ActivityIntentInfo filter : a.intents) {
18986                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18987                        if (DEBUG_DOMAIN_VERIFICATION) {
18988                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18989                        }
18990                        needToVerify = true;
18991                        break;
18992                    }
18993                }
18994            }
18995
18996            if (needToVerify) {
18997                final int verificationId = mIntentFilterVerificationToken++;
18998                for (PackageParser.Activity a : pkg.activities) {
18999                    for (ActivityIntentInfo filter : a.intents) {
19000                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
19001                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
19002                                    "Verification needed for IntentFilter:" + filter.toString());
19003                            mIntentFilterVerifier.addOneIntentFilterVerification(
19004                                    verifierUid, userId, verificationId, filter, packageName);
19005                            count++;
19006                        }
19007                    }
19008                }
19009            }
19010        }
19011
19012        if (count > 0) {
19013            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
19014                    + " IntentFilter verification" + (count > 1 ? "s" : "")
19015                    +  " for userId:" + userId);
19016            mIntentFilterVerifier.startVerifications(userId);
19017        } else {
19018            if (DEBUG_DOMAIN_VERIFICATION) {
19019                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
19020            }
19021        }
19022    }
19023
19024    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
19025        final ComponentName cn  = filter.activity.getComponentName();
19026        final String packageName = cn.getPackageName();
19027
19028        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
19029                packageName);
19030        if (ivi == null) {
19031            return true;
19032        }
19033        int status = ivi.getStatus();
19034        switch (status) {
19035            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
19036            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
19037                return true;
19038
19039            default:
19040                // Nothing to do
19041                return false;
19042        }
19043    }
19044
19045    private static boolean isMultiArch(ApplicationInfo info) {
19046        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
19047    }
19048
19049    private static boolean isExternal(PackageParser.Package pkg) {
19050        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19051    }
19052
19053    private static boolean isExternal(PackageSetting ps) {
19054        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19055    }
19056
19057    private static boolean isSystemApp(PackageParser.Package pkg) {
19058        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19059    }
19060
19061    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19062        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19063    }
19064
19065    private static boolean hasDomainURLs(PackageParser.Package pkg) {
19066        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19067    }
19068
19069    private static boolean isSystemApp(PackageSetting ps) {
19070        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19071    }
19072
19073    private static boolean isUpdatedSystemApp(PackageSetting ps) {
19074        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19075    }
19076
19077    private int packageFlagsToInstallFlags(PackageSetting ps) {
19078        int installFlags = 0;
19079        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19080            // This existing package was an external ASEC install when we have
19081            // the external flag without a UUID
19082            installFlags |= PackageManager.INSTALL_EXTERNAL;
19083        }
19084        if (ps.isForwardLocked()) {
19085            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19086        }
19087        return installFlags;
19088    }
19089
19090    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19091        if (isExternal(pkg)) {
19092            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19093                return StorageManager.UUID_PRIMARY_PHYSICAL;
19094            } else {
19095                return pkg.volumeUuid;
19096            }
19097        } else {
19098            return StorageManager.UUID_PRIVATE_INTERNAL;
19099        }
19100    }
19101
19102    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19103        if (isExternal(pkg)) {
19104            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19105                return mSettings.getExternalVersion();
19106            } else {
19107                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19108            }
19109        } else {
19110            return mSettings.getInternalVersion();
19111        }
19112    }
19113
19114    private void deleteTempPackageFiles() {
19115        final FilenameFilter filter = new FilenameFilter() {
19116            public boolean accept(File dir, String name) {
19117                return name.startsWith("vmdl") && name.endsWith(".tmp");
19118            }
19119        };
19120        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19121            file.delete();
19122        }
19123    }
19124
19125    @Override
19126    public void deletePackageAsUser(String packageName, int versionCode,
19127            IPackageDeleteObserver observer, int userId, int flags) {
19128        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19129                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19130    }
19131
19132    @Override
19133    public void deletePackageVersioned(VersionedPackage versionedPackage,
19134            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19135        final int callingUid = Binder.getCallingUid();
19136        mContext.enforceCallingOrSelfPermission(
19137                android.Manifest.permission.DELETE_PACKAGES, null);
19138        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19139        Preconditions.checkNotNull(versionedPackage);
19140        Preconditions.checkNotNull(observer);
19141        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19142                PackageManager.VERSION_CODE_HIGHEST,
19143                Integer.MAX_VALUE, "versionCode must be >= -1");
19144
19145        final String packageName = versionedPackage.getPackageName();
19146        final int versionCode = versionedPackage.getVersionCode();
19147        final String internalPackageName;
19148        synchronized (mPackages) {
19149            // Normalize package name to handle renamed packages and static libs
19150            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19151                    versionedPackage.getVersionCode());
19152        }
19153
19154        final int uid = Binder.getCallingUid();
19155        if (!isOrphaned(internalPackageName)
19156                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19157            try {
19158                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19159                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19160                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19161                observer.onUserActionRequired(intent);
19162            } catch (RemoteException re) {
19163            }
19164            return;
19165        }
19166        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19167        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19168        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19169            mContext.enforceCallingOrSelfPermission(
19170                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19171                    "deletePackage for user " + userId);
19172        }
19173
19174        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19175            try {
19176                observer.onPackageDeleted(packageName,
19177                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19178            } catch (RemoteException re) {
19179            }
19180            return;
19181        }
19182
19183        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19184            try {
19185                observer.onPackageDeleted(packageName,
19186                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19187            } catch (RemoteException re) {
19188            }
19189            return;
19190        }
19191
19192        if (DEBUG_REMOVE) {
19193            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19194                    + " deleteAllUsers: " + deleteAllUsers + " version="
19195                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19196                    ? "VERSION_CODE_HIGHEST" : versionCode));
19197        }
19198        // Queue up an async operation since the package deletion may take a little while.
19199        mHandler.post(new Runnable() {
19200            public void run() {
19201                mHandler.removeCallbacks(this);
19202                int returnCode;
19203                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19204                boolean doDeletePackage = true;
19205                if (ps != null) {
19206                    final boolean targetIsInstantApp =
19207                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19208                    doDeletePackage = !targetIsInstantApp
19209                            || canViewInstantApps;
19210                }
19211                if (doDeletePackage) {
19212                    if (!deleteAllUsers) {
19213                        returnCode = deletePackageX(internalPackageName, versionCode,
19214                                userId, deleteFlags);
19215                    } else {
19216                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19217                                internalPackageName, users);
19218                        // If nobody is blocking uninstall, proceed with delete for all users
19219                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19220                            returnCode = deletePackageX(internalPackageName, versionCode,
19221                                    userId, deleteFlags);
19222                        } else {
19223                            // Otherwise uninstall individually for users with blockUninstalls=false
19224                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19225                            for (int userId : users) {
19226                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19227                                    returnCode = deletePackageX(internalPackageName, versionCode,
19228                                            userId, userFlags);
19229                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19230                                        Slog.w(TAG, "Package delete failed for user " + userId
19231                                                + ", returnCode " + returnCode);
19232                                    }
19233                                }
19234                            }
19235                            // The app has only been marked uninstalled for certain users.
19236                            // We still need to report that delete was blocked
19237                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19238                        }
19239                    }
19240                } else {
19241                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19242                }
19243                try {
19244                    observer.onPackageDeleted(packageName, returnCode, null);
19245                } catch (RemoteException e) {
19246                    Log.i(TAG, "Observer no longer exists.");
19247                } //end catch
19248            } //end run
19249        });
19250    }
19251
19252    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19253        if (pkg.staticSharedLibName != null) {
19254            return pkg.manifestPackageName;
19255        }
19256        return pkg.packageName;
19257    }
19258
19259    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19260        // Handle renamed packages
19261        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19262        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19263
19264        // Is this a static library?
19265        SparseArray<SharedLibraryEntry> versionedLib =
19266                mStaticLibsByDeclaringPackage.get(packageName);
19267        if (versionedLib == null || versionedLib.size() <= 0) {
19268            return packageName;
19269        }
19270
19271        // Figure out which lib versions the caller can see
19272        SparseIntArray versionsCallerCanSee = null;
19273        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19274        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19275                && callingAppId != Process.ROOT_UID) {
19276            versionsCallerCanSee = new SparseIntArray();
19277            String libName = versionedLib.valueAt(0).info.getName();
19278            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19279            if (uidPackages != null) {
19280                for (String uidPackage : uidPackages) {
19281                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19282                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19283                    if (libIdx >= 0) {
19284                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19285                        versionsCallerCanSee.append(libVersion, libVersion);
19286                    }
19287                }
19288            }
19289        }
19290
19291        // Caller can see nothing - done
19292        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19293            return packageName;
19294        }
19295
19296        // Find the version the caller can see and the app version code
19297        SharedLibraryEntry highestVersion = null;
19298        final int versionCount = versionedLib.size();
19299        for (int i = 0; i < versionCount; i++) {
19300            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19301            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19302                    libEntry.info.getVersion()) < 0) {
19303                continue;
19304            }
19305            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19306            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19307                if (libVersionCode == versionCode) {
19308                    return libEntry.apk;
19309                }
19310            } else if (highestVersion == null) {
19311                highestVersion = libEntry;
19312            } else if (libVersionCode  > highestVersion.info
19313                    .getDeclaringPackage().getVersionCode()) {
19314                highestVersion = libEntry;
19315            }
19316        }
19317
19318        if (highestVersion != null) {
19319            return highestVersion.apk;
19320        }
19321
19322        return packageName;
19323    }
19324
19325    boolean isCallerVerifier(int callingUid) {
19326        final int callingUserId = UserHandle.getUserId(callingUid);
19327        return mRequiredVerifierPackage != null &&
19328                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19329    }
19330
19331    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19332        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19333              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19334            return true;
19335        }
19336        final int callingUserId = UserHandle.getUserId(callingUid);
19337        // If the caller installed the pkgName, then allow it to silently uninstall.
19338        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19339            return true;
19340        }
19341
19342        // Allow package verifier to silently uninstall.
19343        if (mRequiredVerifierPackage != null &&
19344                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19345            return true;
19346        }
19347
19348        // Allow package uninstaller to silently uninstall.
19349        if (mRequiredUninstallerPackage != null &&
19350                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19351            return true;
19352        }
19353
19354        // Allow storage manager to silently uninstall.
19355        if (mStorageManagerPackage != null &&
19356                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19357            return true;
19358        }
19359
19360        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19361        // uninstall for device owner provisioning.
19362        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19363                == PERMISSION_GRANTED) {
19364            return true;
19365        }
19366
19367        return false;
19368    }
19369
19370    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19371        int[] result = EMPTY_INT_ARRAY;
19372        for (int userId : userIds) {
19373            if (getBlockUninstallForUser(packageName, userId)) {
19374                result = ArrayUtils.appendInt(result, userId);
19375            }
19376        }
19377        return result;
19378    }
19379
19380    @Override
19381    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19382        final int callingUid = Binder.getCallingUid();
19383        if (getInstantAppPackageName(callingUid) != null
19384                && !isCallerSameApp(packageName, callingUid)) {
19385            return false;
19386        }
19387        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19388    }
19389
19390    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19391        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19392                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19393        try {
19394            if (dpm != null) {
19395                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19396                        /* callingUserOnly =*/ false);
19397                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19398                        : deviceOwnerComponentName.getPackageName();
19399                // Does the package contains the device owner?
19400                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19401                // this check is probably not needed, since DO should be registered as a device
19402                // admin on some user too. (Original bug for this: b/17657954)
19403                if (packageName.equals(deviceOwnerPackageName)) {
19404                    return true;
19405                }
19406                // Does it contain a device admin for any user?
19407                int[] users;
19408                if (userId == UserHandle.USER_ALL) {
19409                    users = sUserManager.getUserIds();
19410                } else {
19411                    users = new int[]{userId};
19412                }
19413                for (int i = 0; i < users.length; ++i) {
19414                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19415                        return true;
19416                    }
19417                }
19418            }
19419        } catch (RemoteException e) {
19420        }
19421        return false;
19422    }
19423
19424    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19425        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19426    }
19427
19428    /**
19429     *  This method is an internal method that could be get invoked either
19430     *  to delete an installed package or to clean up a failed installation.
19431     *  After deleting an installed package, a broadcast is sent to notify any
19432     *  listeners that the package has been removed. For cleaning up a failed
19433     *  installation, the broadcast is not necessary since the package's
19434     *  installation wouldn't have sent the initial broadcast either
19435     *  The key steps in deleting a package are
19436     *  deleting the package information in internal structures like mPackages,
19437     *  deleting the packages base directories through installd
19438     *  updating mSettings to reflect current status
19439     *  persisting settings for later use
19440     *  sending a broadcast if necessary
19441     */
19442    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19443        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19444        final boolean res;
19445
19446        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19447                ? UserHandle.USER_ALL : userId;
19448
19449        if (isPackageDeviceAdmin(packageName, removeUser)) {
19450            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19451            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19452        }
19453
19454        PackageSetting uninstalledPs = null;
19455        PackageParser.Package pkg = null;
19456
19457        // for the uninstall-updates case and restricted profiles, remember the per-
19458        // user handle installed state
19459        int[] allUsers;
19460        synchronized (mPackages) {
19461            uninstalledPs = mSettings.mPackages.get(packageName);
19462            if (uninstalledPs == null) {
19463                Slog.w(TAG, "Not removing non-existent package " + packageName);
19464                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19465            }
19466
19467            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19468                    && uninstalledPs.versionCode != versionCode) {
19469                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19470                        + uninstalledPs.versionCode + " != " + versionCode);
19471                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19472            }
19473
19474            // Static shared libs can be declared by any package, so let us not
19475            // allow removing a package if it provides a lib others depend on.
19476            pkg = mPackages.get(packageName);
19477
19478            allUsers = sUserManager.getUserIds();
19479
19480            if (pkg != null && pkg.staticSharedLibName != null) {
19481                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19482                        pkg.staticSharedLibVersion);
19483                if (libEntry != null) {
19484                    for (int currUserId : allUsers) {
19485                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19486                            continue;
19487                        }
19488                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19489                                libEntry.info, 0, currUserId);
19490                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19491                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19492                                    + " hosting lib " + libEntry.info.getName() + " version "
19493                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19494                                    + " for user " + currUserId);
19495                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19496                        }
19497                    }
19498                }
19499            }
19500
19501            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19502        }
19503
19504        final int freezeUser;
19505        if (isUpdatedSystemApp(uninstalledPs)
19506                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19507            // We're downgrading a system app, which will apply to all users, so
19508            // freeze them all during the downgrade
19509            freezeUser = UserHandle.USER_ALL;
19510        } else {
19511            freezeUser = removeUser;
19512        }
19513
19514        synchronized (mInstallLock) {
19515            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19516            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19517                    deleteFlags, "deletePackageX")) {
19518                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19519                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19520            }
19521            synchronized (mPackages) {
19522                if (res) {
19523                    if (pkg != null) {
19524                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19525                    }
19526                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19527                    updateInstantAppInstallerLocked(packageName);
19528                }
19529            }
19530        }
19531
19532        if (res) {
19533            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19534            info.sendPackageRemovedBroadcasts(killApp);
19535            info.sendSystemPackageUpdatedBroadcasts();
19536            info.sendSystemPackageAppearedBroadcasts();
19537        }
19538        // Force a gc here.
19539        Runtime.getRuntime().gc();
19540        // Delete the resources here after sending the broadcast to let
19541        // other processes clean up before deleting resources.
19542        if (info.args != null) {
19543            synchronized (mInstallLock) {
19544                info.args.doPostDeleteLI(true);
19545            }
19546        }
19547
19548        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19549    }
19550
19551    static class PackageRemovedInfo {
19552        final PackageSender packageSender;
19553        String removedPackage;
19554        String installerPackageName;
19555        int uid = -1;
19556        int removedAppId = -1;
19557        int[] origUsers;
19558        int[] removedUsers = null;
19559        int[] broadcastUsers = null;
19560        SparseArray<Integer> installReasons;
19561        boolean isRemovedPackageSystemUpdate = false;
19562        boolean isUpdate;
19563        boolean dataRemoved;
19564        boolean removedForAllUsers;
19565        boolean isStaticSharedLib;
19566        // Clean up resources deleted packages.
19567        InstallArgs args = null;
19568        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19569        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19570
19571        PackageRemovedInfo(PackageSender packageSender) {
19572            this.packageSender = packageSender;
19573        }
19574
19575        void sendPackageRemovedBroadcasts(boolean killApp) {
19576            sendPackageRemovedBroadcastInternal(killApp);
19577            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19578            for (int i = 0; i < childCount; i++) {
19579                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19580                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19581            }
19582        }
19583
19584        void sendSystemPackageUpdatedBroadcasts() {
19585            if (isRemovedPackageSystemUpdate) {
19586                sendSystemPackageUpdatedBroadcastsInternal();
19587                final int childCount = (removedChildPackages != null)
19588                        ? removedChildPackages.size() : 0;
19589                for (int i = 0; i < childCount; i++) {
19590                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19591                    if (childInfo.isRemovedPackageSystemUpdate) {
19592                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19593                    }
19594                }
19595            }
19596        }
19597
19598        void sendSystemPackageAppearedBroadcasts() {
19599            final int packageCount = (appearedChildPackages != null)
19600                    ? appearedChildPackages.size() : 0;
19601            for (int i = 0; i < packageCount; i++) {
19602                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19603                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19604                    true /*sendBootCompleted*/, false /*startReceiver*/,
19605                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19606            }
19607        }
19608
19609        private void sendSystemPackageUpdatedBroadcastsInternal() {
19610            Bundle extras = new Bundle(2);
19611            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19612            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19613            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19614                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19615            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19616                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19617            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19618                null, null, 0, removedPackage, null, null);
19619            if (installerPackageName != null) {
19620                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19621                        removedPackage, extras, 0 /*flags*/,
19622                        installerPackageName, null, null);
19623                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19624                        removedPackage, extras, 0 /*flags*/,
19625                        installerPackageName, null, null);
19626            }
19627        }
19628
19629        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19630            // Don't send static shared library removal broadcasts as these
19631            // libs are visible only the the apps that depend on them an one
19632            // cannot remove the library if it has a dependency.
19633            if (isStaticSharedLib) {
19634                return;
19635            }
19636            Bundle extras = new Bundle(2);
19637            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19638            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19639            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19640            if (isUpdate || isRemovedPackageSystemUpdate) {
19641                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19642            }
19643            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19644            if (removedPackage != null) {
19645                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19646                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19647                if (installerPackageName != null) {
19648                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19649                            removedPackage, extras, 0 /*flags*/,
19650                            installerPackageName, null, broadcastUsers);
19651                }
19652                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19653                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19654                        removedPackage, extras,
19655                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19656                        null, null, broadcastUsers);
19657                }
19658            }
19659            if (removedAppId >= 0) {
19660                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19661                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19662                    null, null, broadcastUsers);
19663            }
19664        }
19665
19666        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19667            removedUsers = userIds;
19668            if (removedUsers == null) {
19669                broadcastUsers = null;
19670                return;
19671            }
19672
19673            broadcastUsers = EMPTY_INT_ARRAY;
19674            for (int i = userIds.length - 1; i >= 0; --i) {
19675                final int userId = userIds[i];
19676                if (deletedPackageSetting.getInstantApp(userId)) {
19677                    continue;
19678                }
19679                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19680            }
19681        }
19682    }
19683
19684    /*
19685     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19686     * flag is not set, the data directory is removed as well.
19687     * make sure this flag is set for partially installed apps. If not its meaningless to
19688     * delete a partially installed application.
19689     */
19690    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19691            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19692        String packageName = ps.name;
19693        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19694        // Retrieve object to delete permissions for shared user later on
19695        final PackageParser.Package deletedPkg;
19696        final PackageSetting deletedPs;
19697        // reader
19698        synchronized (mPackages) {
19699            deletedPkg = mPackages.get(packageName);
19700            deletedPs = mSettings.mPackages.get(packageName);
19701            if (outInfo != null) {
19702                outInfo.removedPackage = packageName;
19703                outInfo.installerPackageName = ps.installerPackageName;
19704                outInfo.isStaticSharedLib = deletedPkg != null
19705                        && deletedPkg.staticSharedLibName != null;
19706                outInfo.populateUsers(deletedPs == null ? null
19707                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19708            }
19709        }
19710
19711        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19712
19713        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19714            final PackageParser.Package resolvedPkg;
19715            if (deletedPkg != null) {
19716                resolvedPkg = deletedPkg;
19717            } else {
19718                // We don't have a parsed package when it lives on an ejected
19719                // adopted storage device, so fake something together
19720                resolvedPkg = new PackageParser.Package(ps.name);
19721                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19722            }
19723            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19724                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19725            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19726            if (outInfo != null) {
19727                outInfo.dataRemoved = true;
19728            }
19729            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19730        }
19731
19732        int removedAppId = -1;
19733
19734        // writer
19735        synchronized (mPackages) {
19736            boolean installedStateChanged = false;
19737            if (deletedPs != null) {
19738                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19739                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19740                    clearDefaultBrowserIfNeeded(packageName);
19741                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19742                    removedAppId = mSettings.removePackageLPw(packageName);
19743                    if (outInfo != null) {
19744                        outInfo.removedAppId = removedAppId;
19745                    }
19746                    updatePermissionsLPw(deletedPs.name, null, 0);
19747                    if (deletedPs.sharedUser != null) {
19748                        // Remove permissions associated with package. Since runtime
19749                        // permissions are per user we have to kill the removed package
19750                        // or packages running under the shared user of the removed
19751                        // package if revoking the permissions requested only by the removed
19752                        // package is successful and this causes a change in gids.
19753                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19754                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19755                                    userId);
19756                            if (userIdToKill == UserHandle.USER_ALL
19757                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19758                                // If gids changed for this user, kill all affected packages.
19759                                mHandler.post(new Runnable() {
19760                                    @Override
19761                                    public void run() {
19762                                        // This has to happen with no lock held.
19763                                        killApplication(deletedPs.name, deletedPs.appId,
19764                                                KILL_APP_REASON_GIDS_CHANGED);
19765                                    }
19766                                });
19767                                break;
19768                            }
19769                        }
19770                    }
19771                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19772                }
19773                // make sure to preserve per-user disabled state if this removal was just
19774                // a downgrade of a system app to the factory package
19775                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19776                    if (DEBUG_REMOVE) {
19777                        Slog.d(TAG, "Propagating install state across downgrade");
19778                    }
19779                    for (int userId : allUserHandles) {
19780                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19781                        if (DEBUG_REMOVE) {
19782                            Slog.d(TAG, "    user " + userId + " => " + installed);
19783                        }
19784                        if (installed != ps.getInstalled(userId)) {
19785                            installedStateChanged = true;
19786                        }
19787                        ps.setInstalled(installed, userId);
19788                    }
19789                }
19790            }
19791            // can downgrade to reader
19792            if (writeSettings) {
19793                // Save settings now
19794                mSettings.writeLPr();
19795            }
19796            if (installedStateChanged) {
19797                mSettings.writeKernelMappingLPr(ps);
19798            }
19799        }
19800        if (removedAppId != -1) {
19801            // A user ID was deleted here. Go through all users and remove it
19802            // from KeyStore.
19803            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19804        }
19805    }
19806
19807    static boolean locationIsPrivileged(File path) {
19808        try {
19809            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19810                    .getCanonicalPath();
19811            return path.getCanonicalPath().startsWith(privilegedAppDir);
19812        } catch (IOException e) {
19813            Slog.e(TAG, "Unable to access code path " + path);
19814        }
19815        return false;
19816    }
19817
19818    /*
19819     * Tries to delete system package.
19820     */
19821    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19822            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19823            boolean writeSettings) {
19824        if (deletedPs.parentPackageName != null) {
19825            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19826            return false;
19827        }
19828
19829        final boolean applyUserRestrictions
19830                = (allUserHandles != null) && (outInfo.origUsers != null);
19831        final PackageSetting disabledPs;
19832        // Confirm if the system package has been updated
19833        // An updated system app can be deleted. This will also have to restore
19834        // the system pkg from system partition
19835        // reader
19836        synchronized (mPackages) {
19837            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19838        }
19839
19840        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19841                + " disabledPs=" + disabledPs);
19842
19843        if (disabledPs == null) {
19844            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19845            return false;
19846        } else if (DEBUG_REMOVE) {
19847            Slog.d(TAG, "Deleting system pkg from data partition");
19848        }
19849
19850        if (DEBUG_REMOVE) {
19851            if (applyUserRestrictions) {
19852                Slog.d(TAG, "Remembering install states:");
19853                for (int userId : allUserHandles) {
19854                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19855                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19856                }
19857            }
19858        }
19859
19860        // Delete the updated package
19861        outInfo.isRemovedPackageSystemUpdate = true;
19862        if (outInfo.removedChildPackages != null) {
19863            final int childCount = (deletedPs.childPackageNames != null)
19864                    ? deletedPs.childPackageNames.size() : 0;
19865            for (int i = 0; i < childCount; i++) {
19866                String childPackageName = deletedPs.childPackageNames.get(i);
19867                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19868                        .contains(childPackageName)) {
19869                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19870                            childPackageName);
19871                    if (childInfo != null) {
19872                        childInfo.isRemovedPackageSystemUpdate = true;
19873                    }
19874                }
19875            }
19876        }
19877
19878        if (disabledPs.versionCode < deletedPs.versionCode) {
19879            // Delete data for downgrades
19880            flags &= ~PackageManager.DELETE_KEEP_DATA;
19881        } else {
19882            // Preserve data by setting flag
19883            flags |= PackageManager.DELETE_KEEP_DATA;
19884        }
19885
19886        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19887                outInfo, writeSettings, disabledPs.pkg);
19888        if (!ret) {
19889            return false;
19890        }
19891
19892        // writer
19893        synchronized (mPackages) {
19894            // NOTE: The system package always needs to be enabled; even if it's for
19895            // a compressed stub. If we don't, installing the system package fails
19896            // during scan [scanning checks the disabled packages]. We will reverse
19897            // this later, after we've "installed" the stub.
19898            // Reinstate the old system package
19899            enableSystemPackageLPw(disabledPs.pkg);
19900            // Remove any native libraries from the upgraded package.
19901            removeNativeBinariesLI(deletedPs);
19902        }
19903
19904        // Install the system package
19905        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19906        try {
19907            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19908                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19909        } catch (PackageManagerException e) {
19910            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19911                    + e.getMessage());
19912            return false;
19913        } finally {
19914            if (disabledPs.pkg.isStub) {
19915                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19916            }
19917        }
19918        return true;
19919    }
19920
19921    /**
19922     * Installs a package that's already on the system partition.
19923     */
19924    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19925            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19926            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19927                    throws PackageManagerException {
19928        int parseFlags = mDefParseFlags
19929                | PackageParser.PARSE_MUST_BE_APK
19930                | PackageParser.PARSE_IS_SYSTEM
19931                | PackageParser.PARSE_IS_SYSTEM_DIR;
19932        if (isPrivileged || locationIsPrivileged(codePath)) {
19933            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19934        }
19935
19936        final PackageParser.Package newPkg =
19937                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19938
19939        try {
19940            // update shared libraries for the newly re-installed system package
19941            updateSharedLibrariesLPr(newPkg, null);
19942        } catch (PackageManagerException e) {
19943            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19944        }
19945
19946        prepareAppDataAfterInstallLIF(newPkg);
19947
19948        // writer
19949        synchronized (mPackages) {
19950            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19951
19952            // Propagate the permissions state as we do not want to drop on the floor
19953            // runtime permissions. The update permissions method below will take
19954            // care of removing obsolete permissions and grant install permissions.
19955            if (origPermissionState != null) {
19956                ps.getPermissionsState().copyFrom(origPermissionState);
19957            }
19958            updatePermissionsLPw(newPkg.packageName, newPkg,
19959                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19960
19961            final boolean applyUserRestrictions
19962                    = (allUserHandles != null) && (origUserHandles != null);
19963            if (applyUserRestrictions) {
19964                boolean installedStateChanged = false;
19965                if (DEBUG_REMOVE) {
19966                    Slog.d(TAG, "Propagating install state across reinstall");
19967                }
19968                for (int userId : allUserHandles) {
19969                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19970                    if (DEBUG_REMOVE) {
19971                        Slog.d(TAG, "    user " + userId + " => " + installed);
19972                    }
19973                    if (installed != ps.getInstalled(userId)) {
19974                        installedStateChanged = true;
19975                    }
19976                    ps.setInstalled(installed, userId);
19977
19978                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19979                }
19980                // Regardless of writeSettings we need to ensure that this restriction
19981                // state propagation is persisted
19982                mSettings.writeAllUsersPackageRestrictionsLPr();
19983                if (installedStateChanged) {
19984                    mSettings.writeKernelMappingLPr(ps);
19985                }
19986            }
19987            // can downgrade to reader here
19988            if (writeSettings) {
19989                mSettings.writeLPr();
19990            }
19991        }
19992        return newPkg;
19993    }
19994
19995    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19996            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19997            PackageRemovedInfo outInfo, boolean writeSettings,
19998            PackageParser.Package replacingPackage) {
19999        synchronized (mPackages) {
20000            if (outInfo != null) {
20001                outInfo.uid = ps.appId;
20002            }
20003
20004            if (outInfo != null && outInfo.removedChildPackages != null) {
20005                final int childCount = (ps.childPackageNames != null)
20006                        ? ps.childPackageNames.size() : 0;
20007                for (int i = 0; i < childCount; i++) {
20008                    String childPackageName = ps.childPackageNames.get(i);
20009                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
20010                    if (childPs == null) {
20011                        return false;
20012                    }
20013                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
20014                            childPackageName);
20015                    if (childInfo != null) {
20016                        childInfo.uid = childPs.appId;
20017                    }
20018                }
20019            }
20020        }
20021
20022        // Delete package data from internal structures and also remove data if flag is set
20023        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
20024
20025        // Delete the child packages data
20026        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
20027        for (int i = 0; i < childCount; i++) {
20028            PackageSetting childPs;
20029            synchronized (mPackages) {
20030                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
20031            }
20032            if (childPs != null) {
20033                PackageRemovedInfo childOutInfo = (outInfo != null
20034                        && outInfo.removedChildPackages != null)
20035                        ? outInfo.removedChildPackages.get(childPs.name) : null;
20036                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
20037                        && (replacingPackage != null
20038                        && !replacingPackage.hasChildPackage(childPs.name))
20039                        ? flags & ~DELETE_KEEP_DATA : flags;
20040                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
20041                        deleteFlags, writeSettings);
20042            }
20043        }
20044
20045        // Delete application code and resources only for parent packages
20046        if (ps.parentPackageName == null) {
20047            if (deleteCodeAndResources && (outInfo != null)) {
20048                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
20049                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
20050                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
20051            }
20052        }
20053
20054        return true;
20055    }
20056
20057    @Override
20058    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20059            int userId) {
20060        mContext.enforceCallingOrSelfPermission(
20061                android.Manifest.permission.DELETE_PACKAGES, null);
20062        synchronized (mPackages) {
20063            // Cannot block uninstall of static shared libs as they are
20064            // considered a part of the using app (emulating static linking).
20065            // Also static libs are installed always on internal storage.
20066            PackageParser.Package pkg = mPackages.get(packageName);
20067            if (pkg != null && pkg.staticSharedLibName != null) {
20068                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20069                        + " providing static shared library: " + pkg.staticSharedLibName);
20070                return false;
20071            }
20072            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20073            mSettings.writePackageRestrictionsLPr(userId);
20074        }
20075        return true;
20076    }
20077
20078    @Override
20079    public boolean getBlockUninstallForUser(String packageName, int userId) {
20080        synchronized (mPackages) {
20081            final PackageSetting ps = mSettings.mPackages.get(packageName);
20082            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20083                return false;
20084            }
20085            return mSettings.getBlockUninstallLPr(userId, packageName);
20086        }
20087    }
20088
20089    @Override
20090    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20091        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20092        synchronized (mPackages) {
20093            PackageSetting ps = mSettings.mPackages.get(packageName);
20094            if (ps == null) {
20095                Log.w(TAG, "Package doesn't exist: " + packageName);
20096                return false;
20097            }
20098            if (systemUserApp) {
20099                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20100            } else {
20101                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20102            }
20103            mSettings.writeLPr();
20104        }
20105        return true;
20106    }
20107
20108    /*
20109     * This method handles package deletion in general
20110     */
20111    private boolean deletePackageLIF(String packageName, UserHandle user,
20112            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20113            PackageRemovedInfo outInfo, boolean writeSettings,
20114            PackageParser.Package replacingPackage) {
20115        if (packageName == null) {
20116            Slog.w(TAG, "Attempt to delete null packageName.");
20117            return false;
20118        }
20119
20120        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20121
20122        PackageSetting ps;
20123        synchronized (mPackages) {
20124            ps = mSettings.mPackages.get(packageName);
20125            if (ps == null) {
20126                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20127                return false;
20128            }
20129
20130            if (ps.parentPackageName != null && (!isSystemApp(ps)
20131                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20132                if (DEBUG_REMOVE) {
20133                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20134                            + ((user == null) ? UserHandle.USER_ALL : user));
20135                }
20136                final int removedUserId = (user != null) ? user.getIdentifier()
20137                        : UserHandle.USER_ALL;
20138                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20139                    return false;
20140                }
20141                markPackageUninstalledForUserLPw(ps, user);
20142                scheduleWritePackageRestrictionsLocked(user);
20143                return true;
20144            }
20145        }
20146
20147        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20148                && user.getIdentifier() != UserHandle.USER_ALL)) {
20149            // The caller is asking that the package only be deleted for a single
20150            // user.  To do this, we just mark its uninstalled state and delete
20151            // its data. If this is a system app, we only allow this to happen if
20152            // they have set the special DELETE_SYSTEM_APP which requests different
20153            // semantics than normal for uninstalling system apps.
20154            markPackageUninstalledForUserLPw(ps, user);
20155
20156            if (!isSystemApp(ps)) {
20157                // Do not uninstall the APK if an app should be cached
20158                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20159                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20160                    // Other user still have this package installed, so all
20161                    // we need to do is clear this user's data and save that
20162                    // it is uninstalled.
20163                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20164                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20165                        return false;
20166                    }
20167                    scheduleWritePackageRestrictionsLocked(user);
20168                    return true;
20169                } else {
20170                    // We need to set it back to 'installed' so the uninstall
20171                    // broadcasts will be sent correctly.
20172                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20173                    ps.setInstalled(true, user.getIdentifier());
20174                    mSettings.writeKernelMappingLPr(ps);
20175                }
20176            } else {
20177                // This is a system app, so we assume that the
20178                // other users still have this package installed, so all
20179                // we need to do is clear this user's data and save that
20180                // it is uninstalled.
20181                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20182                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20183                    return false;
20184                }
20185                scheduleWritePackageRestrictionsLocked(user);
20186                return true;
20187            }
20188        }
20189
20190        // If we are deleting a composite package for all users, keep track
20191        // of result for each child.
20192        if (ps.childPackageNames != null && outInfo != null) {
20193            synchronized (mPackages) {
20194                final int childCount = ps.childPackageNames.size();
20195                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20196                for (int i = 0; i < childCount; i++) {
20197                    String childPackageName = ps.childPackageNames.get(i);
20198                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20199                    childInfo.removedPackage = childPackageName;
20200                    childInfo.installerPackageName = ps.installerPackageName;
20201                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20202                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20203                    if (childPs != null) {
20204                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20205                    }
20206                }
20207            }
20208        }
20209
20210        boolean ret = false;
20211        if (isSystemApp(ps)) {
20212            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20213            // When an updated system application is deleted we delete the existing resources
20214            // as well and fall back to existing code in system partition
20215            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20216        } else {
20217            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20218            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20219                    outInfo, writeSettings, replacingPackage);
20220        }
20221
20222        // Take a note whether we deleted the package for all users
20223        if (outInfo != null) {
20224            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20225            if (outInfo.removedChildPackages != null) {
20226                synchronized (mPackages) {
20227                    final int childCount = outInfo.removedChildPackages.size();
20228                    for (int i = 0; i < childCount; i++) {
20229                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20230                        if (childInfo != null) {
20231                            childInfo.removedForAllUsers = mPackages.get(
20232                                    childInfo.removedPackage) == null;
20233                        }
20234                    }
20235                }
20236            }
20237            // If we uninstalled an update to a system app there may be some
20238            // child packages that appeared as they are declared in the system
20239            // app but were not declared in the update.
20240            if (isSystemApp(ps)) {
20241                synchronized (mPackages) {
20242                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20243                    final int childCount = (updatedPs.childPackageNames != null)
20244                            ? updatedPs.childPackageNames.size() : 0;
20245                    for (int i = 0; i < childCount; i++) {
20246                        String childPackageName = updatedPs.childPackageNames.get(i);
20247                        if (outInfo.removedChildPackages == null
20248                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20249                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20250                            if (childPs == null) {
20251                                continue;
20252                            }
20253                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20254                            installRes.name = childPackageName;
20255                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20256                            installRes.pkg = mPackages.get(childPackageName);
20257                            installRes.uid = childPs.pkg.applicationInfo.uid;
20258                            if (outInfo.appearedChildPackages == null) {
20259                                outInfo.appearedChildPackages = new ArrayMap<>();
20260                            }
20261                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20262                        }
20263                    }
20264                }
20265            }
20266        }
20267
20268        return ret;
20269    }
20270
20271    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20272        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20273                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20274        for (int nextUserId : userIds) {
20275            if (DEBUG_REMOVE) {
20276                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20277            }
20278            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20279                    false /*installed*/,
20280                    true /*stopped*/,
20281                    true /*notLaunched*/,
20282                    false /*hidden*/,
20283                    false /*suspended*/,
20284                    false /*instantApp*/,
20285                    false /*virtualPreload*/,
20286                    null /*lastDisableAppCaller*/,
20287                    null /*enabledComponents*/,
20288                    null /*disabledComponents*/,
20289                    ps.readUserState(nextUserId).domainVerificationStatus,
20290                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20291        }
20292        mSettings.writeKernelMappingLPr(ps);
20293    }
20294
20295    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20296            PackageRemovedInfo outInfo) {
20297        final PackageParser.Package pkg;
20298        synchronized (mPackages) {
20299            pkg = mPackages.get(ps.name);
20300        }
20301
20302        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20303                : new int[] {userId};
20304        for (int nextUserId : userIds) {
20305            if (DEBUG_REMOVE) {
20306                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20307                        + nextUserId);
20308            }
20309
20310            destroyAppDataLIF(pkg, userId,
20311                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20312            destroyAppProfilesLIF(pkg, userId);
20313            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20314            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20315            schedulePackageCleaning(ps.name, nextUserId, false);
20316            synchronized (mPackages) {
20317                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20318                    scheduleWritePackageRestrictionsLocked(nextUserId);
20319                }
20320                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20321            }
20322        }
20323
20324        if (outInfo != null) {
20325            outInfo.removedPackage = ps.name;
20326            outInfo.installerPackageName = ps.installerPackageName;
20327            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20328            outInfo.removedAppId = ps.appId;
20329            outInfo.removedUsers = userIds;
20330            outInfo.broadcastUsers = userIds;
20331        }
20332
20333        return true;
20334    }
20335
20336    private final class ClearStorageConnection implements ServiceConnection {
20337        IMediaContainerService mContainerService;
20338
20339        @Override
20340        public void onServiceConnected(ComponentName name, IBinder service) {
20341            synchronized (this) {
20342                mContainerService = IMediaContainerService.Stub
20343                        .asInterface(Binder.allowBlocking(service));
20344                notifyAll();
20345            }
20346        }
20347
20348        @Override
20349        public void onServiceDisconnected(ComponentName name) {
20350        }
20351    }
20352
20353    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20354        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20355
20356        final boolean mounted;
20357        if (Environment.isExternalStorageEmulated()) {
20358            mounted = true;
20359        } else {
20360            final String status = Environment.getExternalStorageState();
20361
20362            mounted = status.equals(Environment.MEDIA_MOUNTED)
20363                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20364        }
20365
20366        if (!mounted) {
20367            return;
20368        }
20369
20370        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20371        int[] users;
20372        if (userId == UserHandle.USER_ALL) {
20373            users = sUserManager.getUserIds();
20374        } else {
20375            users = new int[] { userId };
20376        }
20377        final ClearStorageConnection conn = new ClearStorageConnection();
20378        if (mContext.bindServiceAsUser(
20379                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20380            try {
20381                for (int curUser : users) {
20382                    long timeout = SystemClock.uptimeMillis() + 5000;
20383                    synchronized (conn) {
20384                        long now;
20385                        while (conn.mContainerService == null &&
20386                                (now = SystemClock.uptimeMillis()) < timeout) {
20387                            try {
20388                                conn.wait(timeout - now);
20389                            } catch (InterruptedException e) {
20390                            }
20391                        }
20392                    }
20393                    if (conn.mContainerService == null) {
20394                        return;
20395                    }
20396
20397                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20398                    clearDirectory(conn.mContainerService,
20399                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20400                    if (allData) {
20401                        clearDirectory(conn.mContainerService,
20402                                userEnv.buildExternalStorageAppDataDirs(packageName));
20403                        clearDirectory(conn.mContainerService,
20404                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20405                    }
20406                }
20407            } finally {
20408                mContext.unbindService(conn);
20409            }
20410        }
20411    }
20412
20413    @Override
20414    public void clearApplicationProfileData(String packageName) {
20415        enforceSystemOrRoot("Only the system can clear all profile data");
20416
20417        final PackageParser.Package pkg;
20418        synchronized (mPackages) {
20419            pkg = mPackages.get(packageName);
20420        }
20421
20422        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20423            synchronized (mInstallLock) {
20424                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20425            }
20426        }
20427    }
20428
20429    @Override
20430    public void clearApplicationUserData(final String packageName,
20431            final IPackageDataObserver observer, final int userId) {
20432        mContext.enforceCallingOrSelfPermission(
20433                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20434
20435        final int callingUid = Binder.getCallingUid();
20436        enforceCrossUserPermission(callingUid, userId,
20437                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20438
20439        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20440        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20441        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20442            throw new SecurityException("Cannot clear data for a protected package: "
20443                    + packageName);
20444        }
20445        // Queue up an async operation since the package deletion may take a little while.
20446        mHandler.post(new Runnable() {
20447            public void run() {
20448                mHandler.removeCallbacks(this);
20449                final boolean succeeded;
20450                if (!filterApp) {
20451                    try (PackageFreezer freezer = freezePackage(packageName,
20452                            "clearApplicationUserData")) {
20453                        synchronized (mInstallLock) {
20454                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20455                        }
20456                        clearExternalStorageDataSync(packageName, userId, true);
20457                        synchronized (mPackages) {
20458                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20459                                    packageName, userId);
20460                        }
20461                    }
20462                    if (succeeded) {
20463                        // invoke DeviceStorageMonitor's update method to clear any notifications
20464                        DeviceStorageMonitorInternal dsm = LocalServices
20465                                .getService(DeviceStorageMonitorInternal.class);
20466                        if (dsm != null) {
20467                            dsm.checkMemory();
20468                        }
20469                    }
20470                } else {
20471                    succeeded = false;
20472                }
20473                if (observer != null) {
20474                    try {
20475                        observer.onRemoveCompleted(packageName, succeeded);
20476                    } catch (RemoteException e) {
20477                        Log.i(TAG, "Observer no longer exists.");
20478                    }
20479                } //end if observer
20480            } //end run
20481        });
20482    }
20483
20484    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20485        if (packageName == null) {
20486            Slog.w(TAG, "Attempt to delete null packageName.");
20487            return false;
20488        }
20489
20490        // Try finding details about the requested package
20491        PackageParser.Package pkg;
20492        synchronized (mPackages) {
20493            pkg = mPackages.get(packageName);
20494            if (pkg == null) {
20495                final PackageSetting ps = mSettings.mPackages.get(packageName);
20496                if (ps != null) {
20497                    pkg = ps.pkg;
20498                }
20499            }
20500
20501            if (pkg == null) {
20502                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20503                return false;
20504            }
20505
20506            PackageSetting ps = (PackageSetting) pkg.mExtras;
20507            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20508        }
20509
20510        clearAppDataLIF(pkg, userId,
20511                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20512
20513        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20514        removeKeystoreDataIfNeeded(userId, appId);
20515
20516        UserManagerInternal umInternal = getUserManagerInternal();
20517        final int flags;
20518        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20519            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20520        } else if (umInternal.isUserRunning(userId)) {
20521            flags = StorageManager.FLAG_STORAGE_DE;
20522        } else {
20523            flags = 0;
20524        }
20525        prepareAppDataContentsLIF(pkg, userId, flags);
20526
20527        return true;
20528    }
20529
20530    /**
20531     * Reverts user permission state changes (permissions and flags) in
20532     * all packages for a given user.
20533     *
20534     * @param userId The device user for which to do a reset.
20535     */
20536    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20537        final int packageCount = mPackages.size();
20538        for (int i = 0; i < packageCount; i++) {
20539            PackageParser.Package pkg = mPackages.valueAt(i);
20540            PackageSetting ps = (PackageSetting) pkg.mExtras;
20541            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20542        }
20543    }
20544
20545    private void resetNetworkPolicies(int userId) {
20546        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20547    }
20548
20549    /**
20550     * Reverts user permission state changes (permissions and flags).
20551     *
20552     * @param ps The package for which to reset.
20553     * @param userId The device user for which to do a reset.
20554     */
20555    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20556            final PackageSetting ps, final int userId) {
20557        if (ps.pkg == null) {
20558            return;
20559        }
20560
20561        // These are flags that can change base on user actions.
20562        final int userSettableMask = FLAG_PERMISSION_USER_SET
20563                | FLAG_PERMISSION_USER_FIXED
20564                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20565                | FLAG_PERMISSION_REVIEW_REQUIRED;
20566
20567        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20568                | FLAG_PERMISSION_POLICY_FIXED;
20569
20570        boolean writeInstallPermissions = false;
20571        boolean writeRuntimePermissions = false;
20572
20573        final int permissionCount = ps.pkg.requestedPermissions.size();
20574        for (int i = 0; i < permissionCount; i++) {
20575            String permission = ps.pkg.requestedPermissions.get(i);
20576
20577            BasePermission bp = mSettings.mPermissions.get(permission);
20578            if (bp == null) {
20579                continue;
20580            }
20581
20582            // If shared user we just reset the state to which only this app contributed.
20583            if (ps.sharedUser != null) {
20584                boolean used = false;
20585                final int packageCount = ps.sharedUser.packages.size();
20586                for (int j = 0; j < packageCount; j++) {
20587                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20588                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20589                            && pkg.pkg.requestedPermissions.contains(permission)) {
20590                        used = true;
20591                        break;
20592                    }
20593                }
20594                if (used) {
20595                    continue;
20596                }
20597            }
20598
20599            PermissionsState permissionsState = ps.getPermissionsState();
20600
20601            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20602
20603            // Always clear the user settable flags.
20604            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20605                    bp.name) != null;
20606            // If permission review is enabled and this is a legacy app, mark the
20607            // permission as requiring a review as this is the initial state.
20608            int flags = 0;
20609            if (mPermissionReviewRequired
20610                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20611                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20612            }
20613            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20614                if (hasInstallState) {
20615                    writeInstallPermissions = true;
20616                } else {
20617                    writeRuntimePermissions = true;
20618                }
20619            }
20620
20621            // Below is only runtime permission handling.
20622            if (!bp.isRuntime()) {
20623                continue;
20624            }
20625
20626            // Never clobber system or policy.
20627            if ((oldFlags & policyOrSystemFlags) != 0) {
20628                continue;
20629            }
20630
20631            // If this permission was granted by default, make sure it is.
20632            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20633                if (permissionsState.grantRuntimePermission(bp, userId)
20634                        != PERMISSION_OPERATION_FAILURE) {
20635                    writeRuntimePermissions = true;
20636                }
20637            // If permission review is enabled the permissions for a legacy apps
20638            // are represented as constantly granted runtime ones, so don't revoke.
20639            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20640                // Otherwise, reset the permission.
20641                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20642                switch (revokeResult) {
20643                    case PERMISSION_OPERATION_SUCCESS:
20644                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20645                        writeRuntimePermissions = true;
20646                        final int appId = ps.appId;
20647                        mHandler.post(new Runnable() {
20648                            @Override
20649                            public void run() {
20650                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20651                            }
20652                        });
20653                    } break;
20654                }
20655            }
20656        }
20657
20658        // Synchronously write as we are taking permissions away.
20659        if (writeRuntimePermissions) {
20660            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20661        }
20662
20663        // Synchronously write as we are taking permissions away.
20664        if (writeInstallPermissions) {
20665            mSettings.writeLPr();
20666        }
20667    }
20668
20669    /**
20670     * Remove entries from the keystore daemon. Will only remove it if the
20671     * {@code appId} is valid.
20672     */
20673    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20674        if (appId < 0) {
20675            return;
20676        }
20677
20678        final KeyStore keyStore = KeyStore.getInstance();
20679        if (keyStore != null) {
20680            if (userId == UserHandle.USER_ALL) {
20681                for (final int individual : sUserManager.getUserIds()) {
20682                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20683                }
20684            } else {
20685                keyStore.clearUid(UserHandle.getUid(userId, appId));
20686            }
20687        } else {
20688            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20689        }
20690    }
20691
20692    @Override
20693    public void deleteApplicationCacheFiles(final String packageName,
20694            final IPackageDataObserver observer) {
20695        final int userId = UserHandle.getCallingUserId();
20696        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20697    }
20698
20699    @Override
20700    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20701            final IPackageDataObserver observer) {
20702        final int callingUid = Binder.getCallingUid();
20703        mContext.enforceCallingOrSelfPermission(
20704                android.Manifest.permission.DELETE_CACHE_FILES, null);
20705        enforceCrossUserPermission(callingUid, userId,
20706                /* requireFullPermission= */ true, /* checkShell= */ false,
20707                "delete application cache files");
20708        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20709                android.Manifest.permission.ACCESS_INSTANT_APPS);
20710
20711        final PackageParser.Package pkg;
20712        synchronized (mPackages) {
20713            pkg = mPackages.get(packageName);
20714        }
20715
20716        // Queue up an async operation since the package deletion may take a little while.
20717        mHandler.post(new Runnable() {
20718            public void run() {
20719                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20720                boolean doClearData = true;
20721                if (ps != null) {
20722                    final boolean targetIsInstantApp =
20723                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20724                    doClearData = !targetIsInstantApp
20725                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20726                }
20727                if (doClearData) {
20728                    synchronized (mInstallLock) {
20729                        final int flags = StorageManager.FLAG_STORAGE_DE
20730                                | StorageManager.FLAG_STORAGE_CE;
20731                        // We're only clearing cache files, so we don't care if the
20732                        // app is unfrozen and still able to run
20733                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20734                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20735                    }
20736                    clearExternalStorageDataSync(packageName, userId, false);
20737                }
20738                if (observer != null) {
20739                    try {
20740                        observer.onRemoveCompleted(packageName, true);
20741                    } catch (RemoteException e) {
20742                        Log.i(TAG, "Observer no longer exists.");
20743                    }
20744                }
20745            }
20746        });
20747    }
20748
20749    @Override
20750    public void getPackageSizeInfo(final String packageName, int userHandle,
20751            final IPackageStatsObserver observer) {
20752        throw new UnsupportedOperationException(
20753                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20754    }
20755
20756    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20757        final PackageSetting ps;
20758        synchronized (mPackages) {
20759            ps = mSettings.mPackages.get(packageName);
20760            if (ps == null) {
20761                Slog.w(TAG, "Failed to find settings for " + packageName);
20762                return false;
20763            }
20764        }
20765
20766        final String[] packageNames = { packageName };
20767        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20768        final String[] codePaths = { ps.codePathString };
20769
20770        try {
20771            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20772                    ps.appId, ceDataInodes, codePaths, stats);
20773
20774            // For now, ignore code size of packages on system partition
20775            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20776                stats.codeSize = 0;
20777            }
20778
20779            // External clients expect these to be tracked separately
20780            stats.dataSize -= stats.cacheSize;
20781
20782        } catch (InstallerException e) {
20783            Slog.w(TAG, String.valueOf(e));
20784            return false;
20785        }
20786
20787        return true;
20788    }
20789
20790    private int getUidTargetSdkVersionLockedLPr(int uid) {
20791        Object obj = mSettings.getUserIdLPr(uid);
20792        if (obj instanceof SharedUserSetting) {
20793            final SharedUserSetting sus = (SharedUserSetting) obj;
20794            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20795            final Iterator<PackageSetting> it = sus.packages.iterator();
20796            while (it.hasNext()) {
20797                final PackageSetting ps = it.next();
20798                if (ps.pkg != null) {
20799                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20800                    if (v < vers) vers = v;
20801                }
20802            }
20803            return vers;
20804        } else if (obj instanceof PackageSetting) {
20805            final PackageSetting ps = (PackageSetting) obj;
20806            if (ps.pkg != null) {
20807                return ps.pkg.applicationInfo.targetSdkVersion;
20808            }
20809        }
20810        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20811    }
20812
20813    @Override
20814    public void addPreferredActivity(IntentFilter filter, int match,
20815            ComponentName[] set, ComponentName activity, int userId) {
20816        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20817                "Adding preferred");
20818    }
20819
20820    private void addPreferredActivityInternal(IntentFilter filter, int match,
20821            ComponentName[] set, ComponentName activity, boolean always, int userId,
20822            String opname) {
20823        // writer
20824        int callingUid = Binder.getCallingUid();
20825        enforceCrossUserPermission(callingUid, userId,
20826                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20827        if (filter.countActions() == 0) {
20828            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20829            return;
20830        }
20831        synchronized (mPackages) {
20832            if (mContext.checkCallingOrSelfPermission(
20833                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20834                    != PackageManager.PERMISSION_GRANTED) {
20835                if (getUidTargetSdkVersionLockedLPr(callingUid)
20836                        < Build.VERSION_CODES.FROYO) {
20837                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20838                            + callingUid);
20839                    return;
20840                }
20841                mContext.enforceCallingOrSelfPermission(
20842                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20843            }
20844
20845            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20846            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20847                    + userId + ":");
20848            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20849            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20850            scheduleWritePackageRestrictionsLocked(userId);
20851            postPreferredActivityChangedBroadcast(userId);
20852        }
20853    }
20854
20855    private void postPreferredActivityChangedBroadcast(int userId) {
20856        mHandler.post(() -> {
20857            final IActivityManager am = ActivityManager.getService();
20858            if (am == null) {
20859                return;
20860            }
20861
20862            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20863            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20864            try {
20865                am.broadcastIntent(null, intent, null, null,
20866                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20867                        null, false, false, userId);
20868            } catch (RemoteException e) {
20869            }
20870        });
20871    }
20872
20873    @Override
20874    public void replacePreferredActivity(IntentFilter filter, int match,
20875            ComponentName[] set, ComponentName activity, int userId) {
20876        if (filter.countActions() != 1) {
20877            throw new IllegalArgumentException(
20878                    "replacePreferredActivity expects filter to have only 1 action.");
20879        }
20880        if (filter.countDataAuthorities() != 0
20881                || filter.countDataPaths() != 0
20882                || filter.countDataSchemes() > 1
20883                || filter.countDataTypes() != 0) {
20884            throw new IllegalArgumentException(
20885                    "replacePreferredActivity expects filter to have no data authorities, " +
20886                    "paths, or types; and at most one scheme.");
20887        }
20888
20889        final int callingUid = Binder.getCallingUid();
20890        enforceCrossUserPermission(callingUid, userId,
20891                true /* requireFullPermission */, false /* checkShell */,
20892                "replace preferred activity");
20893        synchronized (mPackages) {
20894            if (mContext.checkCallingOrSelfPermission(
20895                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20896                    != PackageManager.PERMISSION_GRANTED) {
20897                if (getUidTargetSdkVersionLockedLPr(callingUid)
20898                        < Build.VERSION_CODES.FROYO) {
20899                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20900                            + Binder.getCallingUid());
20901                    return;
20902                }
20903                mContext.enforceCallingOrSelfPermission(
20904                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20905            }
20906
20907            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20908            if (pir != null) {
20909                // Get all of the existing entries that exactly match this filter.
20910                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20911                if (existing != null && existing.size() == 1) {
20912                    PreferredActivity cur = existing.get(0);
20913                    if (DEBUG_PREFERRED) {
20914                        Slog.i(TAG, "Checking replace of preferred:");
20915                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20916                        if (!cur.mPref.mAlways) {
20917                            Slog.i(TAG, "  -- CUR; not mAlways!");
20918                        } else {
20919                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20920                            Slog.i(TAG, "  -- CUR: mSet="
20921                                    + Arrays.toString(cur.mPref.mSetComponents));
20922                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20923                            Slog.i(TAG, "  -- NEW: mMatch="
20924                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20925                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20926                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20927                        }
20928                    }
20929                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20930                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20931                            && cur.mPref.sameSet(set)) {
20932                        // Setting the preferred activity to what it happens to be already
20933                        if (DEBUG_PREFERRED) {
20934                            Slog.i(TAG, "Replacing with same preferred activity "
20935                                    + cur.mPref.mShortComponent + " for user "
20936                                    + userId + ":");
20937                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20938                        }
20939                        return;
20940                    }
20941                }
20942
20943                if (existing != null) {
20944                    if (DEBUG_PREFERRED) {
20945                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20946                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20947                    }
20948                    for (int i = 0; i < existing.size(); i++) {
20949                        PreferredActivity pa = existing.get(i);
20950                        if (DEBUG_PREFERRED) {
20951                            Slog.i(TAG, "Removing existing preferred activity "
20952                                    + pa.mPref.mComponent + ":");
20953                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20954                        }
20955                        pir.removeFilter(pa);
20956                    }
20957                }
20958            }
20959            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20960                    "Replacing preferred");
20961        }
20962    }
20963
20964    @Override
20965    public void clearPackagePreferredActivities(String packageName) {
20966        final int callingUid = Binder.getCallingUid();
20967        if (getInstantAppPackageName(callingUid) != null) {
20968            return;
20969        }
20970        // writer
20971        synchronized (mPackages) {
20972            PackageParser.Package pkg = mPackages.get(packageName);
20973            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20974                if (mContext.checkCallingOrSelfPermission(
20975                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20976                        != PackageManager.PERMISSION_GRANTED) {
20977                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20978                            < Build.VERSION_CODES.FROYO) {
20979                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20980                                + callingUid);
20981                        return;
20982                    }
20983                    mContext.enforceCallingOrSelfPermission(
20984                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20985                }
20986            }
20987            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20988            if (ps != null
20989                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20990                return;
20991            }
20992            int user = UserHandle.getCallingUserId();
20993            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20994                scheduleWritePackageRestrictionsLocked(user);
20995            }
20996        }
20997    }
20998
20999    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21000    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
21001        ArrayList<PreferredActivity> removed = null;
21002        boolean changed = false;
21003        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21004            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
21005            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21006            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
21007                continue;
21008            }
21009            Iterator<PreferredActivity> it = pir.filterIterator();
21010            while (it.hasNext()) {
21011                PreferredActivity pa = it.next();
21012                // Mark entry for removal only if it matches the package name
21013                // and the entry is of type "always".
21014                if (packageName == null ||
21015                        (pa.mPref.mComponent.getPackageName().equals(packageName)
21016                                && pa.mPref.mAlways)) {
21017                    if (removed == null) {
21018                        removed = new ArrayList<PreferredActivity>();
21019                    }
21020                    removed.add(pa);
21021                }
21022            }
21023            if (removed != null) {
21024                for (int j=0; j<removed.size(); j++) {
21025                    PreferredActivity pa = removed.get(j);
21026                    pir.removeFilter(pa);
21027                }
21028                changed = true;
21029            }
21030        }
21031        if (changed) {
21032            postPreferredActivityChangedBroadcast(userId);
21033        }
21034        return changed;
21035    }
21036
21037    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21038    private void clearIntentFilterVerificationsLPw(int userId) {
21039        final int packageCount = mPackages.size();
21040        for (int i = 0; i < packageCount; i++) {
21041            PackageParser.Package pkg = mPackages.valueAt(i);
21042            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
21043        }
21044    }
21045
21046    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21047    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
21048        if (userId == UserHandle.USER_ALL) {
21049            if (mSettings.removeIntentFilterVerificationLPw(packageName,
21050                    sUserManager.getUserIds())) {
21051                for (int oneUserId : sUserManager.getUserIds()) {
21052                    scheduleWritePackageRestrictionsLocked(oneUserId);
21053                }
21054            }
21055        } else {
21056            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21057                scheduleWritePackageRestrictionsLocked(userId);
21058            }
21059        }
21060    }
21061
21062    /** Clears state for all users, and touches intent filter verification policy */
21063    void clearDefaultBrowserIfNeeded(String packageName) {
21064        for (int oneUserId : sUserManager.getUserIds()) {
21065            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21066        }
21067    }
21068
21069    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21070        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21071        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21072            if (packageName.equals(defaultBrowserPackageName)) {
21073                setDefaultBrowserPackageName(null, userId);
21074            }
21075        }
21076    }
21077
21078    @Override
21079    public void resetApplicationPreferences(int userId) {
21080        mContext.enforceCallingOrSelfPermission(
21081                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21082        final long identity = Binder.clearCallingIdentity();
21083        // writer
21084        try {
21085            synchronized (mPackages) {
21086                clearPackagePreferredActivitiesLPw(null, userId);
21087                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21088                // TODO: We have to reset the default SMS and Phone. This requires
21089                // significant refactoring to keep all default apps in the package
21090                // manager (cleaner but more work) or have the services provide
21091                // callbacks to the package manager to request a default app reset.
21092                applyFactoryDefaultBrowserLPw(userId);
21093                clearIntentFilterVerificationsLPw(userId);
21094                primeDomainVerificationsLPw(userId);
21095                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21096                scheduleWritePackageRestrictionsLocked(userId);
21097            }
21098            resetNetworkPolicies(userId);
21099        } finally {
21100            Binder.restoreCallingIdentity(identity);
21101        }
21102    }
21103
21104    @Override
21105    public int getPreferredActivities(List<IntentFilter> outFilters,
21106            List<ComponentName> outActivities, String packageName) {
21107        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21108            return 0;
21109        }
21110        int num = 0;
21111        final int userId = UserHandle.getCallingUserId();
21112        // reader
21113        synchronized (mPackages) {
21114            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21115            if (pir != null) {
21116                final Iterator<PreferredActivity> it = pir.filterIterator();
21117                while (it.hasNext()) {
21118                    final PreferredActivity pa = it.next();
21119                    if (packageName == null
21120                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21121                                    && pa.mPref.mAlways)) {
21122                        if (outFilters != null) {
21123                            outFilters.add(new IntentFilter(pa));
21124                        }
21125                        if (outActivities != null) {
21126                            outActivities.add(pa.mPref.mComponent);
21127                        }
21128                    }
21129                }
21130            }
21131        }
21132
21133        return num;
21134    }
21135
21136    @Override
21137    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21138            int userId) {
21139        int callingUid = Binder.getCallingUid();
21140        if (callingUid != Process.SYSTEM_UID) {
21141            throw new SecurityException(
21142                    "addPersistentPreferredActivity can only be run by the system");
21143        }
21144        if (filter.countActions() == 0) {
21145            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21146            return;
21147        }
21148        synchronized (mPackages) {
21149            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21150                    ":");
21151            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21152            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21153                    new PersistentPreferredActivity(filter, activity));
21154            scheduleWritePackageRestrictionsLocked(userId);
21155            postPreferredActivityChangedBroadcast(userId);
21156        }
21157    }
21158
21159    @Override
21160    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21161        int callingUid = Binder.getCallingUid();
21162        if (callingUid != Process.SYSTEM_UID) {
21163            throw new SecurityException(
21164                    "clearPackagePersistentPreferredActivities can only be run by the system");
21165        }
21166        ArrayList<PersistentPreferredActivity> removed = null;
21167        boolean changed = false;
21168        synchronized (mPackages) {
21169            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21170                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21171                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21172                        .valueAt(i);
21173                if (userId != thisUserId) {
21174                    continue;
21175                }
21176                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21177                while (it.hasNext()) {
21178                    PersistentPreferredActivity ppa = it.next();
21179                    // Mark entry for removal only if it matches the package name.
21180                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21181                        if (removed == null) {
21182                            removed = new ArrayList<PersistentPreferredActivity>();
21183                        }
21184                        removed.add(ppa);
21185                    }
21186                }
21187                if (removed != null) {
21188                    for (int j=0; j<removed.size(); j++) {
21189                        PersistentPreferredActivity ppa = removed.get(j);
21190                        ppir.removeFilter(ppa);
21191                    }
21192                    changed = true;
21193                }
21194            }
21195
21196            if (changed) {
21197                scheduleWritePackageRestrictionsLocked(userId);
21198                postPreferredActivityChangedBroadcast(userId);
21199            }
21200        }
21201    }
21202
21203    /**
21204     * Common machinery for picking apart a restored XML blob and passing
21205     * it to a caller-supplied functor to be applied to the running system.
21206     */
21207    private void restoreFromXml(XmlPullParser parser, int userId,
21208            String expectedStartTag, BlobXmlRestorer functor)
21209            throws IOException, XmlPullParserException {
21210        int type;
21211        while ((type = parser.next()) != XmlPullParser.START_TAG
21212                && type != XmlPullParser.END_DOCUMENT) {
21213        }
21214        if (type != XmlPullParser.START_TAG) {
21215            // oops didn't find a start tag?!
21216            if (DEBUG_BACKUP) {
21217                Slog.e(TAG, "Didn't find start tag during restore");
21218            }
21219            return;
21220        }
21221Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21222        // this is supposed to be TAG_PREFERRED_BACKUP
21223        if (!expectedStartTag.equals(parser.getName())) {
21224            if (DEBUG_BACKUP) {
21225                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21226            }
21227            return;
21228        }
21229
21230        // skip interfering stuff, then we're aligned with the backing implementation
21231        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21232Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21233        functor.apply(parser, userId);
21234    }
21235
21236    private interface BlobXmlRestorer {
21237        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21238    }
21239
21240    /**
21241     * Non-Binder method, support for the backup/restore mechanism: write the
21242     * full set of preferred activities in its canonical XML format.  Returns the
21243     * XML output as a byte array, or null if there is none.
21244     */
21245    @Override
21246    public byte[] getPreferredActivityBackup(int userId) {
21247        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21248            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21249        }
21250
21251        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21252        try {
21253            final XmlSerializer serializer = new FastXmlSerializer();
21254            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21255            serializer.startDocument(null, true);
21256            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21257
21258            synchronized (mPackages) {
21259                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21260            }
21261
21262            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21263            serializer.endDocument();
21264            serializer.flush();
21265        } catch (Exception e) {
21266            if (DEBUG_BACKUP) {
21267                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21268            }
21269            return null;
21270        }
21271
21272        return dataStream.toByteArray();
21273    }
21274
21275    @Override
21276    public void restorePreferredActivities(byte[] backup, int userId) {
21277        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21278            throw new SecurityException("Only the system may call restorePreferredActivities()");
21279        }
21280
21281        try {
21282            final XmlPullParser parser = Xml.newPullParser();
21283            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21284            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21285                    new BlobXmlRestorer() {
21286                        @Override
21287                        public void apply(XmlPullParser parser, int userId)
21288                                throws XmlPullParserException, IOException {
21289                            synchronized (mPackages) {
21290                                mSettings.readPreferredActivitiesLPw(parser, userId);
21291                            }
21292                        }
21293                    } );
21294        } catch (Exception e) {
21295            if (DEBUG_BACKUP) {
21296                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21297            }
21298        }
21299    }
21300
21301    /**
21302     * Non-Binder method, support for the backup/restore mechanism: write the
21303     * default browser (etc) settings in its canonical XML format.  Returns the default
21304     * browser XML representation as a byte array, or null if there is none.
21305     */
21306    @Override
21307    public byte[] getDefaultAppsBackup(int userId) {
21308        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21309            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21310        }
21311
21312        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21313        try {
21314            final XmlSerializer serializer = new FastXmlSerializer();
21315            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21316            serializer.startDocument(null, true);
21317            serializer.startTag(null, TAG_DEFAULT_APPS);
21318
21319            synchronized (mPackages) {
21320                mSettings.writeDefaultAppsLPr(serializer, userId);
21321            }
21322
21323            serializer.endTag(null, TAG_DEFAULT_APPS);
21324            serializer.endDocument();
21325            serializer.flush();
21326        } catch (Exception e) {
21327            if (DEBUG_BACKUP) {
21328                Slog.e(TAG, "Unable to write default apps for backup", e);
21329            }
21330            return null;
21331        }
21332
21333        return dataStream.toByteArray();
21334    }
21335
21336    @Override
21337    public void restoreDefaultApps(byte[] backup, int userId) {
21338        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21339            throw new SecurityException("Only the system may call restoreDefaultApps()");
21340        }
21341
21342        try {
21343            final XmlPullParser parser = Xml.newPullParser();
21344            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21345            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21346                    new BlobXmlRestorer() {
21347                        @Override
21348                        public void apply(XmlPullParser parser, int userId)
21349                                throws XmlPullParserException, IOException {
21350                            synchronized (mPackages) {
21351                                mSettings.readDefaultAppsLPw(parser, userId);
21352                            }
21353                        }
21354                    } );
21355        } catch (Exception e) {
21356            if (DEBUG_BACKUP) {
21357                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21358            }
21359        }
21360    }
21361
21362    @Override
21363    public byte[] getIntentFilterVerificationBackup(int userId) {
21364        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21365            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21366        }
21367
21368        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21369        try {
21370            final XmlSerializer serializer = new FastXmlSerializer();
21371            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21372            serializer.startDocument(null, true);
21373            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21374
21375            synchronized (mPackages) {
21376                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21377            }
21378
21379            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21380            serializer.endDocument();
21381            serializer.flush();
21382        } catch (Exception e) {
21383            if (DEBUG_BACKUP) {
21384                Slog.e(TAG, "Unable to write default apps for backup", e);
21385            }
21386            return null;
21387        }
21388
21389        return dataStream.toByteArray();
21390    }
21391
21392    @Override
21393    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21394        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21395            throw new SecurityException("Only the system may call restorePreferredActivities()");
21396        }
21397
21398        try {
21399            final XmlPullParser parser = Xml.newPullParser();
21400            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21401            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21402                    new BlobXmlRestorer() {
21403                        @Override
21404                        public void apply(XmlPullParser parser, int userId)
21405                                throws XmlPullParserException, IOException {
21406                            synchronized (mPackages) {
21407                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21408                                mSettings.writeLPr();
21409                            }
21410                        }
21411                    } );
21412        } catch (Exception e) {
21413            if (DEBUG_BACKUP) {
21414                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21415            }
21416        }
21417    }
21418
21419    @Override
21420    public byte[] getPermissionGrantBackup(int userId) {
21421        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21422            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21423        }
21424
21425        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21426        try {
21427            final XmlSerializer serializer = new FastXmlSerializer();
21428            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21429            serializer.startDocument(null, true);
21430            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21431
21432            synchronized (mPackages) {
21433                serializeRuntimePermissionGrantsLPr(serializer, userId);
21434            }
21435
21436            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21437            serializer.endDocument();
21438            serializer.flush();
21439        } catch (Exception e) {
21440            if (DEBUG_BACKUP) {
21441                Slog.e(TAG, "Unable to write default apps for backup", e);
21442            }
21443            return null;
21444        }
21445
21446        return dataStream.toByteArray();
21447    }
21448
21449    @Override
21450    public void restorePermissionGrants(byte[] backup, int userId) {
21451        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21452            throw new SecurityException("Only the system may call restorePermissionGrants()");
21453        }
21454
21455        try {
21456            final XmlPullParser parser = Xml.newPullParser();
21457            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21458            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21459                    new BlobXmlRestorer() {
21460                        @Override
21461                        public void apply(XmlPullParser parser, int userId)
21462                                throws XmlPullParserException, IOException {
21463                            synchronized (mPackages) {
21464                                processRestoredPermissionGrantsLPr(parser, userId);
21465                            }
21466                        }
21467                    } );
21468        } catch (Exception e) {
21469            if (DEBUG_BACKUP) {
21470                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21471            }
21472        }
21473    }
21474
21475    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21476            throws IOException {
21477        serializer.startTag(null, TAG_ALL_GRANTS);
21478
21479        final int N = mSettings.mPackages.size();
21480        for (int i = 0; i < N; i++) {
21481            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21482            boolean pkgGrantsKnown = false;
21483
21484            PermissionsState packagePerms = ps.getPermissionsState();
21485
21486            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21487                final int grantFlags = state.getFlags();
21488                // only look at grants that are not system/policy fixed
21489                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21490                    final boolean isGranted = state.isGranted();
21491                    // And only back up the user-twiddled state bits
21492                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21493                        final String packageName = mSettings.mPackages.keyAt(i);
21494                        if (!pkgGrantsKnown) {
21495                            serializer.startTag(null, TAG_GRANT);
21496                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21497                            pkgGrantsKnown = true;
21498                        }
21499
21500                        final boolean userSet =
21501                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21502                        final boolean userFixed =
21503                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21504                        final boolean revoke =
21505                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21506
21507                        serializer.startTag(null, TAG_PERMISSION);
21508                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21509                        if (isGranted) {
21510                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21511                        }
21512                        if (userSet) {
21513                            serializer.attribute(null, ATTR_USER_SET, "true");
21514                        }
21515                        if (userFixed) {
21516                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21517                        }
21518                        if (revoke) {
21519                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21520                        }
21521                        serializer.endTag(null, TAG_PERMISSION);
21522                    }
21523                }
21524            }
21525
21526            if (pkgGrantsKnown) {
21527                serializer.endTag(null, TAG_GRANT);
21528            }
21529        }
21530
21531        serializer.endTag(null, TAG_ALL_GRANTS);
21532    }
21533
21534    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21535            throws XmlPullParserException, IOException {
21536        String pkgName = null;
21537        int outerDepth = parser.getDepth();
21538        int type;
21539        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21540                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21541            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21542                continue;
21543            }
21544
21545            final String tagName = parser.getName();
21546            if (tagName.equals(TAG_GRANT)) {
21547                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21548                if (DEBUG_BACKUP) {
21549                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21550                }
21551            } else if (tagName.equals(TAG_PERMISSION)) {
21552
21553                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21554                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21555
21556                int newFlagSet = 0;
21557                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21558                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21559                }
21560                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21561                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21562                }
21563                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21564                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21565                }
21566                if (DEBUG_BACKUP) {
21567                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21568                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21569                }
21570                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21571                if (ps != null) {
21572                    // Already installed so we apply the grant immediately
21573                    if (DEBUG_BACKUP) {
21574                        Slog.v(TAG, "        + already installed; applying");
21575                    }
21576                    PermissionsState perms = ps.getPermissionsState();
21577                    BasePermission bp = mSettings.mPermissions.get(permName);
21578                    if (bp != null) {
21579                        if (isGranted) {
21580                            perms.grantRuntimePermission(bp, userId);
21581                        }
21582                        if (newFlagSet != 0) {
21583                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21584                        }
21585                    }
21586                } else {
21587                    // Need to wait for post-restore install to apply the grant
21588                    if (DEBUG_BACKUP) {
21589                        Slog.v(TAG, "        - not yet installed; saving for later");
21590                    }
21591                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21592                            isGranted, newFlagSet, userId);
21593                }
21594            } else {
21595                PackageManagerService.reportSettingsProblem(Log.WARN,
21596                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21597                XmlUtils.skipCurrentTag(parser);
21598            }
21599        }
21600
21601        scheduleWriteSettingsLocked();
21602        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21603    }
21604
21605    @Override
21606    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21607            int sourceUserId, int targetUserId, int flags) {
21608        mContext.enforceCallingOrSelfPermission(
21609                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21610        int callingUid = Binder.getCallingUid();
21611        enforceOwnerRights(ownerPackage, callingUid);
21612        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21613        if (intentFilter.countActions() == 0) {
21614            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21615            return;
21616        }
21617        synchronized (mPackages) {
21618            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21619                    ownerPackage, targetUserId, flags);
21620            CrossProfileIntentResolver resolver =
21621                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21622            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21623            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21624            if (existing != null) {
21625                int size = existing.size();
21626                for (int i = 0; i < size; i++) {
21627                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21628                        return;
21629                    }
21630                }
21631            }
21632            resolver.addFilter(newFilter);
21633            scheduleWritePackageRestrictionsLocked(sourceUserId);
21634        }
21635    }
21636
21637    @Override
21638    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21639        mContext.enforceCallingOrSelfPermission(
21640                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21641        final int callingUid = Binder.getCallingUid();
21642        enforceOwnerRights(ownerPackage, callingUid);
21643        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21644        synchronized (mPackages) {
21645            CrossProfileIntentResolver resolver =
21646                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21647            ArraySet<CrossProfileIntentFilter> set =
21648                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21649            for (CrossProfileIntentFilter filter : set) {
21650                if (filter.getOwnerPackage().equals(ownerPackage)) {
21651                    resolver.removeFilter(filter);
21652                }
21653            }
21654            scheduleWritePackageRestrictionsLocked(sourceUserId);
21655        }
21656    }
21657
21658    // Enforcing that callingUid is owning pkg on userId
21659    private void enforceOwnerRights(String pkg, int callingUid) {
21660        // The system owns everything.
21661        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21662            return;
21663        }
21664        final int callingUserId = UserHandle.getUserId(callingUid);
21665        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21666        if (pi == null) {
21667            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21668                    + callingUserId);
21669        }
21670        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21671            throw new SecurityException("Calling uid " + callingUid
21672                    + " does not own package " + pkg);
21673        }
21674    }
21675
21676    @Override
21677    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21678        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21679            return null;
21680        }
21681        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21682    }
21683
21684    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21685        UserManagerService ums = UserManagerService.getInstance();
21686        if (ums != null) {
21687            final UserInfo parent = ums.getProfileParent(userId);
21688            final int launcherUid = (parent != null) ? parent.id : userId;
21689            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21690            if (launcherComponent != null) {
21691                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21692                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21693                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21694                        .setPackage(launcherComponent.getPackageName());
21695                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21696            }
21697        }
21698    }
21699
21700    /**
21701     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21702     * then reports the most likely home activity or null if there are more than one.
21703     */
21704    private ComponentName getDefaultHomeActivity(int userId) {
21705        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21706        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21707        if (cn != null) {
21708            return cn;
21709        }
21710
21711        // Find the launcher with the highest priority and return that component if there are no
21712        // other home activity with the same priority.
21713        int lastPriority = Integer.MIN_VALUE;
21714        ComponentName lastComponent = null;
21715        final int size = allHomeCandidates.size();
21716        for (int i = 0; i < size; i++) {
21717            final ResolveInfo ri = allHomeCandidates.get(i);
21718            if (ri.priority > lastPriority) {
21719                lastComponent = ri.activityInfo.getComponentName();
21720                lastPriority = ri.priority;
21721            } else if (ri.priority == lastPriority) {
21722                // Two components found with same priority.
21723                lastComponent = null;
21724            }
21725        }
21726        return lastComponent;
21727    }
21728
21729    private Intent getHomeIntent() {
21730        Intent intent = new Intent(Intent.ACTION_MAIN);
21731        intent.addCategory(Intent.CATEGORY_HOME);
21732        intent.addCategory(Intent.CATEGORY_DEFAULT);
21733        return intent;
21734    }
21735
21736    private IntentFilter getHomeFilter() {
21737        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21738        filter.addCategory(Intent.CATEGORY_HOME);
21739        filter.addCategory(Intent.CATEGORY_DEFAULT);
21740        return filter;
21741    }
21742
21743    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21744            int userId) {
21745        Intent intent  = getHomeIntent();
21746        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21747                PackageManager.GET_META_DATA, userId);
21748        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21749                true, false, false, userId);
21750
21751        allHomeCandidates.clear();
21752        if (list != null) {
21753            for (ResolveInfo ri : list) {
21754                allHomeCandidates.add(ri);
21755            }
21756        }
21757        return (preferred == null || preferred.activityInfo == null)
21758                ? null
21759                : new ComponentName(preferred.activityInfo.packageName,
21760                        preferred.activityInfo.name);
21761    }
21762
21763    @Override
21764    public void setHomeActivity(ComponentName comp, int userId) {
21765        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21766            return;
21767        }
21768        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21769        getHomeActivitiesAsUser(homeActivities, userId);
21770
21771        boolean found = false;
21772
21773        final int size = homeActivities.size();
21774        final ComponentName[] set = new ComponentName[size];
21775        for (int i = 0; i < size; i++) {
21776            final ResolveInfo candidate = homeActivities.get(i);
21777            final ActivityInfo info = candidate.activityInfo;
21778            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21779            set[i] = activityName;
21780            if (!found && activityName.equals(comp)) {
21781                found = true;
21782            }
21783        }
21784        if (!found) {
21785            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21786                    + userId);
21787        }
21788        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21789                set, comp, userId);
21790    }
21791
21792    private @Nullable String getSetupWizardPackageName() {
21793        final Intent intent = new Intent(Intent.ACTION_MAIN);
21794        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21795
21796        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21797                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21798                        | MATCH_DISABLED_COMPONENTS,
21799                UserHandle.myUserId());
21800        if (matches.size() == 1) {
21801            return matches.get(0).getComponentInfo().packageName;
21802        } else {
21803            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21804                    + ": matches=" + matches);
21805            return null;
21806        }
21807    }
21808
21809    private @Nullable String getStorageManagerPackageName() {
21810        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21811
21812        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21813                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21814                        | MATCH_DISABLED_COMPONENTS,
21815                UserHandle.myUserId());
21816        if (matches.size() == 1) {
21817            return matches.get(0).getComponentInfo().packageName;
21818        } else {
21819            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21820                    + matches.size() + ": matches=" + matches);
21821            return null;
21822        }
21823    }
21824
21825    @Override
21826    public void setApplicationEnabledSetting(String appPackageName,
21827            int newState, int flags, int userId, String callingPackage) {
21828        if (!sUserManager.exists(userId)) return;
21829        if (callingPackage == null) {
21830            callingPackage = Integer.toString(Binder.getCallingUid());
21831        }
21832        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21833    }
21834
21835    @Override
21836    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21837        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21838        synchronized (mPackages) {
21839            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21840            if (pkgSetting != null) {
21841                pkgSetting.setUpdateAvailable(updateAvailable);
21842            }
21843        }
21844    }
21845
21846    @Override
21847    public void setComponentEnabledSetting(ComponentName componentName,
21848            int newState, int flags, int userId) {
21849        if (!sUserManager.exists(userId)) return;
21850        setEnabledSetting(componentName.getPackageName(),
21851                componentName.getClassName(), newState, flags, userId, null);
21852    }
21853
21854    private void setEnabledSetting(final String packageName, String className, int newState,
21855            final int flags, int userId, String callingPackage) {
21856        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21857              || newState == COMPONENT_ENABLED_STATE_ENABLED
21858              || newState == COMPONENT_ENABLED_STATE_DISABLED
21859              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21860              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21861            throw new IllegalArgumentException("Invalid new component state: "
21862                    + newState);
21863        }
21864        PackageSetting pkgSetting;
21865        final int callingUid = Binder.getCallingUid();
21866        final int permission;
21867        if (callingUid == Process.SYSTEM_UID) {
21868            permission = PackageManager.PERMISSION_GRANTED;
21869        } else {
21870            permission = mContext.checkCallingOrSelfPermission(
21871                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21872        }
21873        enforceCrossUserPermission(callingUid, userId,
21874                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21875        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21876        boolean sendNow = false;
21877        boolean isApp = (className == null);
21878        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21879        String componentName = isApp ? packageName : className;
21880        int packageUid = -1;
21881        ArrayList<String> components;
21882
21883        // reader
21884        synchronized (mPackages) {
21885            pkgSetting = mSettings.mPackages.get(packageName);
21886            if (pkgSetting == null) {
21887                if (!isCallerInstantApp) {
21888                    if (className == null) {
21889                        throw new IllegalArgumentException("Unknown package: " + packageName);
21890                    }
21891                    throw new IllegalArgumentException(
21892                            "Unknown component: " + packageName + "/" + className);
21893                } else {
21894                    // throw SecurityException to prevent leaking package information
21895                    throw new SecurityException(
21896                            "Attempt to change component state; "
21897                            + "pid=" + Binder.getCallingPid()
21898                            + ", uid=" + callingUid
21899                            + (className == null
21900                                    ? ", package=" + packageName
21901                                    : ", component=" + packageName + "/" + className));
21902                }
21903            }
21904        }
21905
21906        // Limit who can change which apps
21907        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21908            // Don't allow apps that don't have permission to modify other apps
21909            if (!allowedByPermission
21910                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21911                throw new SecurityException(
21912                        "Attempt to change component state; "
21913                        + "pid=" + Binder.getCallingPid()
21914                        + ", uid=" + callingUid
21915                        + (className == null
21916                                ? ", package=" + packageName
21917                                : ", component=" + packageName + "/" + className));
21918            }
21919            // Don't allow changing protected packages.
21920            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21921                throw new SecurityException("Cannot disable a protected package: " + packageName);
21922            }
21923        }
21924
21925        synchronized (mPackages) {
21926            if (callingUid == Process.SHELL_UID
21927                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21928                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21929                // unless it is a test package.
21930                int oldState = pkgSetting.getEnabled(userId);
21931                if (className == null
21932                        &&
21933                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21934                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21935                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21936                        &&
21937                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21938                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21939                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21940                    // ok
21941                } else {
21942                    throw new SecurityException(
21943                            "Shell cannot change component state for " + packageName + "/"
21944                                    + className + " to " + newState);
21945                }
21946            }
21947        }
21948        if (className == null) {
21949            // We're dealing with an application/package level state change
21950            synchronized (mPackages) {
21951                if (pkgSetting.getEnabled(userId) == newState) {
21952                    // Nothing to do
21953                    return;
21954                }
21955            }
21956            // If we're enabling a system stub, there's a little more work to do.
21957            // Prior to enabling the package, we need to decompress the APK(s) to the
21958            // data partition and then replace the version on the system partition.
21959            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21960            final boolean isSystemStub = deletedPkg.isStub
21961                    && deletedPkg.isSystemApp();
21962            if (isSystemStub
21963                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21964                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21965                final File codePath = decompressPackage(deletedPkg);
21966                if (codePath == null) {
21967                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21968                    return;
21969                }
21970                // TODO remove direct parsing of the package object during internal cleanup
21971                // of scan package
21972                // We need to call parse directly here for no other reason than we need
21973                // the new package in order to disable the old one [we use the information
21974                // for some internal optimization to optionally create a new package setting
21975                // object on replace]. However, we can't get the package from the scan
21976                // because the scan modifies live structures and we need to remove the
21977                // old [system] package from the system before a scan can be attempted.
21978                // Once scan is indempotent we can remove this parse and use the package
21979                // object we scanned, prior to adding it to package settings.
21980                final PackageParser pp = new PackageParser();
21981                pp.setSeparateProcesses(mSeparateProcesses);
21982                pp.setDisplayMetrics(mMetrics);
21983                pp.setCallback(mPackageParserCallback);
21984                final PackageParser.Package tmpPkg;
21985                try {
21986                    final int parseFlags = mDefParseFlags
21987                            | PackageParser.PARSE_MUST_BE_APK
21988                            | PackageParser.PARSE_IS_SYSTEM
21989                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21990                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21991                } catch (PackageParserException e) {
21992                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21993                    return;
21994                }
21995                synchronized (mInstallLock) {
21996                    // Disable the stub and remove any package entries
21997                    removePackageLI(deletedPkg, true);
21998                    synchronized (mPackages) {
21999                        disableSystemPackageLPw(deletedPkg, tmpPkg);
22000                    }
22001                    final PackageParser.Package newPkg;
22002                    try (PackageFreezer freezer =
22003                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22004                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
22005                                | PackageParser.PARSE_ENFORCE_CODE;
22006                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
22007                                0 /*currentTime*/, null /*user*/);
22008                        prepareAppDataAfterInstallLIF(newPkg);
22009                        synchronized (mPackages) {
22010                            try {
22011                                updateSharedLibrariesLPr(newPkg, null);
22012                            } catch (PackageManagerException e) {
22013                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
22014                            }
22015                            updatePermissionsLPw(newPkg.packageName, newPkg,
22016                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
22017                            mSettings.writeLPr();
22018                        }
22019                    } catch (PackageManagerException e) {
22020                        // Whoops! Something went wrong; try to roll back to the stub
22021                        Slog.w(TAG, "Failed to install compressed system package:"
22022                                + pkgSetting.name, e);
22023                        // Remove the failed install
22024                        removeCodePathLI(codePath);
22025
22026                        // Install the system package
22027                        try (PackageFreezer freezer =
22028                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22029                            synchronized (mPackages) {
22030                                // NOTE: The system package always needs to be enabled; even
22031                                // if it's for a compressed stub. If we don't, installing the
22032                                // system package fails during scan [scanning checks the disabled
22033                                // packages]. We will reverse this later, after we've "installed"
22034                                // the stub.
22035                                // This leaves us in a fragile state; the stub should never be
22036                                // enabled, so, cross your fingers and hope nothing goes wrong
22037                                // until we can disable the package later.
22038                                enableSystemPackageLPw(deletedPkg);
22039                            }
22040                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
22041                                    false /*isPrivileged*/, null /*allUserHandles*/,
22042                                    null /*origUserHandles*/, null /*origPermissionsState*/,
22043                                    true /*writeSettings*/);
22044                        } catch (PackageManagerException pme) {
22045                            Slog.w(TAG, "Failed to restore system package:"
22046                                    + deletedPkg.packageName, pme);
22047                        } finally {
22048                            synchronized (mPackages) {
22049                                mSettings.disableSystemPackageLPw(
22050                                        deletedPkg.packageName, true /*replaced*/);
22051                                mSettings.writeLPr();
22052                            }
22053                        }
22054                        return;
22055                    }
22056                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22057                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22058                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
22059                    mDexManager.notifyPackageUpdated(newPkg.packageName,
22060                            newPkg.baseCodePath, newPkg.splitCodePaths);
22061                }
22062            }
22063            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22064                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22065                // Don't care about who enables an app.
22066                callingPackage = null;
22067            }
22068            synchronized (mPackages) {
22069                pkgSetting.setEnabled(newState, userId, callingPackage);
22070            }
22071        } else {
22072            synchronized (mPackages) {
22073                // We're dealing with a component level state change
22074                // First, verify that this is a valid class name.
22075                PackageParser.Package pkg = pkgSetting.pkg;
22076                if (pkg == null || !pkg.hasComponentClassName(className)) {
22077                    if (pkg != null &&
22078                            pkg.applicationInfo.targetSdkVersion >=
22079                                    Build.VERSION_CODES.JELLY_BEAN) {
22080                        throw new IllegalArgumentException("Component class " + className
22081                                + " does not exist in " + packageName);
22082                    } else {
22083                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22084                                + className + " does not exist in " + packageName);
22085                    }
22086                }
22087                switch (newState) {
22088                    case COMPONENT_ENABLED_STATE_ENABLED:
22089                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22090                            return;
22091                        }
22092                        break;
22093                    case COMPONENT_ENABLED_STATE_DISABLED:
22094                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22095                            return;
22096                        }
22097                        break;
22098                    case COMPONENT_ENABLED_STATE_DEFAULT:
22099                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22100                            return;
22101                        }
22102                        break;
22103                    default:
22104                        Slog.e(TAG, "Invalid new component state: " + newState);
22105                        return;
22106                }
22107            }
22108        }
22109        synchronized (mPackages) {
22110            scheduleWritePackageRestrictionsLocked(userId);
22111            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22112            final long callingId = Binder.clearCallingIdentity();
22113            try {
22114                updateInstantAppInstallerLocked(packageName);
22115            } finally {
22116                Binder.restoreCallingIdentity(callingId);
22117            }
22118            components = mPendingBroadcasts.get(userId, packageName);
22119            final boolean newPackage = components == null;
22120            if (newPackage) {
22121                components = new ArrayList<String>();
22122            }
22123            if (!components.contains(componentName)) {
22124                components.add(componentName);
22125            }
22126            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22127                sendNow = true;
22128                // Purge entry from pending broadcast list if another one exists already
22129                // since we are sending one right away.
22130                mPendingBroadcasts.remove(userId, packageName);
22131            } else {
22132                if (newPackage) {
22133                    mPendingBroadcasts.put(userId, packageName, components);
22134                }
22135                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22136                    // Schedule a message
22137                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22138                }
22139            }
22140        }
22141
22142        long callingId = Binder.clearCallingIdentity();
22143        try {
22144            if (sendNow) {
22145                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22146                sendPackageChangedBroadcast(packageName,
22147                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22148            }
22149        } finally {
22150            Binder.restoreCallingIdentity(callingId);
22151        }
22152    }
22153
22154    @Override
22155    public void flushPackageRestrictionsAsUser(int userId) {
22156        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22157            return;
22158        }
22159        if (!sUserManager.exists(userId)) {
22160            return;
22161        }
22162        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22163                false /* checkShell */, "flushPackageRestrictions");
22164        synchronized (mPackages) {
22165            mSettings.writePackageRestrictionsLPr(userId);
22166            mDirtyUsers.remove(userId);
22167            if (mDirtyUsers.isEmpty()) {
22168                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22169            }
22170        }
22171    }
22172
22173    private void sendPackageChangedBroadcast(String packageName,
22174            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22175        if (DEBUG_INSTALL)
22176            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22177                    + componentNames);
22178        Bundle extras = new Bundle(4);
22179        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22180        String nameList[] = new String[componentNames.size()];
22181        componentNames.toArray(nameList);
22182        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22183        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22184        extras.putInt(Intent.EXTRA_UID, packageUid);
22185        // If this is not reporting a change of the overall package, then only send it
22186        // to registered receivers.  We don't want to launch a swath of apps for every
22187        // little component state change.
22188        final int flags = !componentNames.contains(packageName)
22189                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22190        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22191                new int[] {UserHandle.getUserId(packageUid)});
22192    }
22193
22194    @Override
22195    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22196        if (!sUserManager.exists(userId)) return;
22197        final int callingUid = Binder.getCallingUid();
22198        if (getInstantAppPackageName(callingUid) != null) {
22199            return;
22200        }
22201        final int permission = mContext.checkCallingOrSelfPermission(
22202                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22203        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22204        enforceCrossUserPermission(callingUid, userId,
22205                true /* requireFullPermission */, true /* checkShell */, "stop package");
22206        // writer
22207        synchronized (mPackages) {
22208            final PackageSetting ps = mSettings.mPackages.get(packageName);
22209            if (!filterAppAccessLPr(ps, callingUid, userId)
22210                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22211                            allowedByPermission, callingUid, userId)) {
22212                scheduleWritePackageRestrictionsLocked(userId);
22213            }
22214        }
22215    }
22216
22217    @Override
22218    public String getInstallerPackageName(String packageName) {
22219        final int callingUid = Binder.getCallingUid();
22220        if (getInstantAppPackageName(callingUid) != null) {
22221            return null;
22222        }
22223        // reader
22224        synchronized (mPackages) {
22225            final PackageSetting ps = mSettings.mPackages.get(packageName);
22226            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22227                return null;
22228            }
22229            return mSettings.getInstallerPackageNameLPr(packageName);
22230        }
22231    }
22232
22233    public boolean isOrphaned(String packageName) {
22234        // reader
22235        synchronized (mPackages) {
22236            return mSettings.isOrphaned(packageName);
22237        }
22238    }
22239
22240    @Override
22241    public int getApplicationEnabledSetting(String packageName, int userId) {
22242        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22243        int callingUid = Binder.getCallingUid();
22244        enforceCrossUserPermission(callingUid, userId,
22245                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22246        // reader
22247        synchronized (mPackages) {
22248            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22249                return COMPONENT_ENABLED_STATE_DISABLED;
22250            }
22251            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22252        }
22253    }
22254
22255    @Override
22256    public int getComponentEnabledSetting(ComponentName component, int userId) {
22257        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22258        int callingUid = Binder.getCallingUid();
22259        enforceCrossUserPermission(callingUid, userId,
22260                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22261        synchronized (mPackages) {
22262            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22263                    component, TYPE_UNKNOWN, userId)) {
22264                return COMPONENT_ENABLED_STATE_DISABLED;
22265            }
22266            return mSettings.getComponentEnabledSettingLPr(component, userId);
22267        }
22268    }
22269
22270    @Override
22271    public void enterSafeMode() {
22272        enforceSystemOrRoot("Only the system can request entering safe mode");
22273
22274        if (!mSystemReady) {
22275            mSafeMode = true;
22276        }
22277    }
22278
22279    @Override
22280    public void systemReady() {
22281        enforceSystemOrRoot("Only the system can claim the system is ready");
22282
22283        mSystemReady = true;
22284        final ContentResolver resolver = mContext.getContentResolver();
22285        ContentObserver co = new ContentObserver(mHandler) {
22286            @Override
22287            public void onChange(boolean selfChange) {
22288                mEphemeralAppsDisabled =
22289                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22290                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22291            }
22292        };
22293        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22294                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22295                false, co, UserHandle.USER_SYSTEM);
22296        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22297                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22298        co.onChange(true);
22299
22300        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22301        // disabled after already being started.
22302        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22303                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22304
22305        // Read the compatibilty setting when the system is ready.
22306        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22307                mContext.getContentResolver(),
22308                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22309        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22310        if (DEBUG_SETTINGS) {
22311            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22312        }
22313
22314        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22315
22316        synchronized (mPackages) {
22317            // Verify that all of the preferred activity components actually
22318            // exist.  It is possible for applications to be updated and at
22319            // that point remove a previously declared activity component that
22320            // had been set as a preferred activity.  We try to clean this up
22321            // the next time we encounter that preferred activity, but it is
22322            // possible for the user flow to never be able to return to that
22323            // situation so here we do a sanity check to make sure we haven't
22324            // left any junk around.
22325            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22326            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22327                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22328                removed.clear();
22329                for (PreferredActivity pa : pir.filterSet()) {
22330                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22331                        removed.add(pa);
22332                    }
22333                }
22334                if (removed.size() > 0) {
22335                    for (int r=0; r<removed.size(); r++) {
22336                        PreferredActivity pa = removed.get(r);
22337                        Slog.w(TAG, "Removing dangling preferred activity: "
22338                                + pa.mPref.mComponent);
22339                        pir.removeFilter(pa);
22340                    }
22341                    mSettings.writePackageRestrictionsLPr(
22342                            mSettings.mPreferredActivities.keyAt(i));
22343                }
22344            }
22345
22346            for (int userId : UserManagerService.getInstance().getUserIds()) {
22347                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22348                    grantPermissionsUserIds = ArrayUtils.appendInt(
22349                            grantPermissionsUserIds, userId);
22350                }
22351            }
22352        }
22353        sUserManager.systemReady();
22354
22355        // If we upgraded grant all default permissions before kicking off.
22356        for (int userId : grantPermissionsUserIds) {
22357            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22358        }
22359
22360        // If we did not grant default permissions, we preload from this the
22361        // default permission exceptions lazily to ensure we don't hit the
22362        // disk on a new user creation.
22363        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22364            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22365        }
22366
22367        // Kick off any messages waiting for system ready
22368        if (mPostSystemReadyMessages != null) {
22369            for (Message msg : mPostSystemReadyMessages) {
22370                msg.sendToTarget();
22371            }
22372            mPostSystemReadyMessages = null;
22373        }
22374
22375        // Watch for external volumes that come and go over time
22376        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22377        storage.registerListener(mStorageListener);
22378
22379        mInstallerService.systemReady();
22380        mPackageDexOptimizer.systemReady();
22381
22382        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22383                StorageManagerInternal.class);
22384        StorageManagerInternal.addExternalStoragePolicy(
22385                new StorageManagerInternal.ExternalStorageMountPolicy() {
22386            @Override
22387            public int getMountMode(int uid, String packageName) {
22388                if (Process.isIsolated(uid)) {
22389                    return Zygote.MOUNT_EXTERNAL_NONE;
22390                }
22391                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22392                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22393                }
22394                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22395                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22396                }
22397                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22398                    return Zygote.MOUNT_EXTERNAL_READ;
22399                }
22400                return Zygote.MOUNT_EXTERNAL_WRITE;
22401            }
22402
22403            @Override
22404            public boolean hasExternalStorage(int uid, String packageName) {
22405                return true;
22406            }
22407        });
22408
22409        // Now that we're mostly running, clean up stale users and apps
22410        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22411        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22412
22413        if (mPrivappPermissionsViolations != null) {
22414            Slog.wtf(TAG,"Signature|privileged permissions not in "
22415                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22416            mPrivappPermissionsViolations = null;
22417        }
22418    }
22419
22420    public void waitForAppDataPrepared() {
22421        if (mPrepareAppDataFuture == null) {
22422            return;
22423        }
22424        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22425        mPrepareAppDataFuture = null;
22426    }
22427
22428    @Override
22429    public boolean isSafeMode() {
22430        // allow instant applications
22431        return mSafeMode;
22432    }
22433
22434    @Override
22435    public boolean hasSystemUidErrors() {
22436        // allow instant applications
22437        return mHasSystemUidErrors;
22438    }
22439
22440    static String arrayToString(int[] array) {
22441        StringBuffer buf = new StringBuffer(128);
22442        buf.append('[');
22443        if (array != null) {
22444            for (int i=0; i<array.length; i++) {
22445                if (i > 0) buf.append(", ");
22446                buf.append(array[i]);
22447            }
22448        }
22449        buf.append(']');
22450        return buf.toString();
22451    }
22452
22453    static class DumpState {
22454        public static final int DUMP_LIBS = 1 << 0;
22455        public static final int DUMP_FEATURES = 1 << 1;
22456        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22457        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22458        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22459        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22460        public static final int DUMP_PERMISSIONS = 1 << 6;
22461        public static final int DUMP_PACKAGES = 1 << 7;
22462        public static final int DUMP_SHARED_USERS = 1 << 8;
22463        public static final int DUMP_MESSAGES = 1 << 9;
22464        public static final int DUMP_PROVIDERS = 1 << 10;
22465        public static final int DUMP_VERIFIERS = 1 << 11;
22466        public static final int DUMP_PREFERRED = 1 << 12;
22467        public static final int DUMP_PREFERRED_XML = 1 << 13;
22468        public static final int DUMP_KEYSETS = 1 << 14;
22469        public static final int DUMP_VERSION = 1 << 15;
22470        public static final int DUMP_INSTALLS = 1 << 16;
22471        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22472        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22473        public static final int DUMP_FROZEN = 1 << 19;
22474        public static final int DUMP_DEXOPT = 1 << 20;
22475        public static final int DUMP_COMPILER_STATS = 1 << 21;
22476        public static final int DUMP_CHANGES = 1 << 22;
22477        public static final int DUMP_VOLUMES = 1 << 23;
22478
22479        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22480
22481        private int mTypes;
22482
22483        private int mOptions;
22484
22485        private boolean mTitlePrinted;
22486
22487        private SharedUserSetting mSharedUser;
22488
22489        public boolean isDumping(int type) {
22490            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22491                return true;
22492            }
22493
22494            return (mTypes & type) != 0;
22495        }
22496
22497        public void setDump(int type) {
22498            mTypes |= type;
22499        }
22500
22501        public boolean isOptionEnabled(int option) {
22502            return (mOptions & option) != 0;
22503        }
22504
22505        public void setOptionEnabled(int option) {
22506            mOptions |= option;
22507        }
22508
22509        public boolean onTitlePrinted() {
22510            final boolean printed = mTitlePrinted;
22511            mTitlePrinted = true;
22512            return printed;
22513        }
22514
22515        public boolean getTitlePrinted() {
22516            return mTitlePrinted;
22517        }
22518
22519        public void setTitlePrinted(boolean enabled) {
22520            mTitlePrinted = enabled;
22521        }
22522
22523        public SharedUserSetting getSharedUser() {
22524            return mSharedUser;
22525        }
22526
22527        public void setSharedUser(SharedUserSetting user) {
22528            mSharedUser = user;
22529        }
22530    }
22531
22532    @Override
22533    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22534            FileDescriptor err, String[] args, ShellCallback callback,
22535            ResultReceiver resultReceiver) {
22536        (new PackageManagerShellCommand(this)).exec(
22537                this, in, out, err, args, callback, resultReceiver);
22538    }
22539
22540    @Override
22541    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22542        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22543
22544        DumpState dumpState = new DumpState();
22545        boolean fullPreferred = false;
22546        boolean checkin = false;
22547
22548        String packageName = null;
22549        ArraySet<String> permissionNames = null;
22550
22551        int opti = 0;
22552        while (opti < args.length) {
22553            String opt = args[opti];
22554            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22555                break;
22556            }
22557            opti++;
22558
22559            if ("-a".equals(opt)) {
22560                // Right now we only know how to print all.
22561            } else if ("-h".equals(opt)) {
22562                pw.println("Package manager dump options:");
22563                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22564                pw.println("    --checkin: dump for a checkin");
22565                pw.println("    -f: print details of intent filters");
22566                pw.println("    -h: print this help");
22567                pw.println("  cmd may be one of:");
22568                pw.println("    l[ibraries]: list known shared libraries");
22569                pw.println("    f[eatures]: list device features");
22570                pw.println("    k[eysets]: print known keysets");
22571                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22572                pw.println("    perm[issions]: dump permissions");
22573                pw.println("    permission [name ...]: dump declaration and use of given permission");
22574                pw.println("    pref[erred]: print preferred package settings");
22575                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22576                pw.println("    prov[iders]: dump content providers");
22577                pw.println("    p[ackages]: dump installed packages");
22578                pw.println("    s[hared-users]: dump shared user IDs");
22579                pw.println("    m[essages]: print collected runtime messages");
22580                pw.println("    v[erifiers]: print package verifier info");
22581                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22582                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22583                pw.println("    version: print database version info");
22584                pw.println("    write: write current settings now");
22585                pw.println("    installs: details about install sessions");
22586                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22587                pw.println("    dexopt: dump dexopt state");
22588                pw.println("    compiler-stats: dump compiler statistics");
22589                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22590                pw.println("    <package.name>: info about given package");
22591                return;
22592            } else if ("--checkin".equals(opt)) {
22593                checkin = true;
22594            } else if ("-f".equals(opt)) {
22595                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22596            } else if ("--proto".equals(opt)) {
22597                dumpProto(fd);
22598                return;
22599            } else {
22600                pw.println("Unknown argument: " + opt + "; use -h for help");
22601            }
22602        }
22603
22604        // Is the caller requesting to dump a particular piece of data?
22605        if (opti < args.length) {
22606            String cmd = args[opti];
22607            opti++;
22608            // Is this a package name?
22609            if ("android".equals(cmd) || cmd.contains(".")) {
22610                packageName = cmd;
22611                // When dumping a single package, we always dump all of its
22612                // filter information since the amount of data will be reasonable.
22613                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22614            } else if ("check-permission".equals(cmd)) {
22615                if (opti >= args.length) {
22616                    pw.println("Error: check-permission missing permission argument");
22617                    return;
22618                }
22619                String perm = args[opti];
22620                opti++;
22621                if (opti >= args.length) {
22622                    pw.println("Error: check-permission missing package argument");
22623                    return;
22624                }
22625
22626                String pkg = args[opti];
22627                opti++;
22628                int user = UserHandle.getUserId(Binder.getCallingUid());
22629                if (opti < args.length) {
22630                    try {
22631                        user = Integer.parseInt(args[opti]);
22632                    } catch (NumberFormatException e) {
22633                        pw.println("Error: check-permission user argument is not a number: "
22634                                + args[opti]);
22635                        return;
22636                    }
22637                }
22638
22639                // Normalize package name to handle renamed packages and static libs
22640                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22641
22642                pw.println(checkPermission(perm, pkg, user));
22643                return;
22644            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22645                dumpState.setDump(DumpState.DUMP_LIBS);
22646            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22647                dumpState.setDump(DumpState.DUMP_FEATURES);
22648            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22649                if (opti >= args.length) {
22650                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22651                            | DumpState.DUMP_SERVICE_RESOLVERS
22652                            | DumpState.DUMP_RECEIVER_RESOLVERS
22653                            | DumpState.DUMP_CONTENT_RESOLVERS);
22654                } else {
22655                    while (opti < args.length) {
22656                        String name = args[opti];
22657                        if ("a".equals(name) || "activity".equals(name)) {
22658                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22659                        } else if ("s".equals(name) || "service".equals(name)) {
22660                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22661                        } else if ("r".equals(name) || "receiver".equals(name)) {
22662                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22663                        } else if ("c".equals(name) || "content".equals(name)) {
22664                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22665                        } else {
22666                            pw.println("Error: unknown resolver table type: " + name);
22667                            return;
22668                        }
22669                        opti++;
22670                    }
22671                }
22672            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22673                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22674            } else if ("permission".equals(cmd)) {
22675                if (opti >= args.length) {
22676                    pw.println("Error: permission requires permission name");
22677                    return;
22678                }
22679                permissionNames = new ArraySet<>();
22680                while (opti < args.length) {
22681                    permissionNames.add(args[opti]);
22682                    opti++;
22683                }
22684                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22685                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22686            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22687                dumpState.setDump(DumpState.DUMP_PREFERRED);
22688            } else if ("preferred-xml".equals(cmd)) {
22689                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22690                if (opti < args.length && "--full".equals(args[opti])) {
22691                    fullPreferred = true;
22692                    opti++;
22693                }
22694            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22695                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22696            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22697                dumpState.setDump(DumpState.DUMP_PACKAGES);
22698            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22699                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22700            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22701                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22702            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22703                dumpState.setDump(DumpState.DUMP_MESSAGES);
22704            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22705                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22706            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22707                    || "intent-filter-verifiers".equals(cmd)) {
22708                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22709            } else if ("version".equals(cmd)) {
22710                dumpState.setDump(DumpState.DUMP_VERSION);
22711            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22712                dumpState.setDump(DumpState.DUMP_KEYSETS);
22713            } else if ("installs".equals(cmd)) {
22714                dumpState.setDump(DumpState.DUMP_INSTALLS);
22715            } else if ("frozen".equals(cmd)) {
22716                dumpState.setDump(DumpState.DUMP_FROZEN);
22717            } else if ("volumes".equals(cmd)) {
22718                dumpState.setDump(DumpState.DUMP_VOLUMES);
22719            } else if ("dexopt".equals(cmd)) {
22720                dumpState.setDump(DumpState.DUMP_DEXOPT);
22721            } else if ("compiler-stats".equals(cmd)) {
22722                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22723            } else if ("changes".equals(cmd)) {
22724                dumpState.setDump(DumpState.DUMP_CHANGES);
22725            } else if ("write".equals(cmd)) {
22726                synchronized (mPackages) {
22727                    mSettings.writeLPr();
22728                    pw.println("Settings written.");
22729                    return;
22730                }
22731            }
22732        }
22733
22734        if (checkin) {
22735            pw.println("vers,1");
22736        }
22737
22738        // reader
22739        synchronized (mPackages) {
22740            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22741                if (!checkin) {
22742                    if (dumpState.onTitlePrinted())
22743                        pw.println();
22744                    pw.println("Database versions:");
22745                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22746                }
22747            }
22748
22749            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22750                if (!checkin) {
22751                    if (dumpState.onTitlePrinted())
22752                        pw.println();
22753                    pw.println("Verifiers:");
22754                    pw.print("  Required: ");
22755                    pw.print(mRequiredVerifierPackage);
22756                    pw.print(" (uid=");
22757                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22758                            UserHandle.USER_SYSTEM));
22759                    pw.println(")");
22760                } else if (mRequiredVerifierPackage != null) {
22761                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22762                    pw.print(",");
22763                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22764                            UserHandle.USER_SYSTEM));
22765                }
22766            }
22767
22768            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22769                    packageName == null) {
22770                if (mIntentFilterVerifierComponent != null) {
22771                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22772                    if (!checkin) {
22773                        if (dumpState.onTitlePrinted())
22774                            pw.println();
22775                        pw.println("Intent Filter Verifier:");
22776                        pw.print("  Using: ");
22777                        pw.print(verifierPackageName);
22778                        pw.print(" (uid=");
22779                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22780                                UserHandle.USER_SYSTEM));
22781                        pw.println(")");
22782                    } else if (verifierPackageName != null) {
22783                        pw.print("ifv,"); pw.print(verifierPackageName);
22784                        pw.print(",");
22785                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22786                                UserHandle.USER_SYSTEM));
22787                    }
22788                } else {
22789                    pw.println();
22790                    pw.println("No Intent Filter Verifier available!");
22791                }
22792            }
22793
22794            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22795                boolean printedHeader = false;
22796                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22797                while (it.hasNext()) {
22798                    String libName = it.next();
22799                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22800                    if (versionedLib == null) {
22801                        continue;
22802                    }
22803                    final int versionCount = versionedLib.size();
22804                    for (int i = 0; i < versionCount; i++) {
22805                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22806                        if (!checkin) {
22807                            if (!printedHeader) {
22808                                if (dumpState.onTitlePrinted())
22809                                    pw.println();
22810                                pw.println("Libraries:");
22811                                printedHeader = true;
22812                            }
22813                            pw.print("  ");
22814                        } else {
22815                            pw.print("lib,");
22816                        }
22817                        pw.print(libEntry.info.getName());
22818                        if (libEntry.info.isStatic()) {
22819                            pw.print(" version=" + libEntry.info.getVersion());
22820                        }
22821                        if (!checkin) {
22822                            pw.print(" -> ");
22823                        }
22824                        if (libEntry.path != null) {
22825                            pw.print(" (jar) ");
22826                            pw.print(libEntry.path);
22827                        } else {
22828                            pw.print(" (apk) ");
22829                            pw.print(libEntry.apk);
22830                        }
22831                        pw.println();
22832                    }
22833                }
22834            }
22835
22836            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22837                if (dumpState.onTitlePrinted())
22838                    pw.println();
22839                if (!checkin) {
22840                    pw.println("Features:");
22841                }
22842
22843                synchronized (mAvailableFeatures) {
22844                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22845                        if (checkin) {
22846                            pw.print("feat,");
22847                            pw.print(feat.name);
22848                            pw.print(",");
22849                            pw.println(feat.version);
22850                        } else {
22851                            pw.print("  ");
22852                            pw.print(feat.name);
22853                            if (feat.version > 0) {
22854                                pw.print(" version=");
22855                                pw.print(feat.version);
22856                            }
22857                            pw.println();
22858                        }
22859                    }
22860                }
22861            }
22862
22863            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22864                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22865                        : "Activity Resolver Table:", "  ", packageName,
22866                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22867                    dumpState.setTitlePrinted(true);
22868                }
22869            }
22870            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22871                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22872                        : "Receiver Resolver Table:", "  ", packageName,
22873                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22874                    dumpState.setTitlePrinted(true);
22875                }
22876            }
22877            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22878                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22879                        : "Service Resolver Table:", "  ", packageName,
22880                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22881                    dumpState.setTitlePrinted(true);
22882                }
22883            }
22884            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22885                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22886                        : "Provider Resolver Table:", "  ", packageName,
22887                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22888                    dumpState.setTitlePrinted(true);
22889                }
22890            }
22891
22892            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22893                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22894                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22895                    int user = mSettings.mPreferredActivities.keyAt(i);
22896                    if (pir.dump(pw,
22897                            dumpState.getTitlePrinted()
22898                                ? "\nPreferred Activities User " + user + ":"
22899                                : "Preferred Activities User " + user + ":", "  ",
22900                            packageName, true, false)) {
22901                        dumpState.setTitlePrinted(true);
22902                    }
22903                }
22904            }
22905
22906            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22907                pw.flush();
22908                FileOutputStream fout = new FileOutputStream(fd);
22909                BufferedOutputStream str = new BufferedOutputStream(fout);
22910                XmlSerializer serializer = new FastXmlSerializer();
22911                try {
22912                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22913                    serializer.startDocument(null, true);
22914                    serializer.setFeature(
22915                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22916                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22917                    serializer.endDocument();
22918                    serializer.flush();
22919                } catch (IllegalArgumentException e) {
22920                    pw.println("Failed writing: " + e);
22921                } catch (IllegalStateException e) {
22922                    pw.println("Failed writing: " + e);
22923                } catch (IOException e) {
22924                    pw.println("Failed writing: " + e);
22925                }
22926            }
22927
22928            if (!checkin
22929                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22930                    && packageName == null) {
22931                pw.println();
22932                int count = mSettings.mPackages.size();
22933                if (count == 0) {
22934                    pw.println("No applications!");
22935                    pw.println();
22936                } else {
22937                    final String prefix = "  ";
22938                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22939                    if (allPackageSettings.size() == 0) {
22940                        pw.println("No domain preferred apps!");
22941                        pw.println();
22942                    } else {
22943                        pw.println("App verification status:");
22944                        pw.println();
22945                        count = 0;
22946                        for (PackageSetting ps : allPackageSettings) {
22947                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22948                            if (ivi == null || ivi.getPackageName() == null) continue;
22949                            pw.println(prefix + "Package: " + ivi.getPackageName());
22950                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22951                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22952                            pw.println();
22953                            count++;
22954                        }
22955                        if (count == 0) {
22956                            pw.println(prefix + "No app verification established.");
22957                            pw.println();
22958                        }
22959                        for (int userId : sUserManager.getUserIds()) {
22960                            pw.println("App linkages for user " + userId + ":");
22961                            pw.println();
22962                            count = 0;
22963                            for (PackageSetting ps : allPackageSettings) {
22964                                final long status = ps.getDomainVerificationStatusForUser(userId);
22965                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22966                                        && !DEBUG_DOMAIN_VERIFICATION) {
22967                                    continue;
22968                                }
22969                                pw.println(prefix + "Package: " + ps.name);
22970                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22971                                String statusStr = IntentFilterVerificationInfo.
22972                                        getStatusStringFromValue(status);
22973                                pw.println(prefix + "Status:  " + statusStr);
22974                                pw.println();
22975                                count++;
22976                            }
22977                            if (count == 0) {
22978                                pw.println(prefix + "No configured app linkages.");
22979                                pw.println();
22980                            }
22981                        }
22982                    }
22983                }
22984            }
22985
22986            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22987                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22988                if (packageName == null && permissionNames == null) {
22989                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22990                        if (iperm == 0) {
22991                            if (dumpState.onTitlePrinted())
22992                                pw.println();
22993                            pw.println("AppOp Permissions:");
22994                        }
22995                        pw.print("  AppOp Permission ");
22996                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22997                        pw.println(":");
22998                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22999                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
23000                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
23001                        }
23002                    }
23003                }
23004            }
23005
23006            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
23007                boolean printedSomething = false;
23008                for (PackageParser.Provider p : mProviders.mProviders.values()) {
23009                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23010                        continue;
23011                    }
23012                    if (!printedSomething) {
23013                        if (dumpState.onTitlePrinted())
23014                            pw.println();
23015                        pw.println("Registered ContentProviders:");
23016                        printedSomething = true;
23017                    }
23018                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
23019                    pw.print("    "); pw.println(p.toString());
23020                }
23021                printedSomething = false;
23022                for (Map.Entry<String, PackageParser.Provider> entry :
23023                        mProvidersByAuthority.entrySet()) {
23024                    PackageParser.Provider p = entry.getValue();
23025                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23026                        continue;
23027                    }
23028                    if (!printedSomething) {
23029                        if (dumpState.onTitlePrinted())
23030                            pw.println();
23031                        pw.println("ContentProvider Authorities:");
23032                        printedSomething = true;
23033                    }
23034                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
23035                    pw.print("    "); pw.println(p.toString());
23036                    if (p.info != null && p.info.applicationInfo != null) {
23037                        final String appInfo = p.info.applicationInfo.toString();
23038                        pw.print("      applicationInfo="); pw.println(appInfo);
23039                    }
23040                }
23041            }
23042
23043            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
23044                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
23045            }
23046
23047            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
23048                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
23049            }
23050
23051            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
23052                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
23053            }
23054
23055            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23056                if (dumpState.onTitlePrinted()) pw.println();
23057                pw.println("Package Changes:");
23058                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23059                final int K = mChangedPackages.size();
23060                for (int i = 0; i < K; i++) {
23061                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
23062                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23063                    final int N = changes.size();
23064                    if (N == 0) {
23065                        pw.print("    "); pw.println("No packages changed");
23066                    } else {
23067                        for (int j = 0; j < N; j++) {
23068                            final String pkgName = changes.valueAt(j);
23069                            final int sequenceNumber = changes.keyAt(j);
23070                            pw.print("    ");
23071                            pw.print("seq=");
23072                            pw.print(sequenceNumber);
23073                            pw.print(", package=");
23074                            pw.println(pkgName);
23075                        }
23076                    }
23077                }
23078            }
23079
23080            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23081                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23082            }
23083
23084            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23085                // XXX should handle packageName != null by dumping only install data that
23086                // the given package is involved with.
23087                if (dumpState.onTitlePrinted()) pw.println();
23088
23089                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23090                ipw.println();
23091                ipw.println("Frozen packages:");
23092                ipw.increaseIndent();
23093                if (mFrozenPackages.size() == 0) {
23094                    ipw.println("(none)");
23095                } else {
23096                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23097                        ipw.println(mFrozenPackages.valueAt(i));
23098                    }
23099                }
23100                ipw.decreaseIndent();
23101            }
23102
23103            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23104                if (dumpState.onTitlePrinted()) pw.println();
23105
23106                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23107                ipw.println();
23108                ipw.println("Loaded volumes:");
23109                ipw.increaseIndent();
23110                if (mLoadedVolumes.size() == 0) {
23111                    ipw.println("(none)");
23112                } else {
23113                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23114                        ipw.println(mLoadedVolumes.valueAt(i));
23115                    }
23116                }
23117                ipw.decreaseIndent();
23118            }
23119
23120            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23121                if (dumpState.onTitlePrinted()) pw.println();
23122                dumpDexoptStateLPr(pw, packageName);
23123            }
23124
23125            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23126                if (dumpState.onTitlePrinted()) pw.println();
23127                dumpCompilerStatsLPr(pw, packageName);
23128            }
23129
23130            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23131                if (dumpState.onTitlePrinted()) pw.println();
23132                mSettings.dumpReadMessagesLPr(pw, dumpState);
23133
23134                pw.println();
23135                pw.println("Package warning messages:");
23136                BufferedReader in = null;
23137                String line = null;
23138                try {
23139                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23140                    while ((line = in.readLine()) != null) {
23141                        if (line.contains("ignored: updated version")) continue;
23142                        pw.println(line);
23143                    }
23144                } catch (IOException ignored) {
23145                } finally {
23146                    IoUtils.closeQuietly(in);
23147                }
23148            }
23149
23150            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23151                BufferedReader in = null;
23152                String line = null;
23153                try {
23154                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23155                    while ((line = in.readLine()) != null) {
23156                        if (line.contains("ignored: updated version")) continue;
23157                        pw.print("msg,");
23158                        pw.println(line);
23159                    }
23160                } catch (IOException ignored) {
23161                } finally {
23162                    IoUtils.closeQuietly(in);
23163                }
23164            }
23165        }
23166
23167        // PackageInstaller should be called outside of mPackages lock
23168        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23169            // XXX should handle packageName != null by dumping only install data that
23170            // the given package is involved with.
23171            if (dumpState.onTitlePrinted()) pw.println();
23172            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23173        }
23174    }
23175
23176    private void dumpProto(FileDescriptor fd) {
23177        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23178
23179        synchronized (mPackages) {
23180            final long requiredVerifierPackageToken =
23181                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23182            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23183            proto.write(
23184                    PackageServiceDumpProto.PackageShortProto.UID,
23185                    getPackageUid(
23186                            mRequiredVerifierPackage,
23187                            MATCH_DEBUG_TRIAGED_MISSING,
23188                            UserHandle.USER_SYSTEM));
23189            proto.end(requiredVerifierPackageToken);
23190
23191            if (mIntentFilterVerifierComponent != null) {
23192                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23193                final long verifierPackageToken =
23194                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23195                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23196                proto.write(
23197                        PackageServiceDumpProto.PackageShortProto.UID,
23198                        getPackageUid(
23199                                verifierPackageName,
23200                                MATCH_DEBUG_TRIAGED_MISSING,
23201                                UserHandle.USER_SYSTEM));
23202                proto.end(verifierPackageToken);
23203            }
23204
23205            dumpSharedLibrariesProto(proto);
23206            dumpFeaturesProto(proto);
23207            mSettings.dumpPackagesProto(proto);
23208            mSettings.dumpSharedUsersProto(proto);
23209            dumpMessagesProto(proto);
23210        }
23211        proto.flush();
23212    }
23213
23214    private void dumpMessagesProto(ProtoOutputStream proto) {
23215        BufferedReader in = null;
23216        String line = null;
23217        try {
23218            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23219            while ((line = in.readLine()) != null) {
23220                if (line.contains("ignored: updated version")) continue;
23221                proto.write(PackageServiceDumpProto.MESSAGES, line);
23222            }
23223        } catch (IOException ignored) {
23224        } finally {
23225            IoUtils.closeQuietly(in);
23226        }
23227    }
23228
23229    private void dumpFeaturesProto(ProtoOutputStream proto) {
23230        synchronized (mAvailableFeatures) {
23231            final int count = mAvailableFeatures.size();
23232            for (int i = 0; i < count; i++) {
23233                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23234                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23235                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23236                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23237                proto.end(featureToken);
23238            }
23239        }
23240    }
23241
23242    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23243        final int count = mSharedLibraries.size();
23244        for (int i = 0; i < count; i++) {
23245            final String libName = mSharedLibraries.keyAt(i);
23246            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23247            if (versionedLib == null) {
23248                continue;
23249            }
23250            final int versionCount = versionedLib.size();
23251            for (int j = 0; j < versionCount; j++) {
23252                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23253                final long sharedLibraryToken =
23254                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23255                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23256                final boolean isJar = (libEntry.path != null);
23257                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23258                if (isJar) {
23259                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23260                } else {
23261                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23262                }
23263                proto.end(sharedLibraryToken);
23264            }
23265        }
23266    }
23267
23268    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23269        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23270        ipw.println();
23271        ipw.println("Dexopt state:");
23272        ipw.increaseIndent();
23273        Collection<PackageParser.Package> packages = null;
23274        if (packageName != null) {
23275            PackageParser.Package targetPackage = mPackages.get(packageName);
23276            if (targetPackage != null) {
23277                packages = Collections.singletonList(targetPackage);
23278            } else {
23279                ipw.println("Unable to find package: " + packageName);
23280                return;
23281            }
23282        } else {
23283            packages = mPackages.values();
23284        }
23285
23286        for (PackageParser.Package pkg : packages) {
23287            ipw.println("[" + pkg.packageName + "]");
23288            ipw.increaseIndent();
23289            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23290                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23291            ipw.decreaseIndent();
23292        }
23293    }
23294
23295    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23296        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23297        ipw.println();
23298        ipw.println("Compiler stats:");
23299        ipw.increaseIndent();
23300        Collection<PackageParser.Package> packages = null;
23301        if (packageName != null) {
23302            PackageParser.Package targetPackage = mPackages.get(packageName);
23303            if (targetPackage != null) {
23304                packages = Collections.singletonList(targetPackage);
23305            } else {
23306                ipw.println("Unable to find package: " + packageName);
23307                return;
23308            }
23309        } else {
23310            packages = mPackages.values();
23311        }
23312
23313        for (PackageParser.Package pkg : packages) {
23314            ipw.println("[" + pkg.packageName + "]");
23315            ipw.increaseIndent();
23316
23317            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23318            if (stats == null) {
23319                ipw.println("(No recorded stats)");
23320            } else {
23321                stats.dump(ipw);
23322            }
23323            ipw.decreaseIndent();
23324        }
23325    }
23326
23327    private String dumpDomainString(String packageName) {
23328        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23329                .getList();
23330        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23331
23332        ArraySet<String> result = new ArraySet<>();
23333        if (iviList.size() > 0) {
23334            for (IntentFilterVerificationInfo ivi : iviList) {
23335                for (String host : ivi.getDomains()) {
23336                    result.add(host);
23337                }
23338            }
23339        }
23340        if (filters != null && filters.size() > 0) {
23341            for (IntentFilter filter : filters) {
23342                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23343                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23344                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23345                    result.addAll(filter.getHostsList());
23346                }
23347            }
23348        }
23349
23350        StringBuilder sb = new StringBuilder(result.size() * 16);
23351        for (String domain : result) {
23352            if (sb.length() > 0) sb.append(" ");
23353            sb.append(domain);
23354        }
23355        return sb.toString();
23356    }
23357
23358    // ------- apps on sdcard specific code -------
23359    static final boolean DEBUG_SD_INSTALL = false;
23360
23361    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23362
23363    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23364
23365    private boolean mMediaMounted = false;
23366
23367    static String getEncryptKey() {
23368        try {
23369            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23370                    SD_ENCRYPTION_KEYSTORE_NAME);
23371            if (sdEncKey == null) {
23372                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23373                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23374                if (sdEncKey == null) {
23375                    Slog.e(TAG, "Failed to create encryption keys");
23376                    return null;
23377                }
23378            }
23379            return sdEncKey;
23380        } catch (NoSuchAlgorithmException nsae) {
23381            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23382            return null;
23383        } catch (IOException ioe) {
23384            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23385            return null;
23386        }
23387    }
23388
23389    /*
23390     * Update media status on PackageManager.
23391     */
23392    @Override
23393    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23394        enforceSystemOrRoot("Media status can only be updated by the system");
23395        // reader; this apparently protects mMediaMounted, but should probably
23396        // be a different lock in that case.
23397        synchronized (mPackages) {
23398            Log.i(TAG, "Updating external media status from "
23399                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23400                    + (mediaStatus ? "mounted" : "unmounted"));
23401            if (DEBUG_SD_INSTALL)
23402                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23403                        + ", mMediaMounted=" + mMediaMounted);
23404            if (mediaStatus == mMediaMounted) {
23405                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23406                        : 0, -1);
23407                mHandler.sendMessage(msg);
23408                return;
23409            }
23410            mMediaMounted = mediaStatus;
23411        }
23412        // Queue up an async operation since the package installation may take a
23413        // little while.
23414        mHandler.post(new Runnable() {
23415            public void run() {
23416                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23417            }
23418        });
23419    }
23420
23421    /**
23422     * Called by StorageManagerService when the initial ASECs to scan are available.
23423     * Should block until all the ASEC containers are finished being scanned.
23424     */
23425    public void scanAvailableAsecs() {
23426        updateExternalMediaStatusInner(true, false, false);
23427    }
23428
23429    /*
23430     * Collect information of applications on external media, map them against
23431     * existing containers and update information based on current mount status.
23432     * Please note that we always have to report status if reportStatus has been
23433     * set to true especially when unloading packages.
23434     */
23435    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23436            boolean externalStorage) {
23437        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23438        int[] uidArr = EmptyArray.INT;
23439
23440        final String[] list = PackageHelper.getSecureContainerList();
23441        if (ArrayUtils.isEmpty(list)) {
23442            Log.i(TAG, "No secure containers found");
23443        } else {
23444            // Process list of secure containers and categorize them
23445            // as active or stale based on their package internal state.
23446
23447            // reader
23448            synchronized (mPackages) {
23449                for (String cid : list) {
23450                    // Leave stages untouched for now; installer service owns them
23451                    if (PackageInstallerService.isStageName(cid)) continue;
23452
23453                    if (DEBUG_SD_INSTALL)
23454                        Log.i(TAG, "Processing container " + cid);
23455                    String pkgName = getAsecPackageName(cid);
23456                    if (pkgName == null) {
23457                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23458                        continue;
23459                    }
23460                    if (DEBUG_SD_INSTALL)
23461                        Log.i(TAG, "Looking for pkg : " + pkgName);
23462
23463                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23464                    if (ps == null) {
23465                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23466                        continue;
23467                    }
23468
23469                    /*
23470                     * Skip packages that are not external if we're unmounting
23471                     * external storage.
23472                     */
23473                    if (externalStorage && !isMounted && !isExternal(ps)) {
23474                        continue;
23475                    }
23476
23477                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23478                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23479                    // The package status is changed only if the code path
23480                    // matches between settings and the container id.
23481                    if (ps.codePathString != null
23482                            && ps.codePathString.startsWith(args.getCodePath())) {
23483                        if (DEBUG_SD_INSTALL) {
23484                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23485                                    + " at code path: " + ps.codePathString);
23486                        }
23487
23488                        // We do have a valid package installed on sdcard
23489                        processCids.put(args, ps.codePathString);
23490                        final int uid = ps.appId;
23491                        if (uid != -1) {
23492                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23493                        }
23494                    } else {
23495                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23496                                + ps.codePathString);
23497                    }
23498                }
23499            }
23500
23501            Arrays.sort(uidArr);
23502        }
23503
23504        // Process packages with valid entries.
23505        if (isMounted) {
23506            if (DEBUG_SD_INSTALL)
23507                Log.i(TAG, "Loading packages");
23508            loadMediaPackages(processCids, uidArr, externalStorage);
23509            startCleaningPackages();
23510            mInstallerService.onSecureContainersAvailable();
23511        } else {
23512            if (DEBUG_SD_INSTALL)
23513                Log.i(TAG, "Unloading packages");
23514            unloadMediaPackages(processCids, uidArr, reportStatus);
23515        }
23516    }
23517
23518    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23519            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23520        final int size = infos.size();
23521        final String[] packageNames = new String[size];
23522        final int[] packageUids = new int[size];
23523        for (int i = 0; i < size; i++) {
23524            final ApplicationInfo info = infos.get(i);
23525            packageNames[i] = info.packageName;
23526            packageUids[i] = info.uid;
23527        }
23528        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23529                finishedReceiver);
23530    }
23531
23532    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23533            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23534        sendResourcesChangedBroadcast(mediaStatus, replacing,
23535                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23536    }
23537
23538    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23539            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23540        int size = pkgList.length;
23541        if (size > 0) {
23542            // Send broadcasts here
23543            Bundle extras = new Bundle();
23544            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23545            if (uidArr != null) {
23546                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23547            }
23548            if (replacing) {
23549                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23550            }
23551            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23552                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23553            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23554        }
23555    }
23556
23557   /*
23558     * Look at potentially valid container ids from processCids If package
23559     * information doesn't match the one on record or package scanning fails,
23560     * the cid is added to list of removeCids. We currently don't delete stale
23561     * containers.
23562     */
23563    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23564            boolean externalStorage) {
23565        ArrayList<String> pkgList = new ArrayList<String>();
23566        Set<AsecInstallArgs> keys = processCids.keySet();
23567
23568        for (AsecInstallArgs args : keys) {
23569            String codePath = processCids.get(args);
23570            if (DEBUG_SD_INSTALL)
23571                Log.i(TAG, "Loading container : " + args.cid);
23572            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23573            try {
23574                // Make sure there are no container errors first.
23575                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23576                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23577                            + " when installing from sdcard");
23578                    continue;
23579                }
23580                // Check code path here.
23581                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23582                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23583                            + " does not match one in settings " + codePath);
23584                    continue;
23585                }
23586                // Parse package
23587                int parseFlags = mDefParseFlags;
23588                if (args.isExternalAsec()) {
23589                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23590                }
23591                if (args.isFwdLocked()) {
23592                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23593                }
23594
23595                synchronized (mInstallLock) {
23596                    PackageParser.Package pkg = null;
23597                    try {
23598                        // Sadly we don't know the package name yet to freeze it
23599                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23600                                SCAN_IGNORE_FROZEN, 0, null);
23601                    } catch (PackageManagerException e) {
23602                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23603                    }
23604                    // Scan the package
23605                    if (pkg != null) {
23606                        /*
23607                         * TODO why is the lock being held? doPostInstall is
23608                         * called in other places without the lock. This needs
23609                         * to be straightened out.
23610                         */
23611                        // writer
23612                        synchronized (mPackages) {
23613                            retCode = PackageManager.INSTALL_SUCCEEDED;
23614                            pkgList.add(pkg.packageName);
23615                            // Post process args
23616                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23617                                    pkg.applicationInfo.uid);
23618                        }
23619                    } else {
23620                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23621                    }
23622                }
23623
23624            } finally {
23625                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23626                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23627                }
23628            }
23629        }
23630        // writer
23631        synchronized (mPackages) {
23632            // If the platform SDK has changed since the last time we booted,
23633            // we need to re-grant app permission to catch any new ones that
23634            // appear. This is really a hack, and means that apps can in some
23635            // cases get permissions that the user didn't initially explicitly
23636            // allow... it would be nice to have some better way to handle
23637            // this situation.
23638            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23639                    : mSettings.getInternalVersion();
23640            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23641                    : StorageManager.UUID_PRIVATE_INTERNAL;
23642
23643            int updateFlags = UPDATE_PERMISSIONS_ALL;
23644            if (ver.sdkVersion != mSdkVersion) {
23645                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23646                        + mSdkVersion + "; regranting permissions for external");
23647                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23648            }
23649            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23650
23651            // Yay, everything is now upgraded
23652            ver.forceCurrent();
23653
23654            // can downgrade to reader
23655            // Persist settings
23656            mSettings.writeLPr();
23657        }
23658        // Send a broadcast to let everyone know we are done processing
23659        if (pkgList.size() > 0) {
23660            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23661        }
23662    }
23663
23664   /*
23665     * Utility method to unload a list of specified containers
23666     */
23667    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23668        // Just unmount all valid containers.
23669        for (AsecInstallArgs arg : cidArgs) {
23670            synchronized (mInstallLock) {
23671                arg.doPostDeleteLI(false);
23672           }
23673       }
23674   }
23675
23676    /*
23677     * Unload packages mounted on external media. This involves deleting package
23678     * data from internal structures, sending broadcasts about disabled packages,
23679     * gc'ing to free up references, unmounting all secure containers
23680     * corresponding to packages on external media, and posting a
23681     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23682     * that we always have to post this message if status has been requested no
23683     * matter what.
23684     */
23685    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23686            final boolean reportStatus) {
23687        if (DEBUG_SD_INSTALL)
23688            Log.i(TAG, "unloading media packages");
23689        ArrayList<String> pkgList = new ArrayList<String>();
23690        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23691        final Set<AsecInstallArgs> keys = processCids.keySet();
23692        for (AsecInstallArgs args : keys) {
23693            String pkgName = args.getPackageName();
23694            if (DEBUG_SD_INSTALL)
23695                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23696            // Delete package internally
23697            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23698            synchronized (mInstallLock) {
23699                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23700                final boolean res;
23701                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23702                        "unloadMediaPackages")) {
23703                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23704                            null);
23705                }
23706                if (res) {
23707                    pkgList.add(pkgName);
23708                } else {
23709                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23710                    failedList.add(args);
23711                }
23712            }
23713        }
23714
23715        // reader
23716        synchronized (mPackages) {
23717            // We didn't update the settings after removing each package;
23718            // write them now for all packages.
23719            mSettings.writeLPr();
23720        }
23721
23722        // We have to absolutely send UPDATED_MEDIA_STATUS only
23723        // after confirming that all the receivers processed the ordered
23724        // broadcast when packages get disabled, force a gc to clean things up.
23725        // and unload all the containers.
23726        if (pkgList.size() > 0) {
23727            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23728                    new IIntentReceiver.Stub() {
23729                public void performReceive(Intent intent, int resultCode, String data,
23730                        Bundle extras, boolean ordered, boolean sticky,
23731                        int sendingUser) throws RemoteException {
23732                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23733                            reportStatus ? 1 : 0, 1, keys);
23734                    mHandler.sendMessage(msg);
23735                }
23736            });
23737        } else {
23738            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23739                    keys);
23740            mHandler.sendMessage(msg);
23741        }
23742    }
23743
23744    private void loadPrivatePackages(final VolumeInfo vol) {
23745        mHandler.post(new Runnable() {
23746            @Override
23747            public void run() {
23748                loadPrivatePackagesInner(vol);
23749            }
23750        });
23751    }
23752
23753    private void loadPrivatePackagesInner(VolumeInfo vol) {
23754        final String volumeUuid = vol.fsUuid;
23755        if (TextUtils.isEmpty(volumeUuid)) {
23756            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23757            return;
23758        }
23759
23760        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23761        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23762        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23763
23764        final VersionInfo ver;
23765        final List<PackageSetting> packages;
23766        synchronized (mPackages) {
23767            ver = mSettings.findOrCreateVersion(volumeUuid);
23768            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23769        }
23770
23771        for (PackageSetting ps : packages) {
23772            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23773            synchronized (mInstallLock) {
23774                final PackageParser.Package pkg;
23775                try {
23776                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23777                    loaded.add(pkg.applicationInfo);
23778
23779                } catch (PackageManagerException e) {
23780                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23781                }
23782
23783                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23784                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23785                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23786                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23787                }
23788            }
23789        }
23790
23791        // Reconcile app data for all started/unlocked users
23792        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23793        final UserManager um = mContext.getSystemService(UserManager.class);
23794        UserManagerInternal umInternal = getUserManagerInternal();
23795        for (UserInfo user : um.getUsers()) {
23796            final int flags;
23797            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23798                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23799            } else if (umInternal.isUserRunning(user.id)) {
23800                flags = StorageManager.FLAG_STORAGE_DE;
23801            } else {
23802                continue;
23803            }
23804
23805            try {
23806                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23807                synchronized (mInstallLock) {
23808                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23809                }
23810            } catch (IllegalStateException e) {
23811                // Device was probably ejected, and we'll process that event momentarily
23812                Slog.w(TAG, "Failed to prepare storage: " + e);
23813            }
23814        }
23815
23816        synchronized (mPackages) {
23817            int updateFlags = UPDATE_PERMISSIONS_ALL;
23818            if (ver.sdkVersion != mSdkVersion) {
23819                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23820                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23821                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23822            }
23823            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23824
23825            // Yay, everything is now upgraded
23826            ver.forceCurrent();
23827
23828            mSettings.writeLPr();
23829        }
23830
23831        for (PackageFreezer freezer : freezers) {
23832            freezer.close();
23833        }
23834
23835        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23836        sendResourcesChangedBroadcast(true, false, loaded, null);
23837        mLoadedVolumes.add(vol.getId());
23838    }
23839
23840    private void unloadPrivatePackages(final VolumeInfo vol) {
23841        mHandler.post(new Runnable() {
23842            @Override
23843            public void run() {
23844                unloadPrivatePackagesInner(vol);
23845            }
23846        });
23847    }
23848
23849    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23850        final String volumeUuid = vol.fsUuid;
23851        if (TextUtils.isEmpty(volumeUuid)) {
23852            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23853            return;
23854        }
23855
23856        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23857        synchronized (mInstallLock) {
23858        synchronized (mPackages) {
23859            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23860            for (PackageSetting ps : packages) {
23861                if (ps.pkg == null) continue;
23862
23863                final ApplicationInfo info = ps.pkg.applicationInfo;
23864                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23865                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23866
23867                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23868                        "unloadPrivatePackagesInner")) {
23869                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23870                            false, null)) {
23871                        unloaded.add(info);
23872                    } else {
23873                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23874                    }
23875                }
23876
23877                // Try very hard to release any references to this package
23878                // so we don't risk the system server being killed due to
23879                // open FDs
23880                AttributeCache.instance().removePackage(ps.name);
23881            }
23882
23883            mSettings.writeLPr();
23884        }
23885        }
23886
23887        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23888        sendResourcesChangedBroadcast(false, false, unloaded, null);
23889        mLoadedVolumes.remove(vol.getId());
23890
23891        // Try very hard to release any references to this path so we don't risk
23892        // the system server being killed due to open FDs
23893        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23894
23895        for (int i = 0; i < 3; i++) {
23896            System.gc();
23897            System.runFinalization();
23898        }
23899    }
23900
23901    private void assertPackageKnown(String volumeUuid, String packageName)
23902            throws PackageManagerException {
23903        synchronized (mPackages) {
23904            // Normalize package name to handle renamed packages
23905            packageName = normalizePackageNameLPr(packageName);
23906
23907            final PackageSetting ps = mSettings.mPackages.get(packageName);
23908            if (ps == null) {
23909                throw new PackageManagerException("Package " + packageName + " is unknown");
23910            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23911                throw new PackageManagerException(
23912                        "Package " + packageName + " found on unknown volume " + volumeUuid
23913                                + "; expected volume " + ps.volumeUuid);
23914            }
23915        }
23916    }
23917
23918    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23919            throws PackageManagerException {
23920        synchronized (mPackages) {
23921            // Normalize package name to handle renamed packages
23922            packageName = normalizePackageNameLPr(packageName);
23923
23924            final PackageSetting ps = mSettings.mPackages.get(packageName);
23925            if (ps == null) {
23926                throw new PackageManagerException("Package " + packageName + " is unknown");
23927            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23928                throw new PackageManagerException(
23929                        "Package " + packageName + " found on unknown volume " + volumeUuid
23930                                + "; expected volume " + ps.volumeUuid);
23931            } else if (!ps.getInstalled(userId)) {
23932                throw new PackageManagerException(
23933                        "Package " + packageName + " not installed for user " + userId);
23934            }
23935        }
23936    }
23937
23938    private List<String> collectAbsoluteCodePaths() {
23939        synchronized (mPackages) {
23940            List<String> codePaths = new ArrayList<>();
23941            final int packageCount = mSettings.mPackages.size();
23942            for (int i = 0; i < packageCount; i++) {
23943                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23944                codePaths.add(ps.codePath.getAbsolutePath());
23945            }
23946            return codePaths;
23947        }
23948    }
23949
23950    /**
23951     * Examine all apps present on given mounted volume, and destroy apps that
23952     * aren't expected, either due to uninstallation or reinstallation on
23953     * another volume.
23954     */
23955    private void reconcileApps(String volumeUuid) {
23956        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23957        List<File> filesToDelete = null;
23958
23959        final File[] files = FileUtils.listFilesOrEmpty(
23960                Environment.getDataAppDirectory(volumeUuid));
23961        for (File file : files) {
23962            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23963                    && !PackageInstallerService.isStageName(file.getName());
23964            if (!isPackage) {
23965                // Ignore entries which are not packages
23966                continue;
23967            }
23968
23969            String absolutePath = file.getAbsolutePath();
23970
23971            boolean pathValid = false;
23972            final int absoluteCodePathCount = absoluteCodePaths.size();
23973            for (int i = 0; i < absoluteCodePathCount; i++) {
23974                String absoluteCodePath = absoluteCodePaths.get(i);
23975                if (absolutePath.startsWith(absoluteCodePath)) {
23976                    pathValid = true;
23977                    break;
23978                }
23979            }
23980
23981            if (!pathValid) {
23982                if (filesToDelete == null) {
23983                    filesToDelete = new ArrayList<>();
23984                }
23985                filesToDelete.add(file);
23986            }
23987        }
23988
23989        if (filesToDelete != null) {
23990            final int fileToDeleteCount = filesToDelete.size();
23991            for (int i = 0; i < fileToDeleteCount; i++) {
23992                File fileToDelete = filesToDelete.get(i);
23993                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23994                synchronized (mInstallLock) {
23995                    removeCodePathLI(fileToDelete);
23996                }
23997            }
23998        }
23999    }
24000
24001    /**
24002     * Reconcile all app data for the given user.
24003     * <p>
24004     * Verifies that directories exist and that ownership and labeling is
24005     * correct for all installed apps on all mounted volumes.
24006     */
24007    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
24008        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24009        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
24010            final String volumeUuid = vol.getFsUuid();
24011            synchronized (mInstallLock) {
24012                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
24013            }
24014        }
24015    }
24016
24017    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24018            boolean migrateAppData) {
24019        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
24020    }
24021
24022    /**
24023     * Reconcile all app data on given mounted volume.
24024     * <p>
24025     * Destroys app data that isn't expected, either due to uninstallation or
24026     * reinstallation on another volume.
24027     * <p>
24028     * Verifies that directories exist and that ownership and labeling is
24029     * correct for all installed apps.
24030     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
24031     */
24032    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24033            boolean migrateAppData, boolean onlyCoreApps) {
24034        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
24035                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
24036        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
24037
24038        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
24039        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
24040
24041        // First look for stale data that doesn't belong, and check if things
24042        // have changed since we did our last restorecon
24043        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24044            if (StorageManager.isFileEncryptedNativeOrEmulated()
24045                    && !StorageManager.isUserKeyUnlocked(userId)) {
24046                throw new RuntimeException(
24047                        "Yikes, someone asked us to reconcile CE storage while " + userId
24048                                + " was still locked; this would have caused massive data loss!");
24049            }
24050
24051            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
24052            for (File file : files) {
24053                final String packageName = file.getName();
24054                try {
24055                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24056                } catch (PackageManagerException e) {
24057                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24058                    try {
24059                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24060                                StorageManager.FLAG_STORAGE_CE, 0);
24061                    } catch (InstallerException e2) {
24062                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24063                    }
24064                }
24065            }
24066        }
24067        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24068            final File[] files = FileUtils.listFilesOrEmpty(deDir);
24069            for (File file : files) {
24070                final String packageName = file.getName();
24071                try {
24072                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24073                } catch (PackageManagerException e) {
24074                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24075                    try {
24076                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24077                                StorageManager.FLAG_STORAGE_DE, 0);
24078                    } catch (InstallerException e2) {
24079                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24080                    }
24081                }
24082            }
24083        }
24084
24085        // Ensure that data directories are ready to roll for all packages
24086        // installed for this volume and user
24087        final List<PackageSetting> packages;
24088        synchronized (mPackages) {
24089            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24090        }
24091        int preparedCount = 0;
24092        for (PackageSetting ps : packages) {
24093            final String packageName = ps.name;
24094            if (ps.pkg == null) {
24095                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24096                // TODO: might be due to legacy ASEC apps; we should circle back
24097                // and reconcile again once they're scanned
24098                continue;
24099            }
24100            // Skip non-core apps if requested
24101            if (onlyCoreApps && !ps.pkg.coreApp) {
24102                result.add(packageName);
24103                continue;
24104            }
24105
24106            if (ps.getInstalled(userId)) {
24107                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24108                preparedCount++;
24109            }
24110        }
24111
24112        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24113        return result;
24114    }
24115
24116    /**
24117     * Prepare app data for the given app just after it was installed or
24118     * upgraded. This method carefully only touches users that it's installed
24119     * for, and it forces a restorecon to handle any seinfo changes.
24120     * <p>
24121     * Verifies that directories exist and that ownership and labeling is
24122     * correct for all installed apps. If there is an ownership mismatch, it
24123     * will try recovering system apps by wiping data; third-party app data is
24124     * left intact.
24125     * <p>
24126     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24127     */
24128    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24129        final PackageSetting ps;
24130        synchronized (mPackages) {
24131            ps = mSettings.mPackages.get(pkg.packageName);
24132            mSettings.writeKernelMappingLPr(ps);
24133        }
24134
24135        final UserManager um = mContext.getSystemService(UserManager.class);
24136        UserManagerInternal umInternal = getUserManagerInternal();
24137        for (UserInfo user : um.getUsers()) {
24138            final int flags;
24139            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24140                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24141            } else if (umInternal.isUserRunning(user.id)) {
24142                flags = StorageManager.FLAG_STORAGE_DE;
24143            } else {
24144                continue;
24145            }
24146
24147            if (ps.getInstalled(user.id)) {
24148                // TODO: when user data is locked, mark that we're still dirty
24149                prepareAppDataLIF(pkg, user.id, flags);
24150            }
24151        }
24152    }
24153
24154    /**
24155     * Prepare app data for the given app.
24156     * <p>
24157     * Verifies that directories exist and that ownership and labeling is
24158     * correct for all installed apps. If there is an ownership mismatch, this
24159     * will try recovering system apps by wiping data; third-party app data is
24160     * left intact.
24161     */
24162    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24163        if (pkg == null) {
24164            Slog.wtf(TAG, "Package was null!", new Throwable());
24165            return;
24166        }
24167        prepareAppDataLeafLIF(pkg, userId, flags);
24168        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24169        for (int i = 0; i < childCount; i++) {
24170            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24171        }
24172    }
24173
24174    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24175            boolean maybeMigrateAppData) {
24176        prepareAppDataLIF(pkg, userId, flags);
24177
24178        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24179            // We may have just shuffled around app data directories, so
24180            // prepare them one more time
24181            prepareAppDataLIF(pkg, userId, flags);
24182        }
24183    }
24184
24185    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24186        if (DEBUG_APP_DATA) {
24187            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24188                    + Integer.toHexString(flags));
24189        }
24190
24191        final String volumeUuid = pkg.volumeUuid;
24192        final String packageName = pkg.packageName;
24193        final ApplicationInfo app = pkg.applicationInfo;
24194        final int appId = UserHandle.getAppId(app.uid);
24195
24196        Preconditions.checkNotNull(app.seInfo);
24197
24198        long ceDataInode = -1;
24199        try {
24200            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24201                    appId, app.seInfo, app.targetSdkVersion);
24202        } catch (InstallerException e) {
24203            if (app.isSystemApp()) {
24204                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24205                        + ", but trying to recover: " + e);
24206                destroyAppDataLeafLIF(pkg, userId, flags);
24207                try {
24208                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24209                            appId, app.seInfo, app.targetSdkVersion);
24210                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24211                } catch (InstallerException e2) {
24212                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24213                }
24214            } else {
24215                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24216            }
24217        }
24218
24219        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24220            // TODO: mark this structure as dirty so we persist it!
24221            synchronized (mPackages) {
24222                final PackageSetting ps = mSettings.mPackages.get(packageName);
24223                if (ps != null) {
24224                    ps.setCeDataInode(ceDataInode, userId);
24225                }
24226            }
24227        }
24228
24229        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24230    }
24231
24232    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24233        if (pkg == null) {
24234            Slog.wtf(TAG, "Package was null!", new Throwable());
24235            return;
24236        }
24237        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24238        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24239        for (int i = 0; i < childCount; i++) {
24240            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24241        }
24242    }
24243
24244    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24245        final String volumeUuid = pkg.volumeUuid;
24246        final String packageName = pkg.packageName;
24247        final ApplicationInfo app = pkg.applicationInfo;
24248
24249        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24250            // Create a native library symlink only if we have native libraries
24251            // and if the native libraries are 32 bit libraries. We do not provide
24252            // this symlink for 64 bit libraries.
24253            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24254                final String nativeLibPath = app.nativeLibraryDir;
24255                try {
24256                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24257                            nativeLibPath, userId);
24258                } catch (InstallerException e) {
24259                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24260                }
24261            }
24262        }
24263    }
24264
24265    /**
24266     * For system apps on non-FBE devices, this method migrates any existing
24267     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24268     * requested by the app.
24269     */
24270    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24271        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24272                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24273            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24274                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24275            try {
24276                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24277                        storageTarget);
24278            } catch (InstallerException e) {
24279                logCriticalInfo(Log.WARN,
24280                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24281            }
24282            return true;
24283        } else {
24284            return false;
24285        }
24286    }
24287
24288    public PackageFreezer freezePackage(String packageName, String killReason) {
24289        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24290    }
24291
24292    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24293        return new PackageFreezer(packageName, userId, killReason);
24294    }
24295
24296    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24297            String killReason) {
24298        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24299    }
24300
24301    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24302            String killReason) {
24303        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24304            return new PackageFreezer();
24305        } else {
24306            return freezePackage(packageName, userId, killReason);
24307        }
24308    }
24309
24310    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24311            String killReason) {
24312        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24313    }
24314
24315    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24316            String killReason) {
24317        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24318            return new PackageFreezer();
24319        } else {
24320            return freezePackage(packageName, userId, killReason);
24321        }
24322    }
24323
24324    /**
24325     * Class that freezes and kills the given package upon creation, and
24326     * unfreezes it upon closing. This is typically used when doing surgery on
24327     * app code/data to prevent the app from running while you're working.
24328     */
24329    private class PackageFreezer implements AutoCloseable {
24330        private final String mPackageName;
24331        private final PackageFreezer[] mChildren;
24332
24333        private final boolean mWeFroze;
24334
24335        private final AtomicBoolean mClosed = new AtomicBoolean();
24336        private final CloseGuard mCloseGuard = CloseGuard.get();
24337
24338        /**
24339         * Create and return a stub freezer that doesn't actually do anything,
24340         * typically used when someone requested
24341         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24342         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24343         */
24344        public PackageFreezer() {
24345            mPackageName = null;
24346            mChildren = null;
24347            mWeFroze = false;
24348            mCloseGuard.open("close");
24349        }
24350
24351        public PackageFreezer(String packageName, int userId, String killReason) {
24352            synchronized (mPackages) {
24353                mPackageName = packageName;
24354                mWeFroze = mFrozenPackages.add(mPackageName);
24355
24356                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24357                if (ps != null) {
24358                    killApplication(ps.name, ps.appId, userId, killReason);
24359                }
24360
24361                final PackageParser.Package p = mPackages.get(packageName);
24362                if (p != null && p.childPackages != null) {
24363                    final int N = p.childPackages.size();
24364                    mChildren = new PackageFreezer[N];
24365                    for (int i = 0; i < N; i++) {
24366                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24367                                userId, killReason);
24368                    }
24369                } else {
24370                    mChildren = null;
24371                }
24372            }
24373            mCloseGuard.open("close");
24374        }
24375
24376        @Override
24377        protected void finalize() throws Throwable {
24378            try {
24379                if (mCloseGuard != null) {
24380                    mCloseGuard.warnIfOpen();
24381                }
24382
24383                close();
24384            } finally {
24385                super.finalize();
24386            }
24387        }
24388
24389        @Override
24390        public void close() {
24391            mCloseGuard.close();
24392            if (mClosed.compareAndSet(false, true)) {
24393                synchronized (mPackages) {
24394                    if (mWeFroze) {
24395                        mFrozenPackages.remove(mPackageName);
24396                    }
24397
24398                    if (mChildren != null) {
24399                        for (PackageFreezer freezer : mChildren) {
24400                            freezer.close();
24401                        }
24402                    }
24403                }
24404            }
24405        }
24406    }
24407
24408    /**
24409     * Verify that given package is currently frozen.
24410     */
24411    private void checkPackageFrozen(String packageName) {
24412        synchronized (mPackages) {
24413            if (!mFrozenPackages.contains(packageName)) {
24414                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24415            }
24416        }
24417    }
24418
24419    @Override
24420    public int movePackage(final String packageName, final String volumeUuid) {
24421        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24422
24423        final int callingUid = Binder.getCallingUid();
24424        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24425        final int moveId = mNextMoveId.getAndIncrement();
24426        mHandler.post(new Runnable() {
24427            @Override
24428            public void run() {
24429                try {
24430                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24431                } catch (PackageManagerException e) {
24432                    Slog.w(TAG, "Failed to move " + packageName, e);
24433                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24434                }
24435            }
24436        });
24437        return moveId;
24438    }
24439
24440    private void movePackageInternal(final String packageName, final String volumeUuid,
24441            final int moveId, final int callingUid, UserHandle user)
24442                    throws PackageManagerException {
24443        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24444        final PackageManager pm = mContext.getPackageManager();
24445
24446        final boolean currentAsec;
24447        final String currentVolumeUuid;
24448        final File codeFile;
24449        final String installerPackageName;
24450        final String packageAbiOverride;
24451        final int appId;
24452        final String seinfo;
24453        final String label;
24454        final int targetSdkVersion;
24455        final PackageFreezer freezer;
24456        final int[] installedUserIds;
24457
24458        // reader
24459        synchronized (mPackages) {
24460            final PackageParser.Package pkg = mPackages.get(packageName);
24461            final PackageSetting ps = mSettings.mPackages.get(packageName);
24462            if (pkg == null
24463                    || ps == null
24464                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24465                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24466            }
24467            if (pkg.applicationInfo.isSystemApp()) {
24468                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24469                        "Cannot move system application");
24470            }
24471
24472            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24473            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24474                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24475            if (isInternalStorage && !allow3rdPartyOnInternal) {
24476                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24477                        "3rd party apps are not allowed on internal storage");
24478            }
24479
24480            if (pkg.applicationInfo.isExternalAsec()) {
24481                currentAsec = true;
24482                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24483            } else if (pkg.applicationInfo.isForwardLocked()) {
24484                currentAsec = true;
24485                currentVolumeUuid = "forward_locked";
24486            } else {
24487                currentAsec = false;
24488                currentVolumeUuid = ps.volumeUuid;
24489
24490                final File probe = new File(pkg.codePath);
24491                final File probeOat = new File(probe, "oat");
24492                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24493                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24494                            "Move only supported for modern cluster style installs");
24495                }
24496            }
24497
24498            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24499                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24500                        "Package already moved to " + volumeUuid);
24501            }
24502            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24503                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24504                        "Device admin cannot be moved");
24505            }
24506
24507            if (mFrozenPackages.contains(packageName)) {
24508                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24509                        "Failed to move already frozen package");
24510            }
24511
24512            codeFile = new File(pkg.codePath);
24513            installerPackageName = ps.installerPackageName;
24514            packageAbiOverride = ps.cpuAbiOverrideString;
24515            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24516            seinfo = pkg.applicationInfo.seInfo;
24517            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24518            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24519            freezer = freezePackage(packageName, "movePackageInternal");
24520            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24521        }
24522
24523        final Bundle extras = new Bundle();
24524        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24525        extras.putString(Intent.EXTRA_TITLE, label);
24526        mMoveCallbacks.notifyCreated(moveId, extras);
24527
24528        int installFlags;
24529        final boolean moveCompleteApp;
24530        final File measurePath;
24531
24532        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24533            installFlags = INSTALL_INTERNAL;
24534            moveCompleteApp = !currentAsec;
24535            measurePath = Environment.getDataAppDirectory(volumeUuid);
24536        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24537            installFlags = INSTALL_EXTERNAL;
24538            moveCompleteApp = false;
24539            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24540        } else {
24541            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24542            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24543                    || !volume.isMountedWritable()) {
24544                freezer.close();
24545                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24546                        "Move location not mounted private volume");
24547            }
24548
24549            Preconditions.checkState(!currentAsec);
24550
24551            installFlags = INSTALL_INTERNAL;
24552            moveCompleteApp = true;
24553            measurePath = Environment.getDataAppDirectory(volumeUuid);
24554        }
24555
24556        // If we're moving app data around, we need all the users unlocked
24557        if (moveCompleteApp) {
24558            for (int userId : installedUserIds) {
24559                if (StorageManager.isFileEncryptedNativeOrEmulated()
24560                        && !StorageManager.isUserKeyUnlocked(userId)) {
24561                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24562                            "User " + userId + " must be unlocked");
24563                }
24564            }
24565        }
24566
24567        final PackageStats stats = new PackageStats(null, -1);
24568        synchronized (mInstaller) {
24569            for (int userId : installedUserIds) {
24570                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24571                    freezer.close();
24572                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24573                            "Failed to measure package size");
24574                }
24575            }
24576        }
24577
24578        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24579                + stats.dataSize);
24580
24581        final long startFreeBytes = measurePath.getUsableSpace();
24582        final long sizeBytes;
24583        if (moveCompleteApp) {
24584            sizeBytes = stats.codeSize + stats.dataSize;
24585        } else {
24586            sizeBytes = stats.codeSize;
24587        }
24588
24589        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24590            freezer.close();
24591            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24592                    "Not enough free space to move");
24593        }
24594
24595        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24596
24597        final CountDownLatch installedLatch = new CountDownLatch(1);
24598        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24599            @Override
24600            public void onUserActionRequired(Intent intent) throws RemoteException {
24601                throw new IllegalStateException();
24602            }
24603
24604            @Override
24605            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24606                    Bundle extras) throws RemoteException {
24607                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24608                        + PackageManager.installStatusToString(returnCode, msg));
24609
24610                installedLatch.countDown();
24611                freezer.close();
24612
24613                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24614                switch (status) {
24615                    case PackageInstaller.STATUS_SUCCESS:
24616                        mMoveCallbacks.notifyStatusChanged(moveId,
24617                                PackageManager.MOVE_SUCCEEDED);
24618                        break;
24619                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24620                        mMoveCallbacks.notifyStatusChanged(moveId,
24621                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24622                        break;
24623                    default:
24624                        mMoveCallbacks.notifyStatusChanged(moveId,
24625                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24626                        break;
24627                }
24628            }
24629        };
24630
24631        final MoveInfo move;
24632        if (moveCompleteApp) {
24633            // Kick off a thread to report progress estimates
24634            new Thread() {
24635                @Override
24636                public void run() {
24637                    while (true) {
24638                        try {
24639                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24640                                break;
24641                            }
24642                        } catch (InterruptedException ignored) {
24643                        }
24644
24645                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24646                        final int progress = 10 + (int) MathUtils.constrain(
24647                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24648                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24649                    }
24650                }
24651            }.start();
24652
24653            final String dataAppName = codeFile.getName();
24654            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24655                    dataAppName, appId, seinfo, targetSdkVersion);
24656        } else {
24657            move = null;
24658        }
24659
24660        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24661
24662        final Message msg = mHandler.obtainMessage(INIT_COPY);
24663        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24664        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24665                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24666                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24667                PackageManager.INSTALL_REASON_UNKNOWN);
24668        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24669        msg.obj = params;
24670
24671        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24672                System.identityHashCode(msg.obj));
24673        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24674                System.identityHashCode(msg.obj));
24675
24676        mHandler.sendMessage(msg);
24677    }
24678
24679    @Override
24680    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24681        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24682
24683        final int realMoveId = mNextMoveId.getAndIncrement();
24684        final Bundle extras = new Bundle();
24685        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24686        mMoveCallbacks.notifyCreated(realMoveId, extras);
24687
24688        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24689            @Override
24690            public void onCreated(int moveId, Bundle extras) {
24691                // Ignored
24692            }
24693
24694            @Override
24695            public void onStatusChanged(int moveId, int status, long estMillis) {
24696                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24697            }
24698        };
24699
24700        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24701        storage.setPrimaryStorageUuid(volumeUuid, callback);
24702        return realMoveId;
24703    }
24704
24705    @Override
24706    public int getMoveStatus(int moveId) {
24707        mContext.enforceCallingOrSelfPermission(
24708                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24709        return mMoveCallbacks.mLastStatus.get(moveId);
24710    }
24711
24712    @Override
24713    public void registerMoveCallback(IPackageMoveObserver callback) {
24714        mContext.enforceCallingOrSelfPermission(
24715                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24716        mMoveCallbacks.register(callback);
24717    }
24718
24719    @Override
24720    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24721        mContext.enforceCallingOrSelfPermission(
24722                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24723        mMoveCallbacks.unregister(callback);
24724    }
24725
24726    @Override
24727    public boolean setInstallLocation(int loc) {
24728        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24729                null);
24730        if (getInstallLocation() == loc) {
24731            return true;
24732        }
24733        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24734                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24735            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24736                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24737            return true;
24738        }
24739        return false;
24740   }
24741
24742    @Override
24743    public int getInstallLocation() {
24744        // allow instant app access
24745        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24746                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24747                PackageHelper.APP_INSTALL_AUTO);
24748    }
24749
24750    /** Called by UserManagerService */
24751    void cleanUpUser(UserManagerService userManager, int userHandle) {
24752        synchronized (mPackages) {
24753            mDirtyUsers.remove(userHandle);
24754            mUserNeedsBadging.delete(userHandle);
24755            mSettings.removeUserLPw(userHandle);
24756            mPendingBroadcasts.remove(userHandle);
24757            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24758            removeUnusedPackagesLPw(userManager, userHandle);
24759        }
24760    }
24761
24762    /**
24763     * We're removing userHandle and would like to remove any downloaded packages
24764     * that are no longer in use by any other user.
24765     * @param userHandle the user being removed
24766     */
24767    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24768        final boolean DEBUG_CLEAN_APKS = false;
24769        int [] users = userManager.getUserIds();
24770        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24771        while (psit.hasNext()) {
24772            PackageSetting ps = psit.next();
24773            if (ps.pkg == null) {
24774                continue;
24775            }
24776            final String packageName = ps.pkg.packageName;
24777            // Skip over if system app
24778            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24779                continue;
24780            }
24781            if (DEBUG_CLEAN_APKS) {
24782                Slog.i(TAG, "Checking package " + packageName);
24783            }
24784            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24785            if (keep) {
24786                if (DEBUG_CLEAN_APKS) {
24787                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24788                }
24789            } else {
24790                for (int i = 0; i < users.length; i++) {
24791                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24792                        keep = true;
24793                        if (DEBUG_CLEAN_APKS) {
24794                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24795                                    + users[i]);
24796                        }
24797                        break;
24798                    }
24799                }
24800            }
24801            if (!keep) {
24802                if (DEBUG_CLEAN_APKS) {
24803                    Slog.i(TAG, "  Removing package " + packageName);
24804                }
24805                mHandler.post(new Runnable() {
24806                    public void run() {
24807                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24808                                userHandle, 0);
24809                    } //end run
24810                });
24811            }
24812        }
24813    }
24814
24815    /** Called by UserManagerService */
24816    void createNewUser(int userId, String[] disallowedPackages) {
24817        synchronized (mInstallLock) {
24818            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24819        }
24820        synchronized (mPackages) {
24821            scheduleWritePackageRestrictionsLocked(userId);
24822            scheduleWritePackageListLocked(userId);
24823            applyFactoryDefaultBrowserLPw(userId);
24824            primeDomainVerificationsLPw(userId);
24825        }
24826    }
24827
24828    void onNewUserCreated(final int userId) {
24829        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24830        // If permission review for legacy apps is required, we represent
24831        // dagerous permissions for such apps as always granted runtime
24832        // permissions to keep per user flag state whether review is needed.
24833        // Hence, if a new user is added we have to propagate dangerous
24834        // permission grants for these legacy apps.
24835        if (mPermissionReviewRequired) {
24836            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24837                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24838        }
24839    }
24840
24841    @Override
24842    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24843        mContext.enforceCallingOrSelfPermission(
24844                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24845                "Only package verification agents can read the verifier device identity");
24846
24847        synchronized (mPackages) {
24848            return mSettings.getVerifierDeviceIdentityLPw();
24849        }
24850    }
24851
24852    @Override
24853    public void setPermissionEnforced(String permission, boolean enforced) {
24854        // TODO: Now that we no longer change GID for storage, this should to away.
24855        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24856                "setPermissionEnforced");
24857        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24858            synchronized (mPackages) {
24859                if (mSettings.mReadExternalStorageEnforced == null
24860                        || mSettings.mReadExternalStorageEnforced != enforced) {
24861                    mSettings.mReadExternalStorageEnforced = enforced;
24862                    mSettings.writeLPr();
24863                }
24864            }
24865            // kill any non-foreground processes so we restart them and
24866            // grant/revoke the GID.
24867            final IActivityManager am = ActivityManager.getService();
24868            if (am != null) {
24869                final long token = Binder.clearCallingIdentity();
24870                try {
24871                    am.killProcessesBelowForeground("setPermissionEnforcement");
24872                } catch (RemoteException e) {
24873                } finally {
24874                    Binder.restoreCallingIdentity(token);
24875                }
24876            }
24877        } else {
24878            throw new IllegalArgumentException("No selective enforcement for " + permission);
24879        }
24880    }
24881
24882    @Override
24883    @Deprecated
24884    public boolean isPermissionEnforced(String permission) {
24885        // allow instant applications
24886        return true;
24887    }
24888
24889    @Override
24890    public boolean isStorageLow() {
24891        // allow instant applications
24892        final long token = Binder.clearCallingIdentity();
24893        try {
24894            final DeviceStorageMonitorInternal
24895                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24896            if (dsm != null) {
24897                return dsm.isMemoryLow();
24898            } else {
24899                return false;
24900            }
24901        } finally {
24902            Binder.restoreCallingIdentity(token);
24903        }
24904    }
24905
24906    @Override
24907    public IPackageInstaller getPackageInstaller() {
24908        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24909            return null;
24910        }
24911        return mInstallerService;
24912    }
24913
24914    private boolean userNeedsBadging(int userId) {
24915        int index = mUserNeedsBadging.indexOfKey(userId);
24916        if (index < 0) {
24917            final UserInfo userInfo;
24918            final long token = Binder.clearCallingIdentity();
24919            try {
24920                userInfo = sUserManager.getUserInfo(userId);
24921            } finally {
24922                Binder.restoreCallingIdentity(token);
24923            }
24924            final boolean b;
24925            if (userInfo != null && userInfo.isManagedProfile()) {
24926                b = true;
24927            } else {
24928                b = false;
24929            }
24930            mUserNeedsBadging.put(userId, b);
24931            return b;
24932        }
24933        return mUserNeedsBadging.valueAt(index);
24934    }
24935
24936    @Override
24937    public KeySet getKeySetByAlias(String packageName, String alias) {
24938        if (packageName == null || alias == null) {
24939            return null;
24940        }
24941        synchronized(mPackages) {
24942            final PackageParser.Package pkg = mPackages.get(packageName);
24943            if (pkg == null) {
24944                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24945                throw new IllegalArgumentException("Unknown package: " + packageName);
24946            }
24947            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24948            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24949                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24950                throw new IllegalArgumentException("Unknown package: " + packageName);
24951            }
24952            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24953            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24954        }
24955    }
24956
24957    @Override
24958    public KeySet getSigningKeySet(String packageName) {
24959        if (packageName == null) {
24960            return null;
24961        }
24962        synchronized(mPackages) {
24963            final int callingUid = Binder.getCallingUid();
24964            final int callingUserId = UserHandle.getUserId(callingUid);
24965            final PackageParser.Package pkg = mPackages.get(packageName);
24966            if (pkg == null) {
24967                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24968                throw new IllegalArgumentException("Unknown package: " + packageName);
24969            }
24970            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24971            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24972                // filter and pretend the package doesn't exist
24973                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24974                        + ", uid:" + callingUid);
24975                throw new IllegalArgumentException("Unknown package: " + packageName);
24976            }
24977            if (pkg.applicationInfo.uid != callingUid
24978                    && Process.SYSTEM_UID != callingUid) {
24979                throw new SecurityException("May not access signing KeySet of other apps.");
24980            }
24981            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24982            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24983        }
24984    }
24985
24986    @Override
24987    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24988        final int callingUid = Binder.getCallingUid();
24989        if (getInstantAppPackageName(callingUid) != null) {
24990            return false;
24991        }
24992        if (packageName == null || ks == null) {
24993            return false;
24994        }
24995        synchronized(mPackages) {
24996            final PackageParser.Package pkg = mPackages.get(packageName);
24997            if (pkg == null
24998                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24999                            UserHandle.getUserId(callingUid))) {
25000                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25001                throw new IllegalArgumentException("Unknown package: " + packageName);
25002            }
25003            IBinder ksh = ks.getToken();
25004            if (ksh instanceof KeySetHandle) {
25005                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25006                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
25007            }
25008            return false;
25009        }
25010    }
25011
25012    @Override
25013    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
25014        final int callingUid = Binder.getCallingUid();
25015        if (getInstantAppPackageName(callingUid) != null) {
25016            return false;
25017        }
25018        if (packageName == null || ks == null) {
25019            return false;
25020        }
25021        synchronized(mPackages) {
25022            final PackageParser.Package pkg = mPackages.get(packageName);
25023            if (pkg == null
25024                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25025                            UserHandle.getUserId(callingUid))) {
25026                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25027                throw new IllegalArgumentException("Unknown package: " + packageName);
25028            }
25029            IBinder ksh = ks.getToken();
25030            if (ksh instanceof KeySetHandle) {
25031                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25032                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
25033            }
25034            return false;
25035        }
25036    }
25037
25038    private void deletePackageIfUnusedLPr(final String packageName) {
25039        PackageSetting ps = mSettings.mPackages.get(packageName);
25040        if (ps == null) {
25041            return;
25042        }
25043        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
25044            // TODO Implement atomic delete if package is unused
25045            // It is currently possible that the package will be deleted even if it is installed
25046            // after this method returns.
25047            mHandler.post(new Runnable() {
25048                public void run() {
25049                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
25050                            0, PackageManager.DELETE_ALL_USERS);
25051                }
25052            });
25053        }
25054    }
25055
25056    /**
25057     * Check and throw if the given before/after packages would be considered a
25058     * downgrade.
25059     */
25060    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25061            throws PackageManagerException {
25062        if (after.versionCode < before.mVersionCode) {
25063            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25064                    "Update version code " + after.versionCode + " is older than current "
25065                    + before.mVersionCode);
25066        } else if (after.versionCode == before.mVersionCode) {
25067            if (after.baseRevisionCode < before.baseRevisionCode) {
25068                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25069                        "Update base revision code " + after.baseRevisionCode
25070                        + " is older than current " + before.baseRevisionCode);
25071            }
25072
25073            if (!ArrayUtils.isEmpty(after.splitNames)) {
25074                for (int i = 0; i < after.splitNames.length; i++) {
25075                    final String splitName = after.splitNames[i];
25076                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25077                    if (j != -1) {
25078                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25079                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25080                                    "Update split " + splitName + " revision code "
25081                                    + after.splitRevisionCodes[i] + " is older than current "
25082                                    + before.splitRevisionCodes[j]);
25083                        }
25084                    }
25085                }
25086            }
25087        }
25088    }
25089
25090    private static class MoveCallbacks extends Handler {
25091        private static final int MSG_CREATED = 1;
25092        private static final int MSG_STATUS_CHANGED = 2;
25093
25094        private final RemoteCallbackList<IPackageMoveObserver>
25095                mCallbacks = new RemoteCallbackList<>();
25096
25097        private final SparseIntArray mLastStatus = new SparseIntArray();
25098
25099        public MoveCallbacks(Looper looper) {
25100            super(looper);
25101        }
25102
25103        public void register(IPackageMoveObserver callback) {
25104            mCallbacks.register(callback);
25105        }
25106
25107        public void unregister(IPackageMoveObserver callback) {
25108            mCallbacks.unregister(callback);
25109        }
25110
25111        @Override
25112        public void handleMessage(Message msg) {
25113            final SomeArgs args = (SomeArgs) msg.obj;
25114            final int n = mCallbacks.beginBroadcast();
25115            for (int i = 0; i < n; i++) {
25116                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25117                try {
25118                    invokeCallback(callback, msg.what, args);
25119                } catch (RemoteException ignored) {
25120                }
25121            }
25122            mCallbacks.finishBroadcast();
25123            args.recycle();
25124        }
25125
25126        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25127                throws RemoteException {
25128            switch (what) {
25129                case MSG_CREATED: {
25130                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25131                    break;
25132                }
25133                case MSG_STATUS_CHANGED: {
25134                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25135                    break;
25136                }
25137            }
25138        }
25139
25140        private void notifyCreated(int moveId, Bundle extras) {
25141            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25142
25143            final SomeArgs args = SomeArgs.obtain();
25144            args.argi1 = moveId;
25145            args.arg2 = extras;
25146            obtainMessage(MSG_CREATED, args).sendToTarget();
25147        }
25148
25149        private void notifyStatusChanged(int moveId, int status) {
25150            notifyStatusChanged(moveId, status, -1);
25151        }
25152
25153        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25154            Slog.v(TAG, "Move " + moveId + " status " + status);
25155
25156            final SomeArgs args = SomeArgs.obtain();
25157            args.argi1 = moveId;
25158            args.argi2 = status;
25159            args.arg3 = estMillis;
25160            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25161
25162            synchronized (mLastStatus) {
25163                mLastStatus.put(moveId, status);
25164            }
25165        }
25166    }
25167
25168    private final static class OnPermissionChangeListeners extends Handler {
25169        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25170
25171        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25172                new RemoteCallbackList<>();
25173
25174        public OnPermissionChangeListeners(Looper looper) {
25175            super(looper);
25176        }
25177
25178        @Override
25179        public void handleMessage(Message msg) {
25180            switch (msg.what) {
25181                case MSG_ON_PERMISSIONS_CHANGED: {
25182                    final int uid = msg.arg1;
25183                    handleOnPermissionsChanged(uid);
25184                } break;
25185            }
25186        }
25187
25188        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25189            mPermissionListeners.register(listener);
25190
25191        }
25192
25193        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25194            mPermissionListeners.unregister(listener);
25195        }
25196
25197        public void onPermissionsChanged(int uid) {
25198            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25199                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25200            }
25201        }
25202
25203        private void handleOnPermissionsChanged(int uid) {
25204            final int count = mPermissionListeners.beginBroadcast();
25205            try {
25206                for (int i = 0; i < count; i++) {
25207                    IOnPermissionsChangeListener callback = mPermissionListeners
25208                            .getBroadcastItem(i);
25209                    try {
25210                        callback.onPermissionsChanged(uid);
25211                    } catch (RemoteException e) {
25212                        Log.e(TAG, "Permission listener is dead", e);
25213                    }
25214                }
25215            } finally {
25216                mPermissionListeners.finishBroadcast();
25217            }
25218        }
25219    }
25220
25221    private class PackageManagerNative extends IPackageManagerNative.Stub {
25222        @Override
25223        public String[] getNamesForUids(int[] uids) throws RemoteException {
25224            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25225            // massage results so they can be parsed by the native binder
25226            for (int i = results.length - 1; i >= 0; --i) {
25227                if (results[i] == null) {
25228                    results[i] = "";
25229                }
25230            }
25231            return results;
25232        }
25233
25234        // NB: this differentiates between preloads and sideloads
25235        @Override
25236        public String getInstallerForPackage(String packageName) throws RemoteException {
25237            final String installerName = getInstallerPackageName(packageName);
25238            if (!TextUtils.isEmpty(installerName)) {
25239                return installerName;
25240            }
25241            // differentiate between preload and sideload
25242            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25243            ApplicationInfo appInfo = getApplicationInfo(packageName,
25244                                    /*flags*/ 0,
25245                                    /*userId*/ callingUser);
25246            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25247                return "preload";
25248            }
25249            return "";
25250        }
25251
25252        @Override
25253        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25254            try {
25255                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25256                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25257                if (pInfo != null) {
25258                    return pInfo.versionCode;
25259                }
25260            } catch (Exception e) {
25261            }
25262            return 0;
25263        }
25264    }
25265
25266    private class PackageManagerInternalImpl extends PackageManagerInternal {
25267        @Override
25268        public void setLocationPackagesProvider(PackagesProvider provider) {
25269            synchronized (mPackages) {
25270                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25271            }
25272        }
25273
25274        @Override
25275        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25276            synchronized (mPackages) {
25277                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25278            }
25279        }
25280
25281        @Override
25282        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25283            synchronized (mPackages) {
25284                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25285            }
25286        }
25287
25288        @Override
25289        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25290            synchronized (mPackages) {
25291                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25292            }
25293        }
25294
25295        @Override
25296        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25297            synchronized (mPackages) {
25298                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25299            }
25300        }
25301
25302        @Override
25303        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25304            synchronized (mPackages) {
25305                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25306            }
25307        }
25308
25309        @Override
25310        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25311            synchronized (mPackages) {
25312                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25313                        packageName, userId);
25314            }
25315        }
25316
25317        @Override
25318        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25319            synchronized (mPackages) {
25320                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25321                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25322                        packageName, userId);
25323            }
25324        }
25325
25326        @Override
25327        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25328            synchronized (mPackages) {
25329                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25330                        packageName, userId);
25331            }
25332        }
25333
25334        @Override
25335        public void setKeepUninstalledPackages(final List<String> packageList) {
25336            Preconditions.checkNotNull(packageList);
25337            List<String> removedFromList = null;
25338            synchronized (mPackages) {
25339                if (mKeepUninstalledPackages != null) {
25340                    final int packagesCount = mKeepUninstalledPackages.size();
25341                    for (int i = 0; i < packagesCount; i++) {
25342                        String oldPackage = mKeepUninstalledPackages.get(i);
25343                        if (packageList != null && packageList.contains(oldPackage)) {
25344                            continue;
25345                        }
25346                        if (removedFromList == null) {
25347                            removedFromList = new ArrayList<>();
25348                        }
25349                        removedFromList.add(oldPackage);
25350                    }
25351                }
25352                mKeepUninstalledPackages = new ArrayList<>(packageList);
25353                if (removedFromList != null) {
25354                    final int removedCount = removedFromList.size();
25355                    for (int i = 0; i < removedCount; i++) {
25356                        deletePackageIfUnusedLPr(removedFromList.get(i));
25357                    }
25358                }
25359            }
25360        }
25361
25362        @Override
25363        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25364            synchronized (mPackages) {
25365                // If we do not support permission review, done.
25366                if (!mPermissionReviewRequired) {
25367                    return false;
25368                }
25369
25370                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25371                if (packageSetting == null) {
25372                    return false;
25373                }
25374
25375                // Permission review applies only to apps not supporting the new permission model.
25376                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25377                    return false;
25378                }
25379
25380                // Legacy apps have the permission and get user consent on launch.
25381                PermissionsState permissionsState = packageSetting.getPermissionsState();
25382                return permissionsState.isPermissionReviewRequired(userId);
25383            }
25384        }
25385
25386        @Override
25387        public PackageInfo getPackageInfo(
25388                String packageName, int flags, int filterCallingUid, int userId) {
25389            return PackageManagerService.this
25390                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25391                            flags, filterCallingUid, userId);
25392        }
25393
25394        @Override
25395        public ApplicationInfo getApplicationInfo(
25396                String packageName, int flags, int filterCallingUid, int userId) {
25397            return PackageManagerService.this
25398                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25399        }
25400
25401        @Override
25402        public ActivityInfo getActivityInfo(
25403                ComponentName component, int flags, int filterCallingUid, int userId) {
25404            return PackageManagerService.this
25405                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25406        }
25407
25408        @Override
25409        public List<ResolveInfo> queryIntentActivities(
25410                Intent intent, int flags, int filterCallingUid, int userId) {
25411            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25412            return PackageManagerService.this
25413                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25414                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25415        }
25416
25417        @Override
25418        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25419                int userId) {
25420            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25421        }
25422
25423        @Override
25424        public void setDeviceAndProfileOwnerPackages(
25425                int deviceOwnerUserId, String deviceOwnerPackage,
25426                SparseArray<String> profileOwnerPackages) {
25427            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25428                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25429        }
25430
25431        @Override
25432        public boolean isPackageDataProtected(int userId, String packageName) {
25433            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25434        }
25435
25436        @Override
25437        public boolean isPackageEphemeral(int userId, String packageName) {
25438            synchronized (mPackages) {
25439                final PackageSetting ps = mSettings.mPackages.get(packageName);
25440                return ps != null ? ps.getInstantApp(userId) : false;
25441            }
25442        }
25443
25444        @Override
25445        public boolean wasPackageEverLaunched(String packageName, int userId) {
25446            synchronized (mPackages) {
25447                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25448            }
25449        }
25450
25451        @Override
25452        public void grantRuntimePermission(String packageName, String name, int userId,
25453                boolean overridePolicy) {
25454            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25455                    overridePolicy);
25456        }
25457
25458        @Override
25459        public void revokeRuntimePermission(String packageName, String name, int userId,
25460                boolean overridePolicy) {
25461            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25462                    overridePolicy);
25463        }
25464
25465        @Override
25466        public String getNameForUid(int uid) {
25467            return PackageManagerService.this.getNameForUid(uid);
25468        }
25469
25470        @Override
25471        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25472                Intent origIntent, String resolvedType, String callingPackage,
25473                Bundle verificationBundle, int userId) {
25474            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25475                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25476                    userId);
25477        }
25478
25479        @Override
25480        public void grantEphemeralAccess(int userId, Intent intent,
25481                int targetAppId, int ephemeralAppId) {
25482            synchronized (mPackages) {
25483                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25484                        targetAppId, ephemeralAppId);
25485            }
25486        }
25487
25488        @Override
25489        public boolean isInstantAppInstallerComponent(ComponentName component) {
25490            synchronized (mPackages) {
25491                return mInstantAppInstallerActivity != null
25492                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25493            }
25494        }
25495
25496        @Override
25497        public void pruneInstantApps() {
25498            mInstantAppRegistry.pruneInstantApps();
25499        }
25500
25501        @Override
25502        public String getSetupWizardPackageName() {
25503            return mSetupWizardPackage;
25504        }
25505
25506        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25507            if (policy != null) {
25508                mExternalSourcesPolicy = policy;
25509            }
25510        }
25511
25512        @Override
25513        public boolean isPackagePersistent(String packageName) {
25514            synchronized (mPackages) {
25515                PackageParser.Package pkg = mPackages.get(packageName);
25516                return pkg != null
25517                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25518                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25519                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25520                        : false;
25521            }
25522        }
25523
25524        @Override
25525        public List<PackageInfo> getOverlayPackages(int userId) {
25526            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25527            synchronized (mPackages) {
25528                for (PackageParser.Package p : mPackages.values()) {
25529                    if (p.mOverlayTarget != null) {
25530                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25531                        if (pkg != null) {
25532                            overlayPackages.add(pkg);
25533                        }
25534                    }
25535                }
25536            }
25537            return overlayPackages;
25538        }
25539
25540        @Override
25541        public List<String> getTargetPackageNames(int userId) {
25542            List<String> targetPackages = new ArrayList<>();
25543            synchronized (mPackages) {
25544                for (PackageParser.Package p : mPackages.values()) {
25545                    if (p.mOverlayTarget == null) {
25546                        targetPackages.add(p.packageName);
25547                    }
25548                }
25549            }
25550            return targetPackages;
25551        }
25552
25553        @Override
25554        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25555                @Nullable List<String> overlayPackageNames) {
25556            synchronized (mPackages) {
25557                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25558                    Slog.e(TAG, "failed to find package " + targetPackageName);
25559                    return false;
25560                }
25561                ArrayList<String> overlayPaths = null;
25562                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25563                    final int N = overlayPackageNames.size();
25564                    overlayPaths = new ArrayList<>(N);
25565                    for (int i = 0; i < N; i++) {
25566                        final String packageName = overlayPackageNames.get(i);
25567                        final PackageParser.Package pkg = mPackages.get(packageName);
25568                        if (pkg == null) {
25569                            Slog.e(TAG, "failed to find package " + packageName);
25570                            return false;
25571                        }
25572                        overlayPaths.add(pkg.baseCodePath);
25573                    }
25574                }
25575
25576                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25577                ps.setOverlayPaths(overlayPaths, userId);
25578                return true;
25579            }
25580        }
25581
25582        @Override
25583        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25584                int flags, int userId) {
25585            return resolveIntentInternal(
25586                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25587        }
25588
25589        @Override
25590        public ResolveInfo resolveService(Intent intent, String resolvedType,
25591                int flags, int userId, int callingUid) {
25592            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25593        }
25594
25595        @Override
25596        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25597            synchronized (mPackages) {
25598                mIsolatedOwners.put(isolatedUid, ownerUid);
25599            }
25600        }
25601
25602        @Override
25603        public void removeIsolatedUid(int isolatedUid) {
25604            synchronized (mPackages) {
25605                mIsolatedOwners.delete(isolatedUid);
25606            }
25607        }
25608
25609        @Override
25610        public int getUidTargetSdkVersion(int uid) {
25611            synchronized (mPackages) {
25612                return getUidTargetSdkVersionLockedLPr(uid);
25613            }
25614        }
25615
25616        @Override
25617        public boolean canAccessInstantApps(int callingUid, int userId) {
25618            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25619        }
25620
25621        @Override
25622        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25623            synchronized (mPackages) {
25624                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25625            }
25626        }
25627
25628        @Override
25629        public void notifyPackageUse(String packageName, int reason) {
25630            synchronized (mPackages) {
25631                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25632            }
25633        }
25634    }
25635
25636    @Override
25637    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25638        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25639        synchronized (mPackages) {
25640            final long identity = Binder.clearCallingIdentity();
25641            try {
25642                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25643                        packageNames, userId);
25644            } finally {
25645                Binder.restoreCallingIdentity(identity);
25646            }
25647        }
25648    }
25649
25650    @Override
25651    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25652        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25653        synchronized (mPackages) {
25654            final long identity = Binder.clearCallingIdentity();
25655            try {
25656                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25657                        packageNames, userId);
25658            } finally {
25659                Binder.restoreCallingIdentity(identity);
25660            }
25661        }
25662    }
25663
25664    private static void enforceSystemOrPhoneCaller(String tag) {
25665        int callingUid = Binder.getCallingUid();
25666        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25667            throw new SecurityException(
25668                    "Cannot call " + tag + " from UID " + callingUid);
25669        }
25670    }
25671
25672    boolean isHistoricalPackageUsageAvailable() {
25673        return mPackageUsage.isHistoricalPackageUsageAvailable();
25674    }
25675
25676    /**
25677     * Return a <b>copy</b> of the collection of packages known to the package manager.
25678     * @return A copy of the values of mPackages.
25679     */
25680    Collection<PackageParser.Package> getPackages() {
25681        synchronized (mPackages) {
25682            return new ArrayList<>(mPackages.values());
25683        }
25684    }
25685
25686    /**
25687     * Logs process start information (including base APK hash) to the security log.
25688     * @hide
25689     */
25690    @Override
25691    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25692            String apkFile, int pid) {
25693        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25694            return;
25695        }
25696        if (!SecurityLog.isLoggingEnabled()) {
25697            return;
25698        }
25699        Bundle data = new Bundle();
25700        data.putLong("startTimestamp", System.currentTimeMillis());
25701        data.putString("processName", processName);
25702        data.putInt("uid", uid);
25703        data.putString("seinfo", seinfo);
25704        data.putString("apkFile", apkFile);
25705        data.putInt("pid", pid);
25706        Message msg = mProcessLoggingHandler.obtainMessage(
25707                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25708        msg.setData(data);
25709        mProcessLoggingHandler.sendMessage(msg);
25710    }
25711
25712    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25713        return mCompilerStats.getPackageStats(pkgName);
25714    }
25715
25716    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25717        return getOrCreateCompilerPackageStats(pkg.packageName);
25718    }
25719
25720    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25721        return mCompilerStats.getOrCreatePackageStats(pkgName);
25722    }
25723
25724    public void deleteCompilerPackageStats(String pkgName) {
25725        mCompilerStats.deletePackageStats(pkgName);
25726    }
25727
25728    @Override
25729    public int getInstallReason(String packageName, int userId) {
25730        final int callingUid = Binder.getCallingUid();
25731        enforceCrossUserPermission(callingUid, userId,
25732                true /* requireFullPermission */, false /* checkShell */,
25733                "get install reason");
25734        synchronized (mPackages) {
25735            final PackageSetting ps = mSettings.mPackages.get(packageName);
25736            if (filterAppAccessLPr(ps, callingUid, userId)) {
25737                return PackageManager.INSTALL_REASON_UNKNOWN;
25738            }
25739            if (ps != null) {
25740                return ps.getInstallReason(userId);
25741            }
25742        }
25743        return PackageManager.INSTALL_REASON_UNKNOWN;
25744    }
25745
25746    @Override
25747    public boolean canRequestPackageInstalls(String packageName, int userId) {
25748        return canRequestPackageInstallsInternal(packageName, 0, userId,
25749                true /* throwIfPermNotDeclared*/);
25750    }
25751
25752    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25753            boolean throwIfPermNotDeclared) {
25754        int callingUid = Binder.getCallingUid();
25755        int uid = getPackageUid(packageName, 0, userId);
25756        if (callingUid != uid && callingUid != Process.ROOT_UID
25757                && callingUid != Process.SYSTEM_UID) {
25758            throw new SecurityException(
25759                    "Caller uid " + callingUid + " does not own package " + packageName);
25760        }
25761        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25762        if (info == null) {
25763            return false;
25764        }
25765        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25766            return false;
25767        }
25768        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25769        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25770        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25771            if (throwIfPermNotDeclared) {
25772                throw new SecurityException("Need to declare " + appOpPermission
25773                        + " to call this api");
25774            } else {
25775                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25776                return false;
25777            }
25778        }
25779        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25780            return false;
25781        }
25782        if (mExternalSourcesPolicy != null) {
25783            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25784            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25785                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25786            }
25787        }
25788        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25789    }
25790
25791    @Override
25792    public ComponentName getInstantAppResolverSettingsComponent() {
25793        return mInstantAppResolverSettingsComponent;
25794    }
25795
25796    @Override
25797    public ComponentName getInstantAppInstallerComponent() {
25798        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25799            return null;
25800        }
25801        return mInstantAppInstallerActivity == null
25802                ? null : mInstantAppInstallerActivity.getComponentName();
25803    }
25804
25805    @Override
25806    public String getInstantAppAndroidId(String packageName, int userId) {
25807        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25808                "getInstantAppAndroidId");
25809        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25810                true /* requireFullPermission */, false /* checkShell */,
25811                "getInstantAppAndroidId");
25812        // Make sure the target is an Instant App.
25813        if (!isInstantApp(packageName, userId)) {
25814            return null;
25815        }
25816        synchronized (mPackages) {
25817            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25818        }
25819    }
25820
25821    boolean canHaveOatDir(String packageName) {
25822        synchronized (mPackages) {
25823            PackageParser.Package p = mPackages.get(packageName);
25824            if (p == null) {
25825                return false;
25826            }
25827            return p.canHaveOatDir();
25828        }
25829    }
25830
25831    private String getOatDir(PackageParser.Package pkg) {
25832        if (!pkg.canHaveOatDir()) {
25833            return null;
25834        }
25835        File codePath = new File(pkg.codePath);
25836        if (codePath.isDirectory()) {
25837            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25838        }
25839        return null;
25840    }
25841
25842    void deleteOatArtifactsOfPackage(String packageName) {
25843        final String[] instructionSets;
25844        final List<String> codePaths;
25845        final String oatDir;
25846        final PackageParser.Package pkg;
25847        synchronized (mPackages) {
25848            pkg = mPackages.get(packageName);
25849        }
25850        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25851        codePaths = pkg.getAllCodePaths();
25852        oatDir = getOatDir(pkg);
25853
25854        for (String codePath : codePaths) {
25855            for (String isa : instructionSets) {
25856                try {
25857                    mInstaller.deleteOdex(codePath, isa, oatDir);
25858                } catch (InstallerException e) {
25859                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25860                }
25861            }
25862        }
25863    }
25864
25865    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25866        Set<String> unusedPackages = new HashSet<>();
25867        long currentTimeInMillis = System.currentTimeMillis();
25868        synchronized (mPackages) {
25869            for (PackageParser.Package pkg : mPackages.values()) {
25870                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25871                if (ps == null) {
25872                    continue;
25873                }
25874                PackageDexUsage.PackageUseInfo packageUseInfo =
25875                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25876                if (PackageManagerServiceUtils
25877                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25878                                downgradeTimeThresholdMillis, packageUseInfo,
25879                                pkg.getLatestPackageUseTimeInMills(),
25880                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25881                    unusedPackages.add(pkg.packageName);
25882                }
25883            }
25884        }
25885        return unusedPackages;
25886    }
25887}
25888
25889interface PackageSender {
25890    void sendPackageBroadcast(final String action, final String pkg,
25891        final Bundle extras, final int flags, final String targetPkg,
25892        final IIntentReceiver finishedReceiver, final int[] userIds);
25893    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25894        boolean includeStopped, int appId, int... userIds);
25895}
25896